Lua表检查是否有任何变量与任何值匹配

在 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

点赞
用户849402
用户849402

开始时先删掉复制黏贴的代码。使用 posy[n] 来代替 posy1posy2 等等。同样地,使用 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
2013-01-10 06:39:23
用户1208078
用户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