2

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)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.