在Lua中,如何从作为参数传递给我的函数的函数中获取函数的参数?
我试图用一个函数装饰器装饰多个函数,我想得到我要装饰的函数的参数(在本例中,参数中称为在Lua中,如何从作为参数传递给我的函数的函数中获取函数的参数?,lua,decorator,variadic-functions,Lua,Decorator,Variadic Functions,我试图用一个函数装饰器装饰多个函数,我想得到我要装饰的函数的参数(在本例中,参数中称为fun),我想作为参数传递给返回的函数(在本例中称为func)从参数中获取函数的参数(称为fun) 所以它可能看起来像这样: local function decorator(fun) local function func(fun.args) -- Write here custom behaviour to add to the function 'fun' fun(fun.args)
fun
),我想作为参数传递给返回的函数(在本例中称为func
)从参数中获取函数的参数(称为fun
)
所以它可能看起来像这样:
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
local function decorator(fun)
local function func(...)
-- Write here custom behaviour to add to the function 'fun'
fun(...)
end
return func
end
然而,很明显,没有所谓的fun.args
只是一种更准确地向你解释我想要什么的方式。记住这一点,我不知道我想要修饰的函数,而且我想要修饰的函数可能彼此不同,因此这将是一种向函数添加自定义行为的方法(如上面的代码示例所示)
那么,有没有办法满足我的需要 Lua通过
…
支持varargs。在您的情况下,您可以这样使用它:
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
local function decorator(fun)
local function func(...)
-- Write here custom behaviour to add to the function 'fun'
fun(...)
end
return func
end
如果要使用“自定义行为”部分中的参数,则可以执行localargs={…}
,然后以数字形式访问它们(例如,args[1]
将包含第一个参数)