2
我是Lua的开端,我试图编写继承。Lua和继承:无法访问函数中的自我对象
我从这里做的例子,这个例子是工作: http://lua-users.org/wiki/ObjectOrientationTutorial
所以我做了我的班努力保持本教程的语法,但我不能访问派生类的功能。
这是我的基类代码:
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
派生类的代码:
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
最后的主要功能:
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")
预先感谢任何帮助
无关更换
,但':新的()'这里没有创建新的对象,所以你初始化类表就好像它是一个实例。 – 2014-09-26 15:56:56