Lua中的奇怪表错误。
2011-8-26 6:17:20
收藏:0
阅读:106
评论: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)
运行此代码后,objects 的长度应该是 15,对吗?但不是,它是 4。这是如何工作的,我错过了什么?
谢谢,Elliot Bonneville。
原文链接 https://stackoverflow.com/questions/7200705
点赞
stackoverflow用户734069
函数quantizeNumber
是错误的。你要找的函数是math.fmod
:
objects[i] = bar[math.fmod(i, 3)]
2011-08-26 07:03:48
评论区的留言会收到邮件通知哦~
推荐文章
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
- 如何编写 Lua 模式将字符串(嵌套数组)转换为真正的数组?
是的,答案是 4。
根据 Lua 参考手册的定义:
让我们修改代码来看看表里有什么:
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