【问题标题】:Creating Lua Advanced Table创建 Lua 高级表
【发布时间】:2011-10-07 11:16:09
【问题描述】:

需要创建一些表,以便我可以通过这种方式从中获取信息:

table[attacker][id]

如果我会使用

print(table[attacker][id])

它应该打印

尝试了很多方法,但没有找到任何好的......

我想应该是这样的……

table.insert(table, attacker, [id] = value)

^ 这不起作用。

有人可以帮我吗?


编辑

好吧,当我这样尝试时:

x = {}
function xxx()
    if not x[attacker][cid] then
        x[attacker][cid] = value
    else
        x[attacker][cid] = x[attacker][cid] + value
    end
    print(x[attacker][cid])
end

我收到一条错误消息:

尝试索引字段“?” (零值)

【问题讨论】:

  • 那个错误的意思正是它所说的......x[attacker]显然是nil

标签: multidimensional-array insert lua lua-table


【解决方案1】:

你需要花括号来创建内表:

table.insert(my_table, attacker, {[id]=value})

-- the advantage of this is that it works even if 'attacker' isn't a number
my_table[attacker] = {[id]=value}

a = 1
b = 2
c = 3
d = {}
table.insert(d, a, {[b]=c})
print(d[a][b]) -- prints '3'

【讨论】:

  • 这仅适用于attacker 是整数,因为 table.insert 仅适用于将值插入表的数组部分。
  • 当然。当然,普通的表赋值语法也适用于非整数键;我只是将 OP 的示例调整为最接近可行的方法。
  • 顺便说一句。攻击者总是一个整数,
【解决方案2】:

attacker 是什么?也就是说,它包含什么值? 真正它包含什么并不重要,因为 Lua 表可以使用任何 Lua 值作为键。但知道会很有用。

无论如何,这真的很简单。

tableName = {}; --Note: your table CANNOT be called "table", as that table already exists as part of the Lua standard libraries.
tableName[attacker] = {}; --Create a table within the table.
tableName[attacker][id] = value; --put a value in the table within the table.

您的编辑出现问题是因为您没有注意上面的第 2 步。 Lua 表中的值在有值之前都是空的(nil)。因此,直到第 2 行,tableName[attacker]nil。您不能索引 nil 值。因此,您必须确保您希望索引到的 tableName 中的任何键都是事实表。

换句话说,除非你知道type(tableName[attacker]) == "table" 是真的,否则你不能做tableName[attacker][id]

【讨论】:

    【解决方案3】:

    你应该使用table = {['key']='value'} 会更容易。

    【讨论】:

      猜你喜欢
      • 2014-06-18
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多