-
Notifications
You must be signed in to change notification settings - Fork 2
If Statements
The Language Reference - If Statements
Sometimes it's handy to be able to toggle compilation of code based on some constant expression, or to conveniently branch on some conditional flag, without having to create all the labels yourself. An if
statement in nel provides both of these things.
The syntax of a simple if statement takes the form if condition then ...statements end
, where condition is a condition to check, and statements are what to run when this condition is true.
If the condition is a constant expression, it is used to toggle the compilation of certain subsections of code, and the statements will only be inserted into the final code if the expression is nonzero:
// Conditional compilation
let DEBUG = 1
if DEBUG then
a: get #10
end
Alternatively, the condition can be something that is allowed in a [[goto ... when|Branches]]
statement -- in fact, those statements are embedded into the translated if
, and are subject to the same limits on jump distances). Here is an example:
// Conditional branching at runtime.
a: get @player.hp
if zero then
call player.death
end
// More-or-less equivalent assembly for an if statement, except that the labels are private in the former.
begin
a: get @player.hp
goto end_if when not zero
begin
call player.death
end
def end_if:
end
An if
statement may optionally by followed by an else
, before the end
, which is the code to execute when a condition is false. This works for both compile-time and run-time variations of the if
statement. Here is an example with an else
clause:
// If and else.
a: get @player.hp
if zero then
call player.death
else
call player.hurt
end
// More-or-less equivalent assembly for an if/else statement, except that the labels are private in the former.
begin
a: get @player.hp
goto else_block when not zero
begin
call player.death
goto end_if
end
def else_block:
begin
call player.hurt
end
def end_if:
end
There is also an elseif ... then
clause which works very similar to else
with another if
statement inside, except you can discard an end
with the former:
// Using 'if'/'elseif'/'else'
a: cmp @number
if = then
call match
elseif < then
call number_is_higher
else
call number_is_lower
end
// Using strictly 'if'/'else', note that unlike the former, we need an extra 'end'.
a: cmp @number
if = then
call match
else
if < then
call number_is_higher
else
call number_is_lower
end
end