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

时间:2013-01-10 06:31:38

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

在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,它会给我一个错误,说它无法比较一些零值。

提前致谢,Laurent

2 个答案:

答案 0 :(得分:2)

首先删除复制粘贴代码。使用类似posy[n]而不是posy1posy2的内容......和另一个相同:tableposy[n][id]代替tableposy1[id] ..

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

答案 1 :(得分:1)

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