Search code examples
lualua-table

Lua, using table of strings as keys to call values from different tables


What I want

ores = {"Bauxite", "Coal", "Hematite"}

properties={["Bauxite"]={name="Bauxite", density=1.2808},["Coal"]={name="Coal" , density=1.3465},["Quartz"]={name="Quartz" , density=2.6498},["Hematite"]={name="Hematite" , density=5.0398}}

system.print(properties.ores[1].name)
system.print(properties.ores[1].density)

Should Output

Bauxite
1.2808

Solution

  • This is a recurrent question regarding indexing tables by a value rather than by a constant string. You're currently using ((properties.ores)[1]).name; this is not parsed as properties.(ores[1]).name as you seem to have expected. That's because . is always followed by an identifier - a constant string - which is used to index the table. table.key is just shorthand for table["key"] for keys matching [a-zA-Z_][a-zA-Z0-9_]*. If you want to dynamically index a table with some expression, you have to use table[expr].

    To fix your code, simply do:

    system.print(properties[ores[1]].name)
    system.print(properties[ores[1]].density)