For loop 我可以在for循环中声明局部变量吗?

For loop 我可以在for循环中声明局部变量吗?,for-loop,indexing,graph,lua,grid,For Loop,Indexing,Graph,Lua,Grid,在上面的代码中,centerLookup[点]是指通过输入点位置来查找相应的中心对象 但是,当我尝试这样做时: for x = 1, 16 do for y = 1, 16 do local cntr = Center:new() cntr.point = {x = 0.5 + x - 1, y = 0.5 + y - 1} centerLookup[cntr.point] = cntr table.insert(self.centers, cntr) e

在上面的代码中,centerLookup[点]是指通过输入点位置来查找相应的中心对象

但是,当我尝试这样做时:

for x = 1, 16 do
  for y = 1, 16 do
    local cntr = Center:new()
    cntr.point = {x = 0.5 + x - 1, y = 0.5 + y - 1}
    centerLookup[cntr.point] = cntr
    table.insert(self.centers, cntr)
  end
end
函数邻居(中心,sqrtsize)
如果中心点y+1
centerup以零值返回

Idk如果问题是我不能使用表作为索引,但这就是我的想法

有人知道这里出什么事了吗

另外,如果有帮助,中心从0.5开始(因此[0.5,0.5]将是第一个中心,然后是[0.5,1.5],等等)


提前谢谢

这与局部变量无关,与表是通过引用而不是通过值进行比较这一事实有关

在Lua中,表是具有自己标识的引用类型。即使两个表具有相同的内容,Lua也不认为它们是相等的,除非它们是完全相同的对象。< /P> 为了说明这一点,以下是一些示例代码和打印的值:

function neighbors(center, sqrtsize)
  if center.point.y + 1 < sqrtsize then
    local up = {x = center.point.x, y = center.point.y+1}
    local centerup = centerLookup[up]
    table.insert(center.neighbors, centerup)
  end
end

在这个代码段中,
up
是一个全新的表,只有一个引用(变量本身)。即使存在具有相同内容的表键,此新表也不会是
centerLookup
表中的键

local up = {x = center.point.x, y = center.point.y+1}
local centerup = centerLookup[up]

在这个代码段中,您创建了一个新表,并在三个不同的位置引用它:
cntr.point
centerLookup
作为键,
self.centers
作为值。您可能会遍历
self.centers
数组,并使用完全相同的表在
centerLookup
表中查找项目。但是,如果要使用不在
self.centers
数组中的表,它将不起作用。

这与局部变量无关,而与表是通过引用而不是通过值进行比较这一事实有关

在Lua中,表是具有自己标识的引用类型。即使两个表具有相同的内容,Lua也不认为它们是相等的,除非它们是完全相同的对象。< /P> 为了说明这一点,以下是一些示例代码和打印的值:

function neighbors(center, sqrtsize)
  if center.point.y + 1 < sqrtsize then
    local up = {x = center.point.x, y = center.point.y+1}
    local centerup = centerLookup[up]
    table.insert(center.neighbors, centerup)
  end
end

在这个代码段中,
up
是一个全新的表,只有一个引用(变量本身)。即使存在具有相同内容的表键,此新表也不会是
centerLookup
表中的键

local up = {x = center.point.x, y = center.point.y+1}
local centerup = centerLookup[up]

在这个代码段中,您创建了一个新表,并在三个不同的位置引用它:
cntr.point
centerLookup
作为键,
self.centers
作为值。您可能会遍历
self.centers
数组,并使用完全相同的表在
centerLookup
表中查找项目。但是,如果要使用不在
self.centers
数组中的表,则该表将不起作用。

collone three Two解释了代码无法按预期工作的原因。我只想添加快速解决方案:

cntr.point = {x = 0.5 + x - 1, y = 0.5 + y - 1}
centerLookup[cntr.point] = cntr
table.insert(self.centers, cntr)
使用此函数在两个位置进行查找

function pointToKey(point)
  return point.x .. "_" .. point.y
end

三十二上校解释了代码无法按预期工作的原因。我只想添加快速解决方案:

cntr.point = {x = 0.5 + x - 1, y = 0.5 + y - 1}
centerLookup[cntr.point] = cntr
table.insert(self.centers, cntr)
使用此函数在两个位置进行查找

function pointToKey(point)
  return point.x .. "_" .. point.y
end

谢谢你的深入解释,这正是我想要弄明白的。谢谢你的深入解释,这正是我想要弄明白的