2011-08-26 170 views
2

好了,所以我有一个奇怪的问题,下面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。

+0

我敢肯定,这是从一个较大的项目中提取的,但这里有一堆错误。例如'#foo'不起作用,因为'foo'不是一个表。 'fontObjects'没有定义(我猜你的意思是'#objects')。 – BMitch

回答

5

是的,它是4

从Lua的参考手册:

表T的长度被定义为任何整数索引n,使得T [n]为不是nil和叔[n + 1]是零;而且,如果t [1]为零,则n可以为零。对于一个规则的数组,非零值从1到给定的n,它的长度恰好等于n,即它的最后一个值的索引。如果数组具有“空洞”(即其他非零值之间的零值),那么#t可以是任何直接在零值之前的指数(也就是说,它可以认为任何这样的零值作为结束的阵列)。

让我们修改代码,看看什么是表:

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个插槽。然而,参考手册中定义的#运算符并不关心这一点。它只是寻找值不为零的索引,其后续索引无。

在这种情况下,满足此条件的指数是4

这就是为什么答案是4。这只是方式Lua是。

零可以被看作代表数组的末尾。它有点像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 
+0

但'酒吧'是五个元素长。正如我前面指出的那样,我应该做1到15的for循环,15是bar * 3的长度。这不应该让我有15件物品?为什么我得到4件物品? –

+0

@Elliot,我在回答这个问题时已经回答了这个问题。 HTH。 –

+0

好吧,我正在将我的阵列填充到第4项。为什么它不通过索引4?我期望输出会像这样:1,1,2,2,3,3,3,... 5,5,5。为什么不是这样?我究竟做错了什么? –

0

功能quantizeNumber是错误的。你正在寻找的功能是math.fmod:

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