1

在 Lua(ipad 上的 Codea)中,我制作了一个程序,其中有四对 XY 坐标,它们放在相同 id 下的表中(计数 = 计数 + 1)当我第一次使用一对来测试代码时,检测 XY 坐标何时触及表中的坐标之一(坐标已经位于该坐标的位置)。我使用这段代码做到了这一点:

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 值进行比较。

在此先感谢,劳伦特

4

2 回答 2

2

首先删除复制粘贴代码。使用类似的东西posy[n]代替posy1, posy2... 另一个相同的东西:tableposy[n][id]代替tableposy1[id]..

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

于 2013-01-10T06:39:23.853 回答
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
于 2013-01-10T15:42:52.423 回答