problem with variables and tables

Hi everyone! I just started to learn Lua and have a question.

For example I have a database with information about a player. This database is a table. Then I created a variable hero and want to put all information from database to this variable. But I need them to be as a variables inside a hero. Like hero.name. How it is possible to do?

--\> database.lua local heroInfo = { name = "hero", } return heroInfo --------------------- --\> hero.lua hero = display.newCircle (0,0, 10) heroInfo = require ("database") for key, value in pairs (heroInfo) do hero.key = value end print (hero.name) --\> got nil print (hero.key) --\> "hero" ----------------------  

Is it possible to name a variable by the name of key? Thank You!!

Anton Shekhov

There are two ways of accessing a table’s value (probably more, but there are two that I know of). The first is what you’re doing:

[lua]

thisTable.thisKey = thisValue

[/lua]

The second way is with brackets:

[lua]

thisTable[“thisKey”] = thisValue

[/lua]

If you have a string or a number (I’m not sure about Boolean or table keys) you can use it as a key simply by putting the variable name between the brackets:

[lua]

for key, value in pairs (heroInfo) do

    hero[key] = value

end

[/lua]

Hope this helps!

Caleb :slight_smile:

Thank you!! It is really helped! :slight_smile:

There are two ways of accessing a table’s value (probably more, but there are two that I know of). The first is what you’re doing:

[lua]

thisTable.thisKey = thisValue

[/lua]

The second way is with brackets:

[lua]

thisTable[“thisKey”] = thisValue

[/lua]

If you have a string or a number (I’m not sure about Boolean or table keys) you can use it as a key simply by putting the variable name between the brackets:

[lua]

for key, value in pairs (heroInfo) do

    hero[key] = value

end

[/lua]

Hope this helps!

Caleb :slight_smile:

Thank you!! It is really helped! :slight_smile: