0

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.

1
  • If you want to do this, then you've almost certainly approached the problem in the wrong way. Commented May 30, 2013 at 21:14

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.