您能否以类似于Ruby的方式为LUA中的函数(不在类中)设置别名?在ruby中你会做这样的事情:
alias new_name_for_method method()
def method()
new_name_for_method() # Call original method then do custom code
i = 12 # New code
end
Run Code Online (Sandbox Code Playgroud)
我问,因为我正在开发一个使用LUA脚本的程序,我需要覆盖在默认文件中声明的函数.
在Lua中,函数是值,被视为任何其他值(数字,字符串,表等).您可以通过任意数量的变量引用函数值.
在你的情况下:
local oldmethod = method
function method(...)
oldmethod(...)
i = 12 -- new code
end
Run Code Online (Sandbox Code Playgroud)
请记住
function method() end
Run Code Online (Sandbox Code Playgroud)
是简写:
method = function() end
Run Code Online (Sandbox Code Playgroud)
function() end只创建一个函数值,我们将其赋值给变量method.我们可以转而在十几个其他变量中存储相同的值,或者为变量分配一个字符串或数字method.在Lua中,变量没有类型,只有值.
更多插图:
print("Hello, World")
donut = print
donut("Hello, World")
t = { foo = { bar = donut } }
t.foo.bar("Hello, World")
assert(t.foo.bar == print) -- same value
Run Code Online (Sandbox Code Playgroud)
FYI,当包装函数时,如果你希望它的旧行为现在和永远不受影响,即使它的签名发生了变化,你需要转发所有参数并返回值.
对于预钩子(在旧的之前调用的新代码),这是微不足道的:
local oldmethod = method
function method(...)
i = 12 -- new code
return oldmethod(...)
end
Run Code Online (Sandbox Code Playgroud)
后挂钩(旧的后调用的新代码)有点贵; Lua支持多个返回值,我们必须将它们全部存储起来,这需要创建一个表:
local oldmethod = method
function method(...)
local return_values = { oldmethod(...) }
i = 12 -- new code
return unpack(return_values)
end
Run Code Online (Sandbox Code Playgroud)