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

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. May 12, 2019 at 12:15
  • 1
    You may want to think about including a Tile:clone() function as well. See this question for more on that: stackoverflow.com/questions/56045849/…
    – Nifim
    May 12, 2019 at 14:24

1 Answer 1

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.

1
  • 3
    Also, use 'local o'.
    – lhf
    May 12, 2019 at 14:19

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.