【问题标题】:Creating a table with a string name使用字符串名称创建表
【发布时间】:2013-05-29 22:00:55
【问题描述】:

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

 sName1 = "test"
 sName2 = "test2"

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

我不知道如何让它工作,已经经历了 [] 和 . 的各种组合,但是在运行时我总是遇到索引错误,任何帮助将不胜感激。

【问题讨论】:

  • 如果你想这样做,那么你几乎肯定是以错误的方式解决问题。

标签: lua


【解决方案1】:

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

tables = { }
tables[sName1] = { }

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

【讨论】:

    【解决方案2】:

    您的问题有点含糊,但我假设您想创建基于字符串变量命名的表。一种方法是将它们动态地创建为像这样的全局对象:

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

    【讨论】:

      猜你喜欢
      • 2013-04-12
      • 2013-08-21
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      相关资源
      最近更新 更多