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)
运行此代码后,对象的长度应该为 15,对吧?但不,是 4。这是如何工作的?我错过了什么?
谢谢,埃利奥特·博纳维尔。
Okay, so I've got a strange problem with the following Lua code:
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)
After this code has been run, the length of objects should be 15, right? But no, it's 4. How is this working and what am I missing?
Thanks, Elliot Bonneville.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,是 4。
来自 Lua 参考手册:
让我们修改代码来查看表中的内容:
运行此代码时,您会看到
objects[4]
为 3,但objects[5]
为nil< /代码>。输出如下:
您确实填写了表中的 15 个位置。然而,根据参考手册的定义,表上的
#
运算符并不关心这一点。它只是查找值不为零且其后续索引为 nil 的索引。在这种情况下,满足这个条件的索引是4。
这就是为什么答案是4。Lua就是这样。
nil 可以看作代表数组的结尾。这有点像在 C 中,字符数组中间的零字节实际上是字符串的结尾,而“字符串”只是它之前的那些字符。
如果您的目的是生成表
1,1,1,2,2,2,3,3,3,4,4,4,5,5,5
那么您将需要重写您的quantize
函数如下:Yes it is 4.
From the Lua reference manual:
Let's modify the code to see what is in the table:
When you run this you see that
objects[4]
is 3 butobjects[5]
isnil
. Here is the output:It is true that you filled in 15 slots of the table. However the
#
operator on tables, as defined by the reference manual, does not care about this. It simply looks for an index where the value is not nil, and whose following index is nil.In this case, the index that satisfies this condition is 4.
That is why the answer is 4. It's just the way Lua is.
The nil can be seen as representing the end of an array. It's kind of like in C how a zero byte in the middle of a character array is actually the end of a string and the "string" is only those characters before it.
If your intent was to produce the table
1,1,1,2,2,2,3,3,3,4,4,4,5,5,5
then you will need to rewrite yourquantize
function as follows:函数
quantizeNumber
是错误的。您正在寻找的函数是 math.fmod:The function
quantizeNumber
is wrong. The function you're looking for is math.fmod: