Col_Blimp
Col_Blimp

Reputation: 789

Creating a table with a string name

I've created a lot of string variable names and I would like to use the names as table names ie:

 sName1 = "test"
 sName2 = "test2"

 tsName1 ={} -- would like this to be ttest ={}
 tsName2 ={} -- ttest2 = {}

I can't figure out how to get this to work, have gone through various combinations of [] and .'s but on running I always get an indexing error, any help would be appreciated.

Upvotes: 0

Views: 373

Answers (2)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39370

In addition to using _G, as Mike suggested, you can simply put all of these tables in another table:

tables = { }
tables[sName1] = { }

While _G works the same way pretty much every table does, polluting global "namespace" isn't much useful except for rare cases, and you'll be much better off with a regular table.

Upvotes: 5

Mike Corcoran
Mike Corcoran

Reputation: 14565

your question is sort of vague, but i'm assuming you want to make tables that are named based off of string variables. one way would be to dynamically create them as global objects like this:

local sName1 = "test"

-- this creates a name for the new table, and creates it as a global object
local tblName = "t".. sName1
_G[tblName] = {}

-- get a reference to the table and put something in it.
local ttest = _G[tblName]
table.insert(ttest, "asdf")

-- this just shows that you can modify the global object using just the reference
print(_G[tblName][1])

Upvotes: 3

Related Questions