如何检查Lua表是否包含坐标?
我正在尝试实现一个简单的寻路系统,它可以处理开放列表和封闭列表。我对关闭的列表有问题。如何检查关闭列表是否已包含坐标如何检查Lua表是否包含坐标?,lua,path-finding,a-star,love2d,Lua,Path Finding,A Star,Love2d,我正在尝试实现一个简单的寻路系统,它可以处理开放列表和封闭列表。我对关闭的列表有问题。如何检查关闭列表是否已包含坐标 closed[current] = true local neighbors = getNeighbors(current[1], current[2]) -- get neighbors for the current node for k, v in ipairs(neighbors) do -- iterate through each neighbor if not
closed[current] = true
local neighbors = getNeighbors(current[1], current[2]) -- get neighbors for the current node
for k, v in ipairs(neighbors) do -- iterate through each neighbor
if not closed[v] then
table.insert(open, v)
end
end
GetNeights以坐标(x,y)的形式返回图块(x,y)的每个相邻图块。如何检查封闭表是否已包含这些坐标?对整个表进行哈希运算
closed[current] = true
local neighbors = getNeighbors(current[1], current[2]) -- get neighbors for the current node
for k, v in ipairs(neighbors) do -- iterate through each neighbor
if not closed[v] then
table.insert(open, v)
end
end
使用Lua,表的键(散列)几乎可以是所有内容,甚至是一个包含2个值的表
假设current[1]
和current[2]
分别表示坐标x
和y
,您只需检查closed[current]
。请参见下面的示例:
局部坐标={
{1.3,5},
{2.2,3.4},
{3,6.8}
}
local closed={}--空的封闭列表
局部电流=坐标[1]--{1.3,5}
打印(关闭[当前])--未访问=无
关闭[当前]=真--标记为已访问
打印(已关闭[当前])--已访问=真
打印(坐标[2])--未访问=无
当您勾选如果关闭[当前]则…
,则不存在的条目相当于nil
,即相当于false
。如果您明确地想要false
值而不是nil
,您可以这样初始化关闭列表:
散列坐标值
如果您在代码中的某个位置复制坐标值,而不是引用表{x,y}
,则会发生唯一的问题。在这种情况下,您将拥有不同的表,因此哈希将为您提供false
,即使这两个表的值相等
如果可能发生这种情况,则需要使用值来散列,而不是使用表。您可以按照Egor建议的方式,使用单个散列,也可以使用双散列,如下所示:
local function listAddPoint(list,point) --Adds point (a {x,y} table) to the list
if not list[point[1]] then
list[point[1]] = {}
end
list[point[1]][point[2]] = true
end
local function listHasPoint(list,point) --Checks if the point (a {x,y} table) is on the list
if list[point[1]] and list[point[1]][point[2]] then
return true
end
return false
end
local coordinates = {
{1.3,5},
{2.2,3.4},
{3,6.8}
}
local closed = {} --Empty closed list
local current = coordinates[1] --{1.3,5}
print(listHasPoint(closed,current)) --Not visited = false
listAddPoint(closed,current)--Marking as visited
print(listHasPoint(closed,current)) --visited = true
print(listHasPoint(closed,coordinates[2])) --Not visited = false
如果坐标是2^16以下的整数,则使用数字x*65536+y作为磁贴(x,y)的索引:
closed[current[1]*65536+current[2]=true
和如果未关闭[v[1]*65536+v[2]],则