【问题标题】:Condition evaluating incorrectly (Lua 4)条件评估不正确(Lua 4)
【发布时间】:2020-11-24 22:01:45
【问题描述】:

我正在尝试在 Lua 4 中使用此功能:

function ternary(cond, T, F)
    if cond then return T else return F end
end

在这种情况下:

loadHW1 = false
print(ternary(loadHW1 == true, "this should not appear", nil))

但是,当我希望结果为nil 时,总是会打印文本。我究竟做错了什么?谢谢。

[编辑]

我切换到这个,但仍然得到“这是真的”结果:

loadHW1 = 0
print(ternary(loadHW1, "this is true", "this is false"))

【问题讨论】:

    标签: lua ternary


    【解决方案1】:

    Lua 4 没有布尔值:它们是在 Lua 5 中引入的。

    在 Lua 4 中,只有 nil 是假的;其他任何东西,包括 0,都是真的。

    在您的代码中, falsetrue 被解释为未定义的全局变量,因此它们的计算结果都为零。因此,loadHW1 == true 变为 nil == nil,这是真的,所以 ternarycond 接收 1。

    如果你想在 Lua 4 中使用falsetrue,定义如下:

    false = nil
     true = 1
    

    【讨论】:

    • 我更新了问题。切换到数字,当它应该是假的时候,我仍然得到一个真实的结果。
    • @posfan12,只有 nil 为假; 0 为真。
    猜你喜欢
    • 2011-08-04
    • 1970-01-01
    • 2019-09-23
    • 2019-03-16
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 2013-03-09
    相关资源
    最近更新 更多