Lua表检查是否有任何变量与任何值匹配
2013-3-6 13:14:19
收藏:0
阅读:133
评论:2
在 Lua 中 (在 iPad 上的 Codea 中)我制作了一个程序,其中有四对 X-Y 坐标,并且这些坐标在相同的 ID 下放置在表中(count = count + 1)。
当我首次使用仅一个对进行代码测试,以检测 X-Y 坐标何时接触表中已经有的坐标之一时。
我使用了以下代码:
if (math.abs(xposplayer - posx) < 10) and (math.abs(yposplayer - posy) < 10) and id < (count - 10) then
这段代码在以下循环中执行:
for id,posx in pairs(tableposx) do
posy = tableposy[id]
这正是我想要的方式!
但现在我有了八个表(tableposx1 tableposy1,...)并且我想检查当前坐标是否接触到任何一个表中的坐标(任何时候)因此我尝试了:
for id,posx1 in pairs(tableposx1) do
posy1 = tableposy1[id]
posy2 = tableposy2[id]
posx2 = tableposx2[id]
posy3 = tableposy3[id]
posx3 = tableposx3[id]
posy4 = tableposy4[id]
posx4 = tableposx4[id]
并且对于当前四个坐标,使它四次运行:
if ((math.abs(xposplayer1 - posx1) < 10) and (math.abs(yposplayer1 - posy1) < 10))
or ((math.abs(xposplayer1 - posx2) < 10) and (math.abs(yposplayer1 - posy2) < 10))
or ((math.abs(xposplayer1 - posx3) < 10) and (math.abs(yposplayer1 - posy3) < 10))
or ((math.abs(xposplayer1 - posx4) < 10) and (math.abs(yposplayer1 - posy4) < 10))
and (id < (count - 10))
但是这总是(几乎)正确的。并且由于有时表中的值为 NIL,它会抛出错误,表明它无法将某些内容与 nil 值进行比较。
提前致谢,Laurent
点赞
用户1208078
你可能应该使用表格来组织这些值。使用一个包含一系列“坐标”表格的表格来保存位置,这样你就可以使用 for 循环迭代所有的坐标。确保表格中的每个项目都表示坐标对,可以编写相对通用的函数来测试其有效性。
function GetNewCoords(x_, y_)
x_ = x_ or 0
y_ = y_ or 0
return { x = x_, y = y_}
end
function CoordsAreValid(coords)
if (coords == nil) return false
return coords.x ~= 0 or coords.y ~= 0
end
local positions = {}
table.insert(positions, GetNewCoords(5, 10))
table.insert(positions, GetNewCoords(-1, 26))
table.insert(positions, GetNewCoords())
table.insert(positions, GetNewCoords(19, -10))
for _, coords in pairs(positions) do
if (CoordsAreValid(coords)) then
print(coords.x, coords.y)
end
end
2013-01-10 15:42:52
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在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中获取用户配置主目录的跨平台方法
开始时先删掉复制黏贴的代码。使用
posy[n]来代替posy1、posy2等等。同样地,使用tableposy[n][id]来代替tableposy1[id]等等。然后,可以使用循环在一行中进行比较。你甚至可以将比较重构为一个函数,在比较之前检查
nil。示例代码: for n = 1, numbuildings do if posy1 <= tableposy1[n] + spacex or posy1 >= tableposy1[n] + lengthx - spacex then if posz1 >= tableposz1[n] + spacez and posz1 <= tableposz1[n] + widthz - spacez then return true end end if posy2 <= tableposy2[n] + spacex or posy2 >= tableposy2[n] + lengthx - spacex then if posz2 >= tableposz2[n] + spacez and posz2 <= tableposz2[n] + widthz - spacez then return true end end -- more copies of the above code for each posy and posz variable end