Ternary conditional operator: Difference between revisions

Content deleted Content added
m Add a citation to the Python manual
Line 490:
</syntaxhighlight>
 
This will succeed unless {{code|a}} is logically false (i.e. {{code|lang=lua|false}} or {{code|lang=lua|nil}}); in this case, the expression will always result in {{code|b}}. This can result in some surprising behaviour if ignored.
 
There are also other variants that can be used, but they're generally more verbose:
 
<syntaxhighlight lang="lua">
-- parentheses around the table literal are required
var = (
{
[true] = a,
[false] = b
}
)[not not cond]
</syntaxhighlight>
 
Luau, a dialect of Lua, has ternary expressions that look like if statements, but unlike them, they have no {{code|lang=lua|end}} keyword, and the {{code|lang=lua|else}} clause is required. One may optionally add {{code|lang=lua|elseif}} clauses. It's designed to replace the {{code|lang=lua|cond and a or b}} idiom and is expected to work properly in all cases.<ref>{{Cite web |title=Syntax |url=https://luau-lang.org/syntax |access-date=2023-02-07 |website=Luau |language=en}}</ref>
 
<syntaxhighlight lang="lua">
-- in Luau
var = if cond then a else b
 
-- with elseif clause
sign = if var < 0 then -1 elseif var == 0 then 0 else 1
</syntaxhighlight>
 
=== Objective-C ===