Lua中的奇怪表错误。

好的,所以我有一个关于以下 Lua 代码的奇怪问题:

function quantizeNumber(i, step)
    local d = i / step
    d = round(d, 0)
    return d*step
end

bar = {1, 2, 3, 4, 5}

local objects = {}
local foo = #bar * 3
for i=1, #foo do
    objects[i] = bar[quantizeNumber(i, 3)]
end
print(#fontObjects)

运行此代码后,objects 的长度应该是 15,对吗?但不是,它是 4。这是如何工作的,我错过了什么?

谢谢,Elliot Bonneville。

原文链接 https://stackoverflow.com/questions/7200705

点赞
stackoverflow用户831878
stackoverflow用户831878

是的,答案是 4。

根据 Lua 参考手册的定义:

表 t 的长度被定义为任何整数索引 n,使得 t[n] 不为 nil,且 t[n+1] 为 nil;此外,如果 t[1] 为 nil,则 n 可以为零。对于一个普通数组,其非 nil 值从 1 到给定 n,它的长度恰好为 n,即其最后一个值的索引。如果数组有“空洞”(即在其它非 nil 值之间存在 nil 值),那么 #t 可以是直接在 nil 值前面的任何索引(也就是说,它可以将任何这样的 nil 值视为数组的结尾)。

让我们修改代码来看看表里有什么:

local objects = {}
local foo = #bar * 3
for i=1, foo do
    objects[i] = bar[quantizeNumber(i, 3)]
    print("At " .. i .. " the value is " .. (objects[i] and objects[i] or "nil"))
end
print(objects)
print(#objects)

当你运行这个代码时,你会发现 objects[4] 是 3,但是 objects[5]nil。以下是输出内容:

$ lua quantize.lua
At 1 the value is nil
At 2 the value is 3
At 3 the value is 3
At 4 the value is 3
At 5 the value is nil
At 6 the value is nil
At 7 the value is nil
At 8 the value is nil
At 9 the value is nil
At 10 the value is nil
At 11 the value is nil
At 12 the value is nil
At 13 the value is nil
At 14 the value is nil
At 15 the value is nil
table: 0x1001065f0
4

确实,你填充了表的 15 个槽位。但是,正如参考手册中所定义的那样,表上的 # 运算符并不关心这一点。它只是寻找一个值不为 nil 且其后面的索引是 nil 的索引。

在这种情况下,满足该条件的索引是 4。

这就是为什么答案是 4。这是 Lua 的工作方式。

nil 可以被看作数组的结尾。这有点像在 C 语言中,一个字符数组中间的零字节实际上是一个字符串的结尾,而“字符串”只是它之前的那些字符。

如果你的意图是产生表 1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,那么你需要将 quantize 函数重写如下:

function quantizeNumber(i, step)
    return math.ceil(i / step)
end
2011-08-26 06:41:29
stackoverflow用户734069
stackoverflow用户734069

函数quantizeNumber是错误的。你要找的函数是math.fmod

objects[i] = bar[math.fmod(i, 3)]
2011-08-26 07:03:48