3

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

Cristofer Fuentes
  • 411
  • 1
  • 6
  • 16
  • 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. – glenn jackman May 12 '19 at 12:15
  • 1
    You may want to think about including a `Tile:clone()` function as well. See this question for more on that: https://stackoverflow.com/questions/56045849/lua-how-to-modify-these-arguments-to-be-const-or-what-should-i-do?answertab=oldest#tab-top – Nifim May 12 '19 at 14:24

1 Answers1

6

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.

Cristofer Fuentes
  • 411
  • 1
  • 6
  • 16
Slava
  • 878
  • 5
  • 8