And*_*ldo 1 lua function ternary-operator
我在 codewars 中遇到了这个问题,如下所示:
实现一个函数,该函数将根据布尔值运行 2 个不同的函数。当然,也可以用简单的if语句来实现。像这样:
function _if(bool, func1, func2)
if bool then return func1() else return func2() end
end
Run Code Online (Sandbox Code Playgroud)
但是,当我想使用三元运算符解决它时,它并没有通过所有测试用例:
function _if(bool, func1, func2)
return bool and func1() or func2()
end
Run Code Online (Sandbox Code Playgroud)
但这有效:
function _if(bool, func1, func2)
return (bool and func1 or func2)()
end
Run Code Online (Sandbox Code Playgroud)
我想我根本没有足够的关于 Lua 的知识。我已经在社区中搜索过这个,但找不到任何明确的解释。我想知道是否有人可以对此有所了解,或者只是建议一些可能有助于我理解的文章。
更新 编辑
那么,如果func1
总是返回真值,那么第二个片段与第三个片段有何不同?
function _if(bool, func1, func2)
if bool then return func1() else return func2() end
end
Run Code Online (Sandbox Code Playgroud)
如果 bool 为真,则上面的代码返回 func1(),否则返回 func2()。
以下代码将返回func2()
if bool
is not true 或 if bool
is true and func1()
is not true。只有func1()
当bool
和func1()
都为真时才会返回。
function _if(bool, func1, func2)
return bool and func1() or func2()
end
Run Code Online (Sandbox Code Playgroud)
如果 bool 为真,最后一段代码将返回 func1(),否则返回 func2()。
function _if(bool, func1, func2)
return (bool and func1 or func2)()
end
Run Code Online (Sandbox Code Playgroud)
所以首先,Lua 没有任何三元运算符。巧妙地使用 and 比 or 更高的优先级,相当于 C 的 ? 等三元运算符:
其次,a = b and c or d
只有当 c 为真时,表达式才能正常工作。如果您将函数调用用作 c,情况可能并非总是如此。
这是一种方便的赋值方式,但在许多情况下,它会提高可读性并减少错误,只需坚持使用 if else 语句即可。
一旦您必须添加更多条件,这些条件和/或技巧就会变得一团糟。
所以让我们再看看第二个片段中发生了什么。
function _if(bool, func1, func2)
return bool and func1() or func2()
end
Run Code Online (Sandbox Code Playgroud)
首先bool
,func1()
将被评估。如果bool
不为真,Lua 不必调用,func1()
因为表达式永远不会为真。所以Lua可以func2()
马上去评估。您的函数将返回func2()
!
相反,如果bool
是true
,Lua 会调用func1()
看看它是否也是true
。如果func1()
返回true
,Lua 不会调用func2()
。由于以下原因or
,表达式将始终为true
ifbool
和func1()
is true
。如果func1()
返回 false/nil 则or
必须对其进行评估。所以 Lua 也会调用func2()
,然后返回它的返回值。
了解运算符优先级很重要,在哪些情况下 Lua 将中止计算表达式!
Luaor
和and
运算符使用捷径计算。仅在必要时评估第二个操作数
归档时间: |
|
查看次数: |
4789 次 |
最近记录: |