Lua:“对”不迭代 [1]
我很快就必须调试一些东西,并编写了以下函数:
function dumpTable(t)
for i,v in pairs(t) do
if type(v) == "table" then
dumpTable(v)
else
print(i..":", v)
end
end
end
现在,由于某种原因,
dumpTable({[1]="hello??", [2]="two", {[132]="something", [3.2]="else"}})
输出
132: something
3.2: else
2: two
注意到第一个字符串是如何丢失的?但是如果我改变它的键..
dumpTable({["one"]="hello??", [2]="two", {[132]="something", [3.2]="else"}})
它输出
132: something
3.2: else
one: hello??
2: two
This is so unintuitive我几乎感觉自己像个白痴没有看到错误..
(顺便说一句。我确实知道如果表包含递归引用,我的函数将溢出堆栈,稍后会解决这个问题)
I quickly had to debug something, and wrote following function:
function dumpTable(t)
for i,v in pairs(t) do
if type(v) == "table" then
dumpTable(v)
else
print(i..":", v)
end
end
end
Now, for some reason
dumpTable({[1]="hello??", [2]="two", {[132]="something", [3.2]="else"}})
outputs
132: something
3.2: else
2: two
notice how the first string is missing? But if I change its key..
dumpTable({["one"]="hello??", [2]="two", {[132]="something", [3.2]="else"}})
it outputs
132: something
3.2: else
one: hello??
2: two
This is so unintuitive I almost feel like making an idiot of myself not seeing the mistake..
(btw. I do know that my function will overflow the stack if the table contains a recursive reference, going to fix that later)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题出在内表上。你没有给它一个键,这意味着Lua会给它一个数组索引。即
1
。这将覆盖您用于"hello??"
的[1]
键。因此,您需要为该表值指定一个适当的键,或者您需要停止对其他表值使用整数键。或者,换句话说,以下两个表是相同的:
The problem is the inner table. You didn't give it a key, which mean that Lua will give it an array index. Namely,
1
. Which will overwrite the[1]
key you used for"hello??"
. So you need to give this table value a proper key, or you need to stop using integer keys for the others.Or, to put it another way, the following two tables are identical: