Search code examples
ooplua

Lua OOP multiple instances of class are being ignored, why?


I have a class called "Edit"

function Edit:new(x,y,w,h,text,fnt)
    o = {}
    setmetatable(o,EditMt)
    self.__index = self
    self.x = x or 0
    self.y = y or 0
    self.width = w or 10
    self.height = h or 10
    self.text = text or ""
    self.active = false
    self.font = fnt or font
    self.yo = -(self.height - self.font:getHeight()) / 2
    return o
end

and that class has a function called draw(made with Löve2d)

function Edit:draw(  )
    if self.active then
        love.graphics.setColor(255,255,255,255)
     love.graphics.rectangle("fill",self.x,self.y,self.width,self.height)
        love.graphics.setColor(0,0,0,255)
        love.graphics.printf(self.text,self.font,self.x,self.y,self.width, "center",0,1,1,0,self.yo)
    else 
        love.graphics.setColor(255,255,255,255)
        love.graphics.rectangle("line",self.x,self.y,self.width,self.height)
        love.graphics.printf(self.text,self.font,self.x,self.y,self.width, "center",0,1,1,0,self.yo)
    end
end

and in my main i create 2 of them

edit1 = Edit:new(10,10,60,50,"1")
edit2 = Edit:new(80,10,60,50,"2")

and draw them in the callback

function love.draw( )
    edit1:draw()
    edit2:draw()
end

but it only draws edit2? if i switch the places in draw it still only draws edit2 but if i switch their places while creating them in the main it now only draws edit1?


Solution

  • This is the most common beginners mistake when they get into OOP in Lua.

    You're assigning all those values to self which is Edit. But if you want to change your instance you need to assign them to o.

    Otherwise each call to Edit.new will overwrite the values.

    The second problem is that your instance o is a global. You need it to be local! Or you will overwrite your instances each time.

     function Edit:new (x,y,w,h,text,fnt)
          local o = {}   
          setmetatable(o, self)
          self.__index = self
          o.x = x or 0
          o.y = y or 0 
          -- and so forth
          return o
        end
    

    Read this:

    https://www.lua.org/pil/16.html

    http://lua-users.org/wiki/ObjectOrientedProgramming