2

I am a begginner in Lua and I am trying to code inheritance.

I have done the example from here and this example is working: http://lua-users.org/wiki/ObjectOrientationTutorial

So I've done my classes trying to keep the tutorial syntax but I can't access a derived class function.

This is my code for the base class:

Controller = {page_title = "", view = "index"}
Controller.__index = Controller

setmetatable(Controller, {
__call = function (cls, ...)
  local self = setmetatable({}, cls)
  self:new(...)
  return self
end,
})

function Controller:new()
end

-- Execute the function given in parameter
function Controller:execute(functionName)        
    if(self[functionName] ~= nil) then
        self[functionName]()
    else
        ngx.say("Cette page n'existe pas")
    end
end

The code for the derived class:

require("controllers/Controller")

ControllerUser = {page_title = ""}
ControllerUser.__index = ControllerUser

setmetatable(ControllerUser, {
  __index = Controller, -- this is what makes the inheritance work
  __call = function (cls, ...)
    local self = setmetatable({}, cls)
    self:new(...)
    return self
  end,
})

function ControllerUser:new()
    Controller:new()
    ngx.say('created!') --Displayed one time
    return self
end



function ControllerUser:creerCompte()
    ngx.say("Executed!") --Displays correctly the message
    ngx.say(self.page_title) -- Error: attempt to index local 'self' (a nil value)

end

return ControllerUser

Finally the main function:

local controller = require("controllers/ControllerUsers"):new() --tried without new but it doesn't change anything

-- Call the function "creerCompte" of the class ControllerUsers (which inherits from Controller)
controller:execute("creerCompte")

Thanks in advance for any help

1
  • Unrelated, but :new() here doesn't create a new object, so you're initializing the class table as if it were an instance. Commented Sep 26, 2014 at 15:56

1 Answer 1

2

Try replacing

function Controller:execute(functionName)        
    if(self[functionName] ~= nil) then
        self[functionName]()
    else
        ngx.say("Cette page n'existe pas")
    end
end

with

function Controller:execute(functionName)        
    if(self[functionName] ~= nil) then
        self[functionName](self)
    else
        ngx.say("Cette page n'existe pas")
    end
end
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.