我正在尝试在 Lua 中使用自调用匿名函数,并且看到了一些奇怪的行为。
这个:
(function ()
print("self-invoking approach")
end)()
print("standard approach")
工作正常并打印以下输出:
self-invoking approach
standard approach
但颠倒两者:
print("standard approach")
(function ()
print("self-invoking approach")
end)()
导致此错误:
➜ hammerspoon lua temp.lua
standard approach
lua: temp.lua:1: attempt to call a nil value
stack traceback:
temp.lua:1: in main chunk
[C]: in ?
奇怪的是,当代码在 Lua REPL 中运行时,失败只发生在函数形式为 second 时,并且两个调用都包装在一个被调用的外部函数中:
function foo()
print("standard approach")
(function ()
print("self-invoking approach")
end)()
end
foo()
这里发生了什么事?
最佳答案
这是一个解析歧义。非工作案例被解析为:
print("standard approach")(function ()
print("self-invoking approach")
end)()
换句话说,它正在打印
standard approach
,然后取该 print
的返回值(这是 nil
),并尝试使用您的自调用函数作为参数来调用它(之后它也会尝试调用它的结果,如果它还没有崩溃)。要修复它,请在第一个 print
的末尾添加一个分号函数调用。
关于function - 在 Lua 中自调用匿名函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62030588/