How do I index nested tables?

Normally you would be able to do something like this:

Table = {}

Table[1] = "string"

But when try this on a nested table:

Table = {}

Table[1][2][3] = "string"

I get this error:

I could fix it by doing this:

Table = {}

Table[1] = {[2] = {[3] = "String"}}

But then I lose everything that is already in the table, this:

Table = {[1] = "OtherString"}

Table[1] = {[2] = {[3] = "String"}}


Would delete the otherstring entirely.

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!")

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!")

but that gets bigger and bigger the more nested tables you have, and it probably isn’t the most efficient or clean solution.

So, how should I tackle this?

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

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
1 Like

I am very sorry for the super late response, some things got in the way…

Could you explain this a bit more? Are the three numbers you are passing as parameters the indexes? And how does it work (roughly)?

I’ve been trying to understand it for a while but I don’t really get it.

Thanks in advance!

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)

1 Like