lua:比较表中表的条目

时间:2021-07-17 13:10:11

标签: loops lua iteration path-finding

我需要将 {CLOSED} 中的每个 'pos' 复制到 {PATH} 中,但是按照它们从 'target' 开始的 'came_from' 的顺序。这是寻路方法的最后一部分。我一直没有成功将我的伪代码转换为 lua 代码并且需要帮助。我认为如果有人可以将伪代码转换为代码对我来说最容易理解,因为这里有一些潜在的基础知识在起作用,我互相混淆了。

<块引用>

即路径={{x=33,y=44},{x=22,y=25},{x=0,y=0}}

start={x=0,y=0}
target={x=33,y=44}
CLOSED={
    {pos={x=33,y=44},came_from={x=22,y=25}},
    {pos={x=0,y=0},came_from={x=nil,y=nil}},
    {pos={x=22,y=25},came_from={x=0,y=0}}
}
PATH={}

--outline:
current=target

while current~=start do
    add(path,current)
--??    current=CLOSED[i].came_from[current]??
--outstanding steps:
--check current against each 
--CLOSED[i].pos
--if we have a match, 
--current=closed[i].came_from
--repeat
end

1 个答案:

答案 0 :(得分:0)

除非专门分配给彼此(即 {a}={b}),否则无法比较表格。因此,您必须抓取并比较同一变量(即 x 和 y)的所有键的各个值。下面的函数可以做到这一点,如果命中则返回 true。另一种更具体的方法是将 x,y 坐标从 2d 转换为 1d 并比较整数(因此对于 nxm 矩阵,其 x+m*y)。

start={x=0,y=0}
target={x=33,y=44}
closed={
    {pos={x=33,y=44},came_from={x=22,y=25}},
    {pos={x=0,y=0},came_from={x=nil,y=nil}},
    {pos={x=22,y=25},came_from={x=0,y=0}}
}
path={}

--outline:
current=target
function subset(a,b)
    for k,v in pairs(a) do
  if b[k]~=v then return false end
    end
 return true
end
function equal(a,b)
 return subset(a,b) and subset(b,a)
end

while current.x~=start.x and current.y~=start.y do
    --check current against each 
    --closed[i].pos
    --if we have a match, 
    --current=closed[i].came_from
    --repeat
 add(path,current)
    for i=1,#closed do
        if equal(current,closed[i].pos) then
            current=closed[i].came_from
            break
        end
    end
end
add(path,start)


--expected path={{x=33,y=44},{x=22,y=25},{x=0,y=0}}
--check:
for k,v in pairs(path) do
    for k,v in pairs(v) do
    print(k.."="..tostr(v))
    end
end
相关问题