【问题标题】:LUA: Call a function using its name (string) in a classLUA:在类中使用其名称(字符串)调用函数
【发布时间】:2014-11-20 11:07:43
【问题描述】:

我正在尝试使用其名称调用对象的函数(我想使用该名称,因为我将从 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)

这是控制器对象

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

提前感谢您的帮助

【问题讨论】:

    标签: function oop lua


    【解决方案1】:

    试试self[functionName](self) 而不是self:functionName()

    self:method()self.method(self) 的快捷方式,self.methodself['method'] 的语法糖。

    【讨论】:

      【解决方案2】:

      在 Lua 中,函数没有名字。您用作名称的内容要么是变量的名称,要么是表中的键(通常是全局变量表)

      如果是全局变量,当然可以使用_G['name'](args...),如果namevar 变量中有名称,则当然可以使用_G[namevar](args...)。但这很容易以多种方式破坏(不适用于本地函数或模块内的函数等)

      更好(也更安全)的是创建一个表,其中只包含您想要提供的功能,并使用您想要用作表键的名称:

      local function doOneThing(args)
          -- anything here
      end
      
      local function someOtherThingToDo()
          -- ....
      end
      
      exportFuncs = {
          thing_one = doOneThing,
          someOtherThingToDo = someOtherThingToDo,
      }
      

      然后,您可以轻松地从名称中调用该函数:exportFuncs[namevar](...)

      【讨论】:

        猜你喜欢
        • 2017-09-29
        • 1970-01-01
        • 1970-01-01
        • 2010-12-19
        • 1970-01-01
        • 2019-05-10
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多