Reputation: 2018
For example I loaded a module, and there is a table in this module with name "Table1". In the main file I have a table which I want to be the exact same copy of "Table1". So how can I do it, if I have only a name of that table. When I am trying to do it like this
str = "Table1"
t = str
I obviously get a string instead of table, so how can I get a table content that table content? What I want is to able somehow make this line of code
t = 'Table1'
be equvalent to this one
t = Table1
Upvotes: 2
Views: 775
Reputation: 16753
Tables in Lua are a very flexible and important datatype. So much, that even modules are tables. If you know, that there is a table by a given name in the module, and you have it's name in a variable, just use the []
operator to get the table:
tablename = 'Table1' -- you get this from somewhere, assuming it's not fixed
require 'mymodule'
t = mymodule[tablename]
However, this is not a very good approach, because it assumes that you "know" that the module contains a table by the given name. You can always design modules that will export the table by a given standard name (which does not change):
require 'mymodule'
t = mymodule.Table1 -- equivalent to mymodule['Table1']
Upvotes: 2
Reputation: 72412
If str
is the name of a global variable, use _G[str]
to get its value.
Upvotes: 2