3

I am using functions from a lua-based library and I would like to store those different functions with varying parameter counts in a queue to be executed later on when I need to. Here is a similar question and solution for javascript.

Below is an example that works, but conditionals are done manually for each parameter count. Is there a cleaner way to do this in lua? Keep in mind I cannot modify the library's function implementation since I dont have access to their code.

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
nicolauscg
  • 115
  • 1
  • 5
  • General sidenote: Since `#` operator is `O(f(n))`, you should cache it's result in a variable if you're going to access it multiple times. – dualed Aug 11 '19 at 12:29

2 Answers2

4

You can simply use table.unpack to convert your args table back to a parameter list.

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

newObj should be local btw.

Piglet
  • 27,501
  • 3
  • 20
  • 43
2

This looks like a perfect case for anonymous functions:

local theQueue = {
  function() aFunc(param) end,
  function() aDifferentFunc(param1, param2) end,
}
for _, action in ipairs(theQueue) do
  action()
end
luther
  • 5,195
  • 1
  • 14
  • 24
  • 1
    all functions in Lua are anonymous. they don't have names. references to them do. – Piglet Aug 09 '19 at 07:12
  • 1
    @Piglet: To me, an anonymous function is any function that's defined without immediately assigning it to an explicit name. The term is important because it means we must be constructing a function on the fly instead of pre-defining it, and that it can't be recursive. What you're describing sounds more like first-class functions. In fact, names in *any* language are just abstractions. They're always independent from their values at a deep enough level. – luther Aug 09 '19 at 14:47