【问题标题】:store lua functions in queue to be executed later将lua函数存储在队列中以便稍后执行
【发布时间】:2019-12-16 19:03:59
【问题描述】:

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

以下是一个可行的示例,但条件是手动为每个参数计数完成的。在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

【问题讨论】:

  • 一般旁注:由于# 运算符是O(f(n)),如果你要多次访问它,你应该将它的结果缓存在一个变量中。

标签: lua


【解决方案1】:

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

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

newObj 应该是本地 btw。

【讨论】:

  • 添加到您的答案中,table.unpack 用于 lua v5.2 或更高版本,否则使用 unpack
【解决方案2】:

这看起来像是匿名函数的完美案例:

local theQueue = {
  function() aFunc(param) end,
  function() aDifferentFunc(param1, param2) end,
}
for _, action in ipairs(theQueue) do
  action()
end

【讨论】:

  • Lua 中的所有函数都是匿名的。他们没有名字。对他们的引用确实如此。
  • @Piglet:对我来说,匿名函数是任何在定义时没有立即为其指定显式名称的函数。这个术语很重要,因为它意味着我们必须动态构建一个函数而不是预先定义它,并且它不能是递归的。您所描述的听起来更像是一流的功能。事实上,any 语言中的名称只是抽象。他们总是在足够深的层面上独立于他们的价值观。
猜你喜欢
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 2010-10-25
  • 2013-06-12
  • 1970-01-01
  • 2020-09-08
  • 2021-02-01
相关资源
最近更新 更多