Two instances of a Lua "Class" are the same "object"
Asked Answered
I

1

5

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

Islet answered 12/5, 2019 at 8:5 Comment(2)
Remember that when you have function A:b() ... you really have function b(A) local self=A; ... -> Your Tile:new function uses the same local Tile table as self for every invocation.Castlereagh
You may want to think about including a Tile:clone() function as well. See this question for more on that: #56046349Amen
S
7

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.

Spokane answered 12/5, 2019 at 8:31 Comment(1)
Also, use 'local o'.Wyly

© 2022 - 2024 — McMap. All rights reserved.