Debugging Lua-执行返回和或时出错
我基本上是在做一些测试,以便更好地了解Lua语言。我发现了一个对我来说毫无意义的错误 功能:Debugging Lua-执行返回和或时出错,debugging,error-handling,lua,Debugging,Error Handling,Lua,我基本上是在做一些测试,以便更好地了解Lua语言。我发现了一个对我来说毫无意义的错误 功能: local function d(c) return (!c and print("c", false) or print("c", true)) end local function a(b, c) return (!b and d(c) or print("b", true)) end 当我运行a(1,nil)或a(1,1)时,它会输出b true,但如果我运行a(nil,1)时
local function d(c)
return (!c and print("c", false) or print("c", true))
end
local function a(b, c)
return (!b and d(c) or print("b", true))
end
当我运行a(1,nil)
或a(1,1)
时,它会输出b true
,但如果我运行a(nil,1)
时,它会输出c true
和b true
如果有人能告诉我,为什么它返回两个值,而从技术上来说,这是不可能的?也许你已经明白发生了什么,但我已经写了这篇文章。Lua没有
代码>操作员;我猜你的意思是不是。(如果有人用!
代替而不是,制作了Lua的补丁版本,我不会感到惊讶)
a(nil,1)
返回而不是nil和d(1)或打印(“b”,true)
。现在,not nil
计算为true
,d(1)
计算为nil
,因此我们有true和nil或print(“b”,true)
,反过来计算为nil或print(“b,true)
,从而计算print(“b,true)
至于为什么d(1)
计算为nil:它返回not1并打印(“c”,false)或打印(“c”,true)
。这相当于not 1和nil或nil
,因为print
在调用时总是不返回任何内容,并且操作符和和或都不会将任何内容视为nil
<无论x
是真的还是假的,code>not x和nil或nil总是计算为nil
,因此d
总是返回nil。(唯一的区别是,如果d
接收到一个假值,则两个print
调用都会被计算。)
您可以通过调用type(print('a'))
验证print
是否不返回任何内容:它会将错误“bad argument#1抛出到'type'(预期值)”,而type(nil)
返回“nil”您将返回值与打印输出混淆。最重要的是,您可以在Lua中返回多个值。我知道可以在Lua中返回多个值,但在这种情况下,它应该选择其中一个,而不是两个。但是谢谢你解释我为什么会遇到这个错误。