lualove2d

Two instances of a Lua "Class" are the same "object"


I am working with Love2d and Lua, take a look to my custom 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

and use the class:

-- 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

So, I create a Tile called myGrass with x = 0, then I create other Tile called otherGrass now with x = 200, the result: my first Tile, myGrass, change her own x attribute from 0 to 200 therefore MyGrass and otherGrass are the same object (table).


Solution

  • This works:

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

    Assign new values to new table, not to self.