在 for 循环中声明一个局部变量可以吗?

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

上面的代码中,centerLookup[point] 用来查找相应的 Center 对象,输入点位置即可。

然而当我尝试这样做时:

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

centerup 返回 nil。

我不知道问题是否在于无法使用一个表作为索引,但我认为可能是这个问题。

有人知道这里的问题在哪吗?

顺便说一句,如果有帮助,centers 从 0.5 开始(例如 [0.5, 0.5] 就是第一个 center,然后是 [0.5, 1.5],等等)。

提前感谢!

点赞
用户646619
用户646619

这与局部变量无关,而与表是按引用而不是按值比较有关。

在 Lua 中,表是具有自己标识的引用类型。即使两个表具有相同的内容,Lua 也不认为它们相等,除非它们是完全相同的对象。

这里有一些示例代码和打印出的值来说明这一点:

local tbl1 = {x = 0.5, y = 0.5}
local tbl2 = tbl1
local tbl3 = {x = 0.5, y = 0.5}
print(tbl1 == tbl2) -- True; tbl1 和 tbl2 引用同一张表
print(tbl1 == tbl3) -- False; tbl1 和 tbl3 引用不同的表

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

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

cntr.point = {x = 0.5 + x - 1, y = 0.5 + y - 1}
centerLookup[cntr.point] = cntr
table.insert(self.centers, cntr)

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

2017-04-08 20:50:41
用户5331361
用户5331361

Colonel Thirty Two 解释了代码不能按预期工作的原因。我想要添加快速解决方案:

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

在两个地方都使用这个函数进行查找:

--设定中心查找
centerLookup[pointToKey(cntr.point)] = cntr

--从查找中找到点
local centerup = centerLookup[pointToKey(up)]
2017-04-08 21:04:09