function - LUA:在类中使用其名称(字符串)调用函数

标签 function oop lua

我正在尝试使用其名称调用对象的函数(我想使用该名称,因为我将从 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.methodself['method'] 的语法糖.

关于function - LUA:在类中使用其名称(字符串)调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26042599/

相关文章:

function - Scala中方法和函数的区别

r - 函数内 ddply 未找到对象错误

java - java中的棋盘和棋子设计

c - 将 ZMQ 上下文从 C 传递到嵌入式 Lua

javascript - 调用过程并传递 2 个参数 Javascript

javascript 函数在其他文件中不起作用

java - 为什么我们有非静态函数/方法?

C++:设计、函数模板重写和缺乏多态性

c - Lua C API 推送现有指针

algorithm - 填表保存规则