【问题标题】:Strange table error in LuaLua中的奇怪表错误
【发布时间】:2011-08-26 15:06:34
【问题描述】:

好的,下面的 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。这是如何工作的,我错过了什么?

谢谢,艾略特·邦纳维尔。

【问题讨论】:

  • 我确定这是从一个更大的项目中提取的,但是其中有很多错误。例如#foo 不起作用,因为 foo 不是一张桌子。并且fontObjects 没有定义(我猜你的意思是#objects)。

标签: lua coronasdk


【解决方案1】:

是的,它是 4。

来自 Lua 参考手册:

表 t 的长度被定义为任意整数索引 n,使得 t[n] 不为 nil 且 t[n+1] 为 nil;此外,如果 t[1] 为 nil,则 n 可以为零。对于从 1 到给定 n 的非 nil 值的常规数组,它的长度正好是 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

【讨论】:

  • 但是bar 有五个元素长。我应该做一个从 1 到 15 的 for 循环,15 是 bar * 3 的长度,正如我之前指定的。那不应该给我留下 15 件物品吗?为什么我会收到 4 件商品?
  • @Elliot,我已经在编辑我的答案时回答了这个问题。 HTH。
  • 好的,所以我将数组填充到第 4 项。为什么它没有超过索引 4?我希望输出会像这样:1、1、1、2、2、2、3、3、3、... 5、5、5。为什么不是呢?我做错了什么?
  • 在这种情况下,quantizeNumber 函数是错误的。请参阅答案的最新附录。
【解决方案2】:

函数quantizeNumber 错误。您要查找的函数是 math.fmod:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 2013-09-05
    • 2014-06-14
    • 2013-11-29
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    相关资源
    最近更新 更多