我正在尝试使用其名称调用对象的函数(我想使用该名称,因为我将从 URL 中检索函数的名称)。
我是 LUA 的初学者,所以我试图了解什么是可能的(或不可能!)
在这个例子中,我想从我的主文件中执行对象“controllerUser”的函数“creerCompte()”。
我创建了一个主文件:
--We create the controller object
local controller = require("controllers/ControllerUser"):new()
local stringAction = "creerCompte" -- Name of the function to call in the controller Object
--Attempting to call the function stringAction of the object controller
local action = controller:execute(stringAction)
这是 Controller 对象
ControllerUser = {}
ControllerUser.__index = ControllerUser
function ControllerUser:new()
local o = {}
setmetatable(o, self)
return o
end
function ControllerUser:execute(functionName)
loadstring("self:" .. functionName .. "()") --Doesn't work: nothing happens
getfenv()["self:" .. functionName .. "()"]() --Doesn't work: attempt to call a nil value
_G[functionName]() --Doesn't work: attempt to call a nil value
self:functionName() -- Error: attempt to call method 'functionName' (a nil value)
end
function ControllerUser:creerCompte()
ngx.say("Executed!") --Display the message in the web browser
end
return ControllerUser
在此先感谢您的帮助
最佳答案
试试 self[functionName](self)
而不是 self:functionName()
.self:method()
是 self.method(self)
的快捷方式和 self.method
是 self['method']
的语法糖.
关于function - LUA:在类中使用其名称(字符串)调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26042599/