Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Ternary conditional operator
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Lua === Lua does not have a traditional conditional operator. However, the short-circuiting behaviour of its {{code|and}} and {{code|or}} operators allows the emulation of this behaviour: <syntaxhighlight lang="lua"> -- equivalent to var = cond ? a : b; var = cond and a or b </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 Β§ If-then-else expressions|url=https://luau-lang.org/syntax#if-then-else-expressions |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>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)