I have a similar problem when using an if statement to check if nested table is empty:
Table = {}
if Table[3][8][2] == nil then
print("Hello world!")
end
This is the exact same problem, and errors with:
The only solution to this i can think of is doing this:
Table = {}
if Table[3] == nil then
print("Hello world!")
elseif Table[3][8] == nil then
print("Hello world!")
elseif Table[3][8][2] == nil then
print("Hello world!")
end
but that gets bigger and bigger the more nested tables you have, and it probably isn’t the most efficient or clean solution.
local function nestedIndex(t, ...)
local a = {...}
local i = table.remove(a, 1)
local v = t[i]
return if type(v) == "table" and #a > 0 then nestedIndex(v, table.unpack(a)) else v
end
local t = {{}, {}, {{math.pi}, {}, {}}}
local v = nestedIndex(t, 3, 1, 1)
print(v) --3.14...
local v2 = nestedIndex(t, 4, 1, 1) --Out of range.
print(v2) --nil
The term nested tables is a bit abstruse. It’s just arrays of arrays, tables inside tables. It helps to note that you aren’t necessarily defining a table in your example with Table[1] = {[2] = {[3] = "String"}}.
In Lua, tables and dictionaries are actually the same, it’s called an array; there’s only one data structure. With that in mind, your example wasn’t working because all of your useful data is going to be at the bottom of each trace as each row stores arrays and arrays only.
You can get around this by skipping over them by an even sequence but that could be pretty strange to for loop with. It’s also helpful to note that doing this is not necessarily the most efficient and is fine when the you arent indexing more than twice imo, in a 3 index example if it were in a batch array it would be 300% faster. A more optimized way would be to use a batched array (which would also solve your problem with you losing the data if this is to expand on an already existing system)