Lua:“对”不迭代 [1]

发布于 2024-12-08 01:46:34 字数 759 浏览 1 评论 0原文

我很快就必须调试一些东西,并编写了以下函数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画尸师 2024-12-15 01:46:34

问题出在内表上。你没有给它一个键,这意味着Lua会给它一个数组索引。即1。这将覆盖您用于 "hello??"[1] 键。因此,您需要为该表值指定一个适当的键,或者您需要停止对其他表值使用整数键。

或者,换句话说,以下两个表是相同的:

{"first", "second", "third"}

{[3] = "third", [2] = "second", "first"} --Note the lack of a key for "first".

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:

{"first", "second", "third"}

{[3] = "third", [2] = "second", "first"} --Note the lack of a key for "first".
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文