Tarass
Tarass

Reputation: 131

Lua : Storing in a table through a variable name

I understand why this mwe doesn't work but I don't know how make it works. I'd like to use the variable content as reference name (not the variable name).

salade = {}

name = "tomato"

salade.name = "red"

print (salade.tomato)   -- nil, should be red 
print (salade.name)     -- red, should be nil

Upvotes: 1

Views: 43

Answers (1)

Sneftel
Sneftel

Reputation: 41474

Just use the normal table indexing syntax, rather than the tbl.key syntactic sugar:

salade = {}
name = "tomato"
salade[name] = "red"

print (salade.tomato)   -- red
print (salade.name)     -- nil

Upvotes: 1

Related Questions