r/lua • u/yughiro_destroyer • 3d 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?
9
u/GroundbreakingCup391 2d ago
Flat tables get more cognitively expensive when you want to retrieve data.
Imagine you want to check the player's full data for debug :
In the non-nested case, when you'd add a new player-related variable, you would also have to add it manually to
dumpPlayerTable.On another note, autocorrect is handy, but sometimes I'd just forget how a variable is even named and I'd have to look back in the code anyways.
6
u/kcx01 2d ago
I think both have valid uses. In your example I prefer
player = {pos = {x = 5, y = 5}}}But I probably wouldn't write it that way. In this case I'd definitely want to do oop (or luas version anyway). But the reason that I prefer the nested table is I think it's a cleaner more organized data structure. Imagine 10 players, tracking them individually like that would be horrible.
Plus
player.pos.x = 15is very ergonomic and keeps good namespace. It's also easy to assign whole vectorslocal v = {x= 3, y= 7}then laterplayer.pos = vMethods also get better turning this into oop.
function player:move(x, y) self.pos.x + x self.pos.y + y end
Flat tables are still very helpful, and I use them all the time, but whenever things become more complex, I think nested reads better and leads to cleaner code.
Your ide shouldn't have any issues auto completing dotted notation, but, you can also use something like lua_ls to help your ide with typing hints btw.
1
u/NaturalHour544 1d ago edited 1d ago
I think both have their place depending on how the data is used. For something like player health, speed or other frequently accessed values, a flat structure makes sense and is probably easier to work with
Nested tables become more useful when you have multiple related properties that need to be passed around together. For example, I'd rather pass an entire position table to a function than pass separate x, y and z values every time
I do agree about the debugging part though. Deeply nested tables can become a nightmare, especially when you come back to a project after a few weeks. I think keeping nesting to a reasonable depth is a good compromise rather than sticking exclusively to one approach
3
u/vga256 2d ago edited 2d ago
I exclusively use nested tables, because it greatly simplifies serialization for game/application state saves. All of my objects (tables) are arranged in a large tree, and I can recursively save the state of the entire game by calling object.save() at the bottom of the tree, and letting the serialize function automatically work its way through every sub-table.
(Similarly, de-serializing automatically rebuilds the object with all of its sub-tables without any extra work.)
Keeping track of individual tables in a flat structure for serialization isn't much fun. That being said, for simple calculations inside of functions, I do use flat structures for all kinds of processing. But if it's an object with any kind of permanence or complexity in the game, it is a nested structure.
3
u/ConsciousBath5203 2d ago
Use types.
Sumneko is the vscode plugin that I use to make it readable and easy to work with
2
u/immortalx74 2d ago
I do heavy use of nested tables and even complex mixed ones (with array + hash parts, and even methods) and never had an issue with it. In fact that's what attracted me to Lua. I treat them sort of like C/C++ structs.
Also, I'm using VSCode and autocomplete works on my end.
I understand the simplicity of using "bare" variables but once a project becomes complex enough, it's hard to organize your code without grouping them into little "boxes".
2
u/unburdened_swallow 2d ago edited 2d ago
I think of it in 2 ways. 1, mutability. If you want to pass something somewhere and have them change it and you see the changes, it should be in its own table, and which table it is in should remain the same. 2, prefer flat to avoid extra indexing, but what things am I going to want to pass around together? Might be helpful and faster to not collect them into a new table every time, or have to grab all N of them and pass them to a function vs just passing the table.
Both of these ways of thinking produce similar code. I would do player.pos probably, unless they leave my module and I want to not have them changed, then I would have x and y separate most likely and definitely pass them separate, or at least put them in a new table first.
Like, the function that needs the position though is probably going to need both of them and ALSO other stuff. If you are also writing that function, you probably want to pass the pos table rather than have a million arguments. Especially if you want them to change them for you. So having them already in the table to pass makes sense. Whereas if you don’t want them to change them, pass it separately and they can’t change your copy.
Mutability and avoiding repeated indexing are usually the main concerns.
Like, if you need to pass 5 things often, that’s 5 indexes, vs as 1 table, that is 1. But also, then the receiver can modify your copy, so that’s the counterpoint.
Programmer convenience is not as much of a concern. Lua and the computer in general work the way they work, regardless of your feelings.
Too nested can be painful but also you usually don’t need to get too nested, and you can define a function to safely index nested values, and store intermediate results and stuff, it’s fine.
2
u/4xe1 2d ago
Clean code is not the reason they were doing it, lack/inefficiency of tables/OOP was.
It is not. It is how a computer likes to think, but this should not affect you much.
This may be true in C, C++, C# or Rust, and maybe in lua JIT if you're lucky, but not in lua. In lua, the computer thinks exactly like you tell it to. A flat table will be a flat table, and a nested table will be a nested table. In particular, each path have its own pointer and your struct has no guaranty to be packed, quite the opposite. That's one more reasons to use flat tables I guess, as they'll have less indirections, but if you're after performance, both will be worse than an array or a struct (which you can make in C and use in lua).
Also, if the computer flattens your struct either way in compiled languages (and you can even view the same region of memory as both flat or nested in languages like Rust and COBOL and likely many more), then it precisely means you the computer is optimizing so that you don't have to choose what you want to do based what it is doing.
1
u/PhilipRoman 2d ago
I prefer flat tables, although they are not convenient with Lua, since you need to concatenate strings for the keys. If we had immutable tuples, you could do
1
u/coverdr1 2d ago
A third option that I often use is a delegate chain using metatables. That way objects can have a default state at the base of the chain and custom values are only used if they deviate from the default. Types of key/value pairs can be logically grouped in each of the metatables, yet they can all be accessed via a single level index. Assigning a key/value supersedes but does not overwrite the base value
1
u/xoner2 2d ago edited 2d ago
Gotta get good at table serialization fu. Start with this: https://github.com/pkulchenko/serpent
I use a modified version of that. A powerful feature of Lua is you can examine entire program state just by dumping a table serialization to file. I miss this when working in c++.
So when reworking a program you haven't touched in a while and forgotten how it works; dump a few tables and you're back on track.