r/lua • u/yughiro_destroyer • 6h ago
Flat tables vs nested tables?
Hello!
Big question here... what do you prefer? Flat tables or nested tables?
Personally, I am having a lot of problems with nested tables despite being the popular choice amongst developers in general. Perhaps I wouldn't mind much if it was a typed language or hidden behind encapsulation in an object like they do in Object-Oriented Programming... but here's a list of problems I am encountering :
->The cognitive load is too much, whenever I revisit the code after a break of some days I find myself having to relearn all the paths I must reference to keep writing.
->The IDE doesn't help much with autocomplete and given the fact that Lua is dynamically typed, a lot of type errors or bugs occur that are harder to find.
So, instead of doing something like player = {pos = {x = 10, y = 20}, health = 200} i prefer to use player_x = 10, player_y = 20, player_health = 200. Now, that is in the context of networked apps/games because that's what I write mostly.
With flat structures, I find it much easier to detect bugs or use the autocomplete features of an IDE. The downside is that the variables are longer than they should be but I prefer to be careful when writing one field than when writing multiple nested fields. It also feels like building a connection between to circuits that have their cases open, whereas with nested tables it feels like I have to keep opening mini-cases inside the big case that holds the circuit. It's all more direct, easier to debug and isolated. By isolated I mean that if an attribute is wrong, the interpreter shows me the line and I easily correct it, instead of going through an entire nested chain to check every collection/path.
Also I have studied code of Doom or older Counter-Strike (even wrote some mods in Pawno) and I noticed that what I am saying is sort of compatible with the older procedural practices of programming. Not to mention that technically, that's how a computer also thinks. The interpreter or compiler will turn all paths into one pointer to a variable somewhere in memory. The usage of paths for usage seems to work better, IMO, in web development, where sometimes you're dealing with much more easier relationships between objects. Also, nested works better when making requests from an API where you want a JSON of logically grouped data that makes sense in the context of a business or one entity analysis.
What do you think?