为什么我的 Lua 表对象是空的?

我在我的 Map 模块中创建了一个名为 Map 的 lua 表对象,并创建了一个新的实例:

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

在我的 island 模块中,我在前几行加入了以下代码:

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

当我打印出中心,角落和表的数量时,它们都输出为0。

我有分别用于 Corner:new(),Center:new() 和 Edge:new() 的模块。

为什么 centers、corners 和 edges 的长度输出为 0?

编辑:

这是我输入到 centers 表中的例子(corners 和 edges 类似)

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

size 始终是一个完美的平方数

点赞
用户3455883
用户3455883

这似乎是变量作用域的问题。首先,在实例化新的 Map 时,返回的 o 应该是 local 的:

function Map:new(o)
    local o = o or { -- 这应该是本地的
        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    -- 在这里,将其添加到作为参数传递的表中
        end
    end
    -- 不需要返回 centers
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)
2017-04-14 00:54:15