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

Loops Lua表检查任何变量是否与任何值匹配,loops,if-statement,lua,coordinates,lua-table,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 这就像我希望的那样有效

在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
这就像我希望的那样有效

但现在我有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)和(math.abs(yposplayer1-posy1)<10))
或者((math.abs(xposplayer1-posx2)<10)和(math.abs(yposplayer1-posy2)<10))
或者((math.abs(xposplayer1-posx3)<10)和(math.abs(yposplayer1-posy3)<10))
或者((math.abs(xposplayer1-posx4)<10)和(math.abs(yposplayer1-posy4)<10))
和(id<(计数-10))
但这总是(几乎)成真。因为有时候表中的值是零,所以会给我一个错误,说它不能将某个值与零值进行比较


提前感谢,Laurent从删除复制粘贴代码开始。使用类似于
posy[n]
的内容,而不是
posy1
posy2
。。。另一个也一样:
tableposy[n][id]
而不是
tableposy1[id]


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

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

你能给我举一个这样的循环和所谓的“零检查”的例子吗?
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))
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