Coder547
Coder547

Reputation: 129

Lua class methods

I'm trying to create Ball class and have some methods in the class but I can't find the right syntax

Tried reading this: https://www.lua.org/pil/16.html

MovingObj = {}

function MovingObj:new(o)
  return o
end

ball = MovingObj:new {}

MovingObj.test = function (self)
  print ("Test!")
end

ball:test()

Error message I get: attempt to call method 'test' (a nil value)

Upvotes: 2

Views: 258

Answers (1)

Nifim
Nifim

Reputation: 5031

o is just a empty table, you dont apply a metatable to it which would allow access to the functions of MovingObj

You can correct this by applying a metatable during your new function:

MovingObj = {}

function MovingObj.new(o) 
  o = o or {}

  local meta = {
    __index = MovingObj -- when o does not have a given index check MovingObj for that index.
  }

  return setmetatable(o, meta) -- return o with the new metatable applied.
end

ball = MovingObj.new({type = "ball"})

function MovingObj:test()
  print ("Test! I'm a " .. self.type)
end

ball:test()

It is also not necessary to use the : syntax for this new function, we are not using the self variable.

Upvotes: 1

Related Questions