在 Lua 中,如何从作为参数传递给我的函数的函数中获取函数的参数?
How can I get the parameters of a function from a function passed as a parameter to my function, in Lua?
我正在尝试用一个函数装饰器来装饰多个函数,我想获取我要装饰的函数的参数(在这种情况下,参数中称为 fun
),我想要将参数(称为 fun
)中获取的函数的参数作为参数传递给返回的函数(在本例中称为 func
)
所以它可能看起来像这样:
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
但是,显然没有 fun.args
这只是一种更准确地向您解释我想要什么的方式。记住这一点,我不知道我想要装饰的功能,我想要装饰的功能可能彼此不同,所以这将是一种向功能添加自定义行为的方法(如您所见在上面的代码示例中)
那么,有什么方法可以满足我的需求吗?
Lua 通过 ...
支持可变参数。在你的情况下,你会像这样使用它:
local function decorator(fun)
local function func(...)
-- Write here custom behaviour to add to the function 'fun'
fun(...)
end
return func
end
如果您想使用 "custom behaviour" 部分中的参数,那么您可以执行 local args = {...}
,然后以数字方式访问它们(例如,args[1]
将包含第一个参数).
我正在尝试用一个函数装饰器来装饰多个函数,我想获取我要装饰的函数的参数(在这种情况下,参数中称为 fun
),我想要将参数(称为 fun
)中获取的函数的参数作为参数传递给返回的函数(在本例中称为 func
)
所以它可能看起来像这样:
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
但是,显然没有 fun.args
这只是一种更准确地向您解释我想要什么的方式。记住这一点,我不知道我想要装饰的功能,我想要装饰的功能可能彼此不同,所以这将是一种向功能添加自定义行为的方法(如您所见在上面的代码示例中)
那么,有什么方法可以满足我的需求吗?
Lua 通过 ...
支持可变参数。在你的情况下,你会像这样使用它:
local function decorator(fun)
local function func(...)
-- Write here custom behaviour to add to the function 'fun'
fun(...)
end
return func
end
如果您想使用 "custom behaviour" 部分中的参数,那么您可以执行 local args = {...}
,然后以数字方式访问它们(例如,args[1]
将包含第一个参数).