Referencing a table through a string in Lua

Asked

Viewed 75 times

3

I need to use a table in Lua, but I can only reference it through a string, example:

tabelaA = { "qualquer coisa" }
variavelA = "tabelaA"

print(variavelA)
resultado: "qualquer coisa"

Bearing in mind that I have no way to reference this table directly, I will get the string name.

1 answer

3

Exists the table _G, called the global environment, representing the existing variables:

> print(tabelaA[1])
qualquer coisa
> print(_G["tabelaA"][1])
qualquer coisa

Also, you can always build another table:

tabelaVariaveis = {}
tabelaVariaveis["tabelaA"] = tabelaA

-- e pode acrescentar mais
tabelaB = { "outra coisa" }
tabelaVariaveis["tabelaB"] = tabelaB

and use it:

> print(tabelaVariaveis["tabelaA"][1])
qualquer coisa
  • Thank you very much, Dan Getz !

  • @arthurgps2 tried your suggestion, but print(shared["tabelaA"][1]) did not work here (Lua 5.1.5). Please explain more?

  • There is also _ENV. _ENV and _G are by default the same table, only _ENV is the most commonly used by Lua, for example, when you try to access a non-local name/identifier, Lua takes the current value of _ENV and takes the field with that name. Only Lua 5.2+ supports _ENV (Luajit).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.