2017-04-13 165 views
1

我创造我的地图模块称为映射的LUA表对象,这个函数创建一个新的实例:为什么我的lua表格对象是空的?

function Map:new (o) 
    o = o or { 
    centers = {}, 
    corners = {}, 
    edges = {} 
    } 
    setmetatable(o, self) 
    self.__index = self 
    return o 
end 

,并在我的岛模块,我把这段代码中的第几行:

local map = require (*map module location*) 
Island = map:new() 

,当我打印中心,角落和表的数量,他们都站出来为0

我有单独的模块角:新的(),中心:新的(),与边缘:新的( )

为什么中心,角点和边缘的长度输出为0?

编辑:

这是我输入到中心表例如(四角和边缘是相似的)

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

function Map:generateCenters(centers) 
    local N = math.sqrt(self.SIZE) 
    for xx = 1, N do 
     for yy = 1, N do 
      local cntr = Center:new() 
      cntr.point = {x = 0.5+xx - 1, y = 0.5+yy - 1} 
      centers[pointToKey(cntr.point)] = cntr 
     end 
    end 
    return centers 
end 

大小始终是一个完美的正方形

+1

'map:new()'返回一个带有“转角”键的表格,指向空表格。为什么你会期望尺寸与零不同? – GoojajiGreg

+0

在检查“Island.corners”中的元素数量之前,你正在做'table.insert(Island.corners,Corner:new())'吗? – GoojajiGreg

+0

@GoojajiGreg再次检查,我明白你的意思,所以我深入一点。对不起,混淆 – Denfeet

回答

1

这似乎是一个变量范围的问题。首先,实例化一个新的Map,返回的o应该是local

function Map:new (o) 
    local o = o or { -- this should be local 
     centers = {}, 
     corners = {}, 
     edges = {} 
    } 
    setmetatable(o, self) 
    self.__index = self 
    return o 
end 

当你传递一个指针表Map:generateCenters(),没有必要返回指针。该中心已被添加到该表:

function Map:generateCenters(centers) 
    local N = math.sqrt(self.SIZE) 
    for xx = 1, N do 
     for yy = 1, N do 
      local cntr = Center:new() 
      cntr.point = {x = 0.5+xx - 1, y = 0.5+yy - 1} 
      centers[pointToKey(cntr.point)] = cntr -- HERE you're adding to the table passed as an argument 
     end 
    end 
    -- return centers --> NO NEED TO RETURN THIS 
end 

最后,你会怎么做:

local map = require("map") 
local island = map:new() 
map:generateCenters(island.centers) 

你是在说,“把中心到表由对应于键的表值指出,在名为island的表中称为centers“。

最后,注意

local t = island.centers 
print(#t) 

意愿依然不输出元素表中的centers数量,因为有差距键(即他们不去{0,1,2,3,4, ..}而是任何字符串pointToKey()函数返回)。要计算centers中的元素,您可以执行以下操作:

local count = 0 
for k,v in pairs(island.centers) do 
    count = count + 1 
end 
print(count) 
+2

'o'是本地的,因为它是一个参数。 – lhf

+0

@lhf哦,当然。感谢您指出了这一点。从“在Lua中编程”ch。 15:“参数与局部变量完全一样,用函数调用中给出的实际参数初始化,你可以调用一个参数个数与参数个数不同的函数,Lua将参数个数调整为参数个数,就像它在多个任务中所做的那样:额外的参数被抛弃;额外的参数被取消为零。“ – GoojajiGreg