Noah Stride
Noah Stride

Reputation: 45

Lua and OOP (What am I doing wrong?)

Im learning to code lua and believe I have come quite far and recently picked up the LOVE2D engine. Ive decided to try some OOP to sort out my coding however all efforts seem to fail with the error

main.lua:31: Attempt to call field "Draw"(nil value)

function love.load()
Unicorn = {
    name = "Default",
    breedname = "Default Class of a unicorn",
    description = "Quite a default Unicorn",
    imgclass = love.graphics.newImage("UnicornA.gif"),
    x = 20,
    y = 20,
    height = 0,
    width= 0,
    age = 0,
    maxage = 20,
    health = 100
    }
function Unicorn.Draw(self)
    love.graphics.draw(self.imgclass, self.x, self.y)
end
function Unicorn:new(o)
    o = o or {}
    setmetatable(o, self)
    self._index = self
    return o
end
alfred = Unicorn:new()
alfred.x = 50
harry = Unicorn:new()
end

function love.draw()
    love.graphics.print("Unicorn Farm Simulator 2014", 0, 0)
    alfred.Draw(alfred)
    harry.Draw(harry)
end

To clear things up love.draw is a callback and so is love.load. I am creating the class Unicorn with a Draw function and a New function, the new function creates an Instantation of the Class ( Am i right with that vocabulary?)

Sorry about using full capital acronym for the language, I just presumed it stood for something!

Upvotes: 1

Views: 152

Answers (1)

Tim
Tim

Reputation: 2151

Make self._index = self to self.__index = self, because _index is nonsense here.

You could read more about OO in Lua in this answer I have made.

Bonus:

  1. Make Unicorn.Draw(self) to Unicorn:Draw(), to get rid of self. And use it in this way

    alfred:Draw()
    harry:Draw()
    
  2. Use local as possible as it can be. Because local is faster and friendly to memory usage.

Upvotes: 1

Related Questions