如何检查Lua表中是否包含坐标?

我正在尝试实现一个简单的路径规划系统,它可以使用打开和关闭的列表。我在关闭列表中遇到了问题。如何检查关闭列表是否已经包含了这些坐标?

closed[current] = true

local neighbors = getNeighbors(current[1], current[2]) -- 获取当前节点的所有邻居节点
for k, v in ipairs(neighbors) do -- 遍历邻居节点
  if not closed[v] then
    table.insert(open, v)
  end
end

getNeighbors会返回一个坐标(x,y)的所有邻居坐标。我该如何检查关闭表是否已经包含这些坐标?

点赞
用户5351988
用户5351988

整个表的哈希

在 Lua 中,表的键(哈希)几乎可以是任何东西,甚至是具有两个值的表。

假设 current[1]current[2] 分别表示坐标 xy,你可以只是检查 closed[current]。请参见下面的示例:

local coordinates = {
  {1.3,5},
  {2.2,3.4},
  {3,6.8}
}
local closed = {} -- 空闭合列表
local current = coordinates[1]  -- {1.3,5}
print(closed[current]) -- 尚未访问 = nil
closed[current] = true -- 标记已访问
print(closed[current]) -- 访问过 = true
print(coordinates[2]) -- 尚未访问 = nil

当你检查 if closed[current] then ...,不存在的条目相当于 nil,那就相当于 false。如果你明确想要 false 值而不是 nil,可以像这样初始化闭合列表:

closed = {}
for i=1,#coordinates do
    closed[coordinates[i]] = false
end

哈希坐标值

唯一的问题可能发生在你的代码中复制坐标值而不是引用表 {x, y} 的情况下。在这种情况下,你会有不同的表,因此即使两个表的值相等,哈希结果也会给你 false

如果可能会发生这种情况,你需要使用 而不是表进行哈希。你可以像 Egor 建议的那样使用单个哈希,或者使用双重哈希,例如:

local function listAddPoint(list, point) -- 将点(一个 {x,y} 表)添加到列表中
    if not list[point[1]] then
        list[point[1]] = {}
    end
    list[point[1]][point[2]] = true
end

local function listHasPoint(list, point) -- 检查点(一个 {x,y} 表)是否在列表中
    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 = {} -- 空闭合列表
local current = coordinates[1]  -- {1.3,5}
print(listHasPoint(closed, current)) -- 尚未访问 = false
listAddPoint(closed, current) -- 标记为已访问
print(listHasPoint(closed, current)) -- 访问过 = true
print(listHasPoint(closed, coordinates[2])) -- 尚未访问 = false
2017-03-01 00:55:49