Lua是否在表中共享表?

时间:2014-06-05 19:08:41

标签: lua lua-table love2d

我开始使用Love2d引擎和Lua开发游戏,我有以下代码结构。

BaseEntity = { 
        x = 0,
        y = 0,
        w = 0,
        h = 0,
        img = {},
     }

function BaseEntity:new(obj)
    obj = obj or {}
    setmetatable(obj, self)
    self.__index = self
    return obj
end

function BaseEntity:setPos(x, y)
    self.x = x
    self.y = y
end

function BaseEntity:setImage( index, image )
    self.img[index] = image
end

PlayerType  = {["NORMAL"] = 0, ["AI"] = 1}
PlayerState = {["SELECTED"] = 0, ["NOT_SELECTED"] = 1}

Player =    {
                type    = PlayerType.NORMAL,
                state   = PlayerState.NOT_SELECTED
            }

Player = BaseEntity:new(Player)

function Player:new( obj )
    obj = obj or BaseEntity:new()
    setmetatable(obj, self)
    self.__index = self
    return obj
end

function Player:setImage( image )
    self.img["sprite"] = image
end

当我创建一些Player对象并使用setImage()函数为每个对象分配不同的图像时,它们都共享我分配给最后一个对象的相同图像。但是当我使用setPos()方法为每个对象设置不同的位置时,它们被绘制在正确的独特位置。为什么会这样? Lua是否共享img内的表BaseEntity及其创建的所有实例?

1 个答案:

答案 0 :(得分:1)

表是共享的。如果您不想共享,则必须创建单独的表实例。请注意,x,y ... img您定义为类变量而不是实例变量。要查看此内容,请尝试以下代码:

BaseEntity = { 
        x = 0,
        img = {}, 
     }

function BaseEntity:new(obj)
    obj = obj or {}
    assert(self == BaseEntity)
    setmetatable(obj, self)
    -- obj.img = {}
    self.__index = self
    -- self.__newindex = self
    return obj
end

p1 = BaseEntity:new {y = 1}
p2 = BaseEntity:new {y = 2}

print('p1:', p1.x, p1.y, p1.img)
print('p2:', p2.x, p2.y, p2.img)
print('base:', BaseEntity.x)
p1.x = 3
print('p1:', p1.x, p1.y, p1.img)
print('p2:', p2.x, p2.y, p2.img)
print('base:', BaseEntity.x)

这会产生此输出:

p1: 0   1   table: 0x1736430
p2: 0   2   table: 0x1736430
base:   0
p1: 3   1   table: 0x1736430
p2: 0   2   table: 0x1736430
base:   0

显示该表是共享的,当您写入x时,您正在写入p1实例而不是该类。如果现在取消注释obj.img new(),p1和p2的表将不再相同:每个实例都有自己的表。如果您取消注释__newindex行,您会看到您正在分配给BaseEntity“class”