Trying to work with 3d tables, but I'm having issues. I simplified my code to just the part that deals with tables, so it should be readable

Table3D = {}
Table3D.Row1 = {}
Table3D.Row2 = {}
CurrentRow = "Row1"

for x = 5,10,1 do
	Table3D[CurrentRow][x] = {}
	print(table.getn(Table3D[CurrentRow])) --this prints 0 6 times in a row
end

Every time I add an empty table to Table3D.Row1, it should update the length, but it doesn't. However, when I change the for loop to start at 1 instead of 5, it updates the length properly each time. Any suggestions?

10 comments

0

My first guess would be that you're trying to access index 5 when there aren't any elements occupying the first 4 indices; it wouldn't make sense to start inserting tables at the 5th index, not to me at least, when the first 4 indices aren't already occupied by elements.

0

The thing about Lua tho is that tables are key value pairs, not normal arrays. This code is simplified, in my actual example keys are random coordinates so I can't place them in numerical order. You might be right, but it would suck if Lua just be like that

0

If you look at your code, you're starting at the index 5 and not 1. By using a number to index the table, you're... well, using an index, and not a key(if we want to make the terms have two different definitions). I'm pretty sure you can't just skip the first 4 indices. I don't see why you would need to anyways.

0

It's the same reason people don't just use a player's user ID to store data in data stores. It would think that their user ID is the numeric position of the element in the dictionary. People just concatenate a string to their user ID to combat this for that reason.

0

Welp I just read how the table.getn, it automatically stops on the first nil element so I just need to manually keep track of size, I'm blaming all my issues on Lua being a garbage language with bad data structures and not the fact that I'm bad at programming

0

Is there a particular reason you're skipping over the first 4 indices? Also, you can just put a number sign before a table to return the number of elements in it, as opposed to using a more difficult-to-type function like table.getn.

0

Also, Lua has arrays and dictionaries; lists aren't strictly key-value pairs. If you just create a table and insert elements, it assigns indices to those elements(1, 2, 3, etc), unless you manually assign keys to those elements.

0

what I see: {{{},{},{},{},{},{}},{}}

0

from 5-10, incrementing by one, you are getting tables and so everything is working out, I don't see what the problem is

0

I tested out using #, and it has the same behavior as table.getn. I'm skipping over indices here cause its a simplified example of what I'm actually doing, which is storing coordinates of certain parts, and the coordinates don't start at 1 and go up, so normal array indexing won't work for me. The code adds elements to the table under the proper indices, getting size is the only issue.