创建Lua高级表
需要创建一些表,以便我可以通过以下方式从中获取信息:
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
我收到一条错误消息:
尝试索引字段“?” (零值)
Need to create some table so I can get an info from it in this way:
table[attacker][id]
And if I'll use
print(table[attacker][id])
It should print the value.
Tried many ways, but haven't found any good ...
I guess it should be something like this...
table.insert(table, attacker, [id] = value)
^ This does not work.
Can someone help me?
Edit
Well, when I try it this way:
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
I get an error saying:
attempt to index field '?' (a nil value)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要花括号来创建内部表:
或
You need the curly braces to create the inner table:
or
什么是
攻击者
?也就是说,它包含什么价值?它包含什么并不重要,因为 Lua 表可以使用任何 Lua 值作为键。但了解一下会有用。无论如何,这真的很简单。
您编辑中出现的问题是因为您没有注意上面的步骤 2。 Lua 表中的值在有值之前都是空的 (nil)。因此,直到第 2 行,
tableName[attacker]
为nil。您不能对 nil 值建立索引。因此,您必须确保您希望索引到的tableName
中的任何键实际上都是表。换句话说,除非您
知道
type(tableName[attacker]) == "table"<,否则您无法执行
tableName[attacker][id]
/代码> 是正确的。What is
attacker
? That is, what value does it contain? It doesn't really matter what it contains since Lua tables can use any Lua value as a key. But it would be useful to know.In any case, it's really simple.
The problem in your edit happened because you didn't take note of step 2 above. Values in a Lua table are empty (nil) until they have a value. Therefore, until line 2,
tableName[attacker]
is nil. You cannot index a nil value. You therefore must ensure that any keys intableName
that you expect to index into are in fact tables.To put it another way, you cannot do
tableName[attacker][id]
unless you know thattype(tableName[attacker]) == "table"
is true.您应该使用
table = {['key']='value'}
更容易。you should use
table = {['key']='value'}
makes it easier.