Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to extend a method? #7

Closed
ghost opened this issue Mar 1, 2017 · 2 comments
Closed

How to extend a method? #7

ghost opened this issue Mar 1, 2017 · 2 comments

Comments

@ghost
Copy link

ghost commented Mar 1, 2017

Hello. I want to extend existing method when extending a class (just add a new function to it, not owerwrite), but don't know how to do it. Here is an example:

local Object = require "classic"
local A = Object:extend()

function A:new()
  function self.sayHi()
    print("Hi from A!")
  end
end

local B = A:extend()

function B:new()
  B.super.new(self)
  function self.sayHi()
    -- B.super.sayHi() -- not working
    print("Hi from B!") -- overwrites
  end
end

local b = B()
b.sayHi() -- Hi from B only!
@rxi
Copy link
Owner

rxi commented Mar 1, 2017

Methods should be declared outside of the new function and should use : instead of . when created and called. When calling a super method self should be passed to it:

local Object = require "classic"


local A = Object:extend()

function A:new()
end

function A:sayHi()
  print("Hi from A!")
end


local B = A:extend()

function B:new()
  B.super.new(self)
end

function B:sayHi()
  B.super.sayHi(self)
  print("Hi from B!")
end


local b = B()
b:sayHi()

-- prints:
-- Hi from A!
-- Hi from B!

@ghost
Copy link
Author

ghost commented Mar 1, 2017

Thank you!

@ghost ghost closed this as completed Mar 1, 2017
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant