Reputation: 353
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
Upvotes: 2
Views: 667
Reputation: 2263
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
Upvotes: 2