Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store lua functions in queue to be executed later

Tags:

lua

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
like image 896
nicolauscg Avatar asked Jun 13 '26 15:06

nicolauscg


2 Answers

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.

like image 121
Piglet Avatar answered Jun 17 '26 23:06

Piglet


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
like image 28
luther Avatar answered Jun 18 '26 01:06

luther