使用字符串名称创建表

时间:2013-05-29 13:16:53

标签: lua

我创建了很多字符串变量名,我想将这些名称用作表名,即:

 sName1 = "test"
 sName2 = "test2"

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

我无法弄清楚如何让它工作,经历了[]和。的各种组合,但在运行时我总是得到一个索引错误,任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:5)

除了使用_G之外,正如Mike建议的那样,您可以简单地将所有这些表放在另一个表中:

tables = { }
tables[sName1] = { }

虽然_G几乎每个表都以相同的方式工作,但是除了极少数情况之外,污染全局“命名空间”并不是很有用,并且使用常规表会更好。

答案 1 :(得分:3)

你的问题有点模糊,但我假设你想要创建基于字符串变量命名的表。一种方法是将它们动态创建为全局对象,如下所示:

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