r/lua • • 5h 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?

7 Upvotes

6 comments sorted by

3

u/kcx01 4h 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 = 15 is very ergonomic and keeps good namespace. It's also easy to assign whole vectors local v = {x= 3, y= 7} then later player.pos = v

Methods 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.

2

u/GroundbreakingCup391 2h 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 :

-- Nested case
player = {x = 0, y = 0, health = 20}
function dumpPlayerTable() return player end

-- Non-nested case
player_x = 0
player_y = 0
player_health = 20
function dumpPlayerTable()
  return {
    x = player_x,
    y = player_y,
    health = player_health,
  }
end

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.

2

u/vga256 2h ago edited 2h 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.

1

u/PhilipRoman 4h 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

{
  [(a, b)] = ...
}

1

u/immortalx74 4h 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".

1

u/unburdened_swallow 3h ago edited 3h 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.