How can I get the parameters of a function from a function passed as a parameter to my function, in Lua?

Viewed 79

I'm trying to decorate multiple functions with a function decorator, and I want to get the parameters of a function that I'm gonna decorate (in this case called fun in the parameters) and I want to pass as an argument to the returned function (in this case called func) the arguments of the gotten function from the parameters (which is called fun) So it may look like this:

local function decorator(fun)
  local function func(fun.args)
    -- Write here custom behaviour to add to the function 'fun'

    fun(fun.args)
  end

  return func
end

However, obviously there is no such thing as fun.args that was just a way of explaining with more exactitude to you what I want. Take in mind this, I DON'T know the function I want to decorate, and the functions I want to decorate may be different to each other, so this would be a way of ADDING a custom behaviour to a function (as you can see in the code example above)

So, is there a way to do what I'm needing?

1 Answers

Lua supports varargs via .... In your case, you'd use it like this:

local function decorator(fun)
  local function func(...)
    -- Write here custom behaviour to add to the function 'fun'

    fun(...)
  end

  return func
end

And if you want to use the arguments in the "custom behaviour" section, then you can do local args = {...}, and then access them numerically (e.g., args[1] would contain the first argument).

Related