2017-04-08 168 views
1
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对象。我可以在for循环中声明局部变量吗?

然而,当我尝试这样做:

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收益为空值

IDK如果问题是,我不能用一个表作为索引,但这是我在想什么。

有人知道这里有什么问题吗?

P.S.如果有帮助的话,中心开始为0.5(所以[0.5,0.5]将是第一个中心,然后是[0.5,1.5]等)

在此先感谢!

回答

2

这与局部变量无关,并且与通过引用而不是按值进行比较的事实无关。

在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 and tbl2 both reference the same table 
print(tbl1 == tbl3) -- False; tbl1 and tbl3 reference different tables 

local up = {x = center.point.x, y = center.point.y+1} 
local centerup = centerLookup[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阵列中的表格,它将不起作用。

+0

感谢在深入的解释,这正是我一直在试图找出 – Denfeet

2

上校三十二解释了为什么你的代码不能按预期工作的原因。我只想补充快速的解决方案:

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

使用此功能查找在这两个地方

--setup centerLookup 
centerLookup[pointToKey(cntr.point)] = cntr 

--find point from lookup 
local centerup = centerLookup[pointToKey(up)] 
+0

是的,乌尔实现工作。谢谢! – Denfeet