Add If Keyword
36
If-Keyword.md
Normal file
36
If-Keyword.md
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
Keyword: `if`
|
||||||
|
|
||||||
|
Syntax: `if $bool %line`
|
||||||
|
|
||||||
|
Time Complexity:
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
The `if` keyword allows you to jump to a label or line if a condition is true. It is a core part of the ground programming language, as it would not be [Turing Complete](https://en.wikipedia.org/wiki/Turing_completeness) without.
|
||||||
|
|
||||||
|
## Example usage
|
||||||
|
```grnd
|
||||||
|
@label
|
||||||
|
if false %label
|
||||||
|
```
|
||||||
|
The second line checks if `false` is true. Obviously this is false, so nothing happens and program execution continues.
|
||||||
|
|
||||||
|
However, consider this code:
|
||||||
|
```grnd
|
||||||
|
@label
|
||||||
|
if true %label
|
||||||
|
```
|
||||||
|
The second line checks if `true` is true. This is true, so the program jumps back to `@label`, creating an infinite loop.
|
||||||
|
|
||||||
|
A more practical example would be to repeat some code a certain amount of times, e.g. 5
|
||||||
|
|
||||||
|
```grnd
|
||||||
|
set &loop_counter 0
|
||||||
|
@start_loop
|
||||||
|
equal $loop_counter 5 &cond # if loop_counter equals 5, set cond to true, otherwise set cond to false
|
||||||
|
if $cond %end_loop # If cond (i.e. if loop_counter equals 5), exit the loop
|
||||||
|
# Do some code
|
||||||
|
add $loop_counter 1 &loop_counter # Increment loop_counter
|
||||||
|
jump %start_loop # Repeat
|
||||||
|
@exit_loop
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user