Zelos Malum
Zelos Malum

Reputation: 113

Using a table for variable name in a table is not found when called for

I am making quite the complex thing and I am trying to use tables as variable names cause I have found that lua works with it, that is:

lua
{[{1,2}]="Meep"}

The issue is it is callable, when I do it and try to call it using the same kind of table, it won't find it.

I have tried looking for it and such but I have no clue why it won't do this.

ua
local c = {[{1,2}]="Meep"}
print(c[{1,2}],c)

Do I expect to become but it does not.

"Meep",{[{1,2}]="Meep"}

but what I get is

nil,{[{1,2}]="Meep"}

If I however try

lua
local m={1,2}
local c = {[m]="Meep"}
print(c[m],c)

it becomes the correct one, is there a way to avoid that middle man? After all m=={1,2} will return true.

Upvotes: 1

Views: 142

Answers (1)

Phisn
Phisn

Reputation: 881

The problem you have is that tables in lua are represented as references. If you compare two different talbes you are comparing those references. So the equation only gets true if the given tables are exactly the same.

t = { 1, 2, 3 }
t2 = { 1, 2, 3 }
print(t == t) -- true
print(t2 == t) -- false
print(t2 == t2) -- true

Because of this fact, you can pass them in function per reference.

function f(t)
    t[1] = 5
end

t2 = { 1 }
f(t2)
print(t2[1]) -- 5

To bypass this behavior, you could (like suggested in comments) serialize the table before using it as a key.

Upvotes: 2

Related Questions