【发布时间】: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