Lua中的两个实例“Class”是相同的“对象”

我正在使用Love2d和Lua,看看我的自定义Lua“class”:

-- Tile.lua
local Tile = { img = nil, tileType = 0, x = 0, y = 0 }

function Tile:new (img, tileType, x, y)
    o = {}
    setmetatable(o, self)
    self.__index = self
    self.img = img or nil
    self.tileType = tileType or 0
    self.x = x or 0
    self.y = y or 0
    return o
end

function Tile:getX ()
    return self.x
end

return Tile

并使用该类:

-- main.lua
Tile = require("src/Tile")

function love.load()
    myGrass = Tile:new(nil, 0, 0, 0)
    print(myGrass:getX()) -- 0
    otherGrass = Tile:new(nil, 0, 200, 200)
    print(myGrass:getX()) -- 200
end

因此,我创建一个名为“myGrass”的“Tile”,其“x = 0”,然后我创建另一个名为“otherGrass”的“Tile”,现在其“x = 200”,结果是:我的第一个“Tile”,“myGrass”自己的“x”属性从0更改为200,因此“MyGrass”和“otherGrass”是相同的对象(表)。

点赞
用户7499554
用户7499554

这样做可以:

function Tile:new(img, tileType, x, y)
    local o = {}

    -- 将 o 的 metatable 设置为 self,以便访问 self 的属性和方法
    setmetatable(o, {__index = self})

    -- 对 o 的属性赋新值,而不是对 self 的属性赋新值
    o.img = img or nil
    o.tileType = tileType or 0
    o.x = x or 0
    o.y = y or 0

    return o
end
2019-05-12 08:31:32