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),则输出 c trueb true

如果有人能告诉我为什么它会返回两个值,而这在技术上是不可能的,我将不胜感激。

点赞
用户9383219
用户9383219

也许你已经明白发生了什么,但我已经写下了这篇文章。Lua没有 ! 运算符;我猜你是指 not。 (如果有人已经制作了一个用 ! 替代 not 的 Lua 补丁版本,我也不会感到惊讶。)

a(nil, 1) 返回 not nil and d(1) or print("b", true)。现在,not nil 计算结果为 true,而 d(1) 的计算结果为 nil,所以我们得到 true and nil or print("b", true),这进一步计算为 nil or print("b", true),因此 print("b", true) 被计算。

至于为什么 d(1) 的计算结果为 nil:它返回 not 1 and print("c", false) or print("c", true)。这相当于 not 1 and nil or nil,因为 print 在被调用时总是返回空值,空值被操作符 andor 视为 nilnot x and nil or nil 总是计算结果为 nil,无论 x 是否为真值,因此 d 总是返回 nil。(唯一的区别在于,如果 d 接收到一个假值,两个 print 调用都会被计算。)

你可以通过调用 type(print('a')) 验证 print 返回空值,它会抛出错误 "bad argument #1 to 'type' (value expected)",而 type(nil) 返回 "nil"

2018-11-09 23:16:22