20,741
edits
m (→Conditionals) |
|||
| Line 1: | Line 1: | ||
{{Template:Nasal Navigation}} | {{Template:Nasal Navigation}} | ||
Sometimes you may only want to execute certain portions of your code, depending on conditions. This can be accomplished in several ways. One of the most straightforward ways being an '''if''' expression, which has the form: | |||
<pre> | |||
if (condition) | |||
{ | |||
# true block, will be executed if condition is true | |||
} | |||
else { | |||
# false block, will be executed if condition is false | |||
} | |||
</pre> | |||
To negate the whole thing, use the '''!''' operator: | |||
<pre> | |||
if (!condition) | |||
{ | |||
# false block, will be executed if condition is true | |||
} | |||
else { | |||
# true block, will be executed if condition is false | |||
} | |||
</pre> | |||
== Conditionals == | == Conditionals == | ||
Nasal has no "statements", which means that any expression can appear in any context. This means that you can use an if/else clause to do what the ?: does in C. | Nasal has no "statements", which means that any expression can appear in any context. This means that you can use an if/else clause to do what the ?: (ternary operator) does in C. | ||
The last semicolon in a code block is optional, to make this prettier | The last semicolon in a code block is optional, to make this prettier | ||
<syntaxhighlight lang="php"> | <syntaxhighlight lang="php"> | ||
var abs = func(n) { if(n<0) { -n } else { n } } | var abs = func(n) | ||
{ | |||
if(n<0) | |||
{ return -n } | |||
else | |||
{ return n } | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 150: | Line 180: | ||
( a and do_something() ) or print("failed"); | ( a and do_something() ) or print("failed"); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== Using Hashs to map keys to functions == | == Using Hashs to map keys to functions == | ||