在Lua中,如何从作为参数传递给函数的函数中获取函数的参数?

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)

那么,先生,有没有一种方法可以满足我的需求?事先非常感谢您!

评论
  • 逗小逼
    逗小逼 回复

    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).