Lua中的奇怪表错误

时间:2011-08-26 06:17:20

标签: lua corona

好的,所以我对以下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)

运行此代码后,对象的长度应为15,对吗?但不,这是4.这是如何工作的,我缺少什么?

谢谢,Elliot Bonneville。

2 个答案:

答案 0 :(得分:5)

是的,它是4。

来自Lua参考手册:

  

表t的长度定义为任何整数索引n,使得t [n]不为零且t [n + 1]为零;此外,如果t [1]为零,则n可以为零。对于常规数组,非n值从1到给定n,其长度恰好是n,即其最后一个值的索引。如果数组具有“空洞”(即,其他非零值之间的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,其后续索引 为零。

在这种情况下,满足此条件的索引为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

答案 1 :(得分:0)

函数quantizeNumber错误。你正在寻找的函数是math.fmod:

objects[i] = bar[math.fmod(i, 3)]