【问题标题】:Lua tables check if any variable matches any valueLua 表检查是否有任何变量匹配任何值
【发布时间】:2013-03-06 21:14:18
【问题描述】:

在 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]

这就像我想要的那样工作!

但现在我有 8 个表(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 值进行比较。

提前致谢,劳伦特

【问题讨论】:

    标签: loops if-statement lua coordinates lua-table


    【解决方案1】:

    首先删除复制粘贴代码。使用posy[n] 代替posy1posy2... 之类的东西:tableposy[n][id] 代替tableposy1[id]..

    之后,您可以使用循环在一行中进行比较。您可以将比较重构为一个函数,您可以在比较之前进行nil 检查。

    【讨论】:

    • 你能给我一个这样的循环和所谓的'nil check'的例子吗?
    【解决方案2】:

    您可能应该使用表格来组织这些值。使用包含一系列“坐标”表的位置表。这样,您可以使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 2013-06-04
      • 1970-01-01
      相关资源
      最近更新 更多