Lua中的奇怪表错误

Ell*_*lle 2 lua coronasdk

好的,所以我对以下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)
Run Code Online (Sandbox Code Playgroud)

运行此代码后,对象的长度为15,对吧?但不,这是4.这是如何工作的,我错过了什么?

谢谢,Elliot Bonneville.

Ray*_*oal 5

是的,它是4.

来自Lua参考手册:

表t的长度被定义为任何整数索引n,使得t [n]不是nil且t [n + 1]是nil; 此外,如果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)
Run Code Online (Sandbox Code Playgroud)

当你运行这个你看到的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
Run Code Online (Sandbox Code Playgroud)

确实,你填写了表格的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
Run Code Online (Sandbox Code Playgroud)