将lua函数存储在队列中以便稍后执行

我正在使用基于lua的库中的函数,并希望将具有不同参数计数的这些不同函数存储在队列中,以便在需要时稍后执行。这里有一个类似的javascript问题和解决方法 Here

下面是一个有效的示例,但是对于每个参数计数都需要手动执行条件操作。是否有更干净的方法可以在lua中完成此操作?请记住,由于我无权访问他们的代码,因此不能修改库的函数实现。

Action = {}
function Action:new(func, ...)
  newObj = {
    func = func or nil,
    args = {...} or {}
  }
  self.__index = self
  return setmetatable(newObj, self)
end
function Action:execute()
  if #self.args == 0 then
    self.func()
  elseif #self.args == 1 then
    self.func(self.args[1])
  elseif #self.args == 2 then
    self.func(self.args[1], self.args[2])
  -- and so on
end

theQueue = {
  Action:new(aFunc, param),
  Action:new(aDifferentFunc, param1, param2)
}
for _, action in ipairs(theQueue) do
  action:execute()
end
点赞
用户3574628
用户3574628

这看起来是使用匿名函数的完美情况:

local theQueue = {
  function() aFunc(param) end,
  function() aDifferentFunc(param1, param2) end,
}
for _, action in ipairs(theQueue) do
  action()
end
2019-08-09 05:10:28
用户2858170
用户2858170

你可以简单地使用table.unpack将参数表转换回参数列表。

self.func(table.unpack(self.args))

newObj应该是本地的。

2019-08-09 07:22:49