【问题标题】:Why is my lua table object empty?为什么我的 lua 表对象是空的?
【发布时间】:2017-09-10 04:12:09
【问题描述】:

我在我的 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 ()

为什么中心、角、边的长度输出为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

大小总是一个完美的正方形

【问题讨论】:

  • map:new() 返回一个表,其中包含指向空表的键 corners 等。为什么你会期望大小不为零?
  • 在检查Island.corners中的元素数量之前,你是在做table.insert( Island.corners, Corner:new() )吗?
  • @GoojajiGreg 再检查一次,我明白你的意思,所以我更深入了一点。很抱歉造成混乱

标签: lua scripting instantiation lua-table


【解决方案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 )

您是说,“将中心放入表值所指向的表中,该表值对应于名为 centers 的表中名为 island 的键”。

最后,请注意

local t = island.centers
print( #t )

仍然不会输出表 centers 中的元素数量,因为存在间隙键(即它们不去 {0,1,2,3,4,..} 而是任何字符串 @987654332 @函数返回)。要计算centers 中的元素,您可以这样做:

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

【讨论】:

  • o 是局部变量,因为它是一个参数。
  • @lhf 哦,当然。感谢您指出了这一点。来自“Lua 编程”章节。 15:“参数完全像局部变量一样工作,使用函数调用中给出的实际参数进行初始化。您可以使用与其参数数量不同的参数数量来调用函数。Lu​​a 将参数数量调整为参数数量,就像在多重赋值中一样:多余的参数被丢弃;多余的参数为零。”
猜你喜欢
  • 2015-09-04
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
相关资源
最近更新 更多