L1VM - course 07
L1VM - course 07
loops
In this part of the course I show how to use loops in Brackets.
for loop
// hello-for - Brackets - Hello world! do loop
//
#include <intr.l1h>
(main func)
(set int64 1 zero 0)
(set int64 1 one 1)
(set int64 1 loop 0)
(set int64 1 maxloop 10)
(set int64 1 f 0)
// set string length automatic, by setting "s"
(set string s hello "Hello world!")
// print string
// for
(zero loop =)
(for-loop)
(((loop maxloop <) f =) f for)
print_s (hello)
// print newline
print_n
((loop one +) loop =)
(next)
exit (zero)
(funcend)
Here the include uses the “intr.l1h” include file. So we can use “print_s” and “print_n” macros. The loop continues running until “loop” is less than “maxloop”. In the line:
((loop one +) loop =)
the variable “loop” is increased by one. For loops can be used if you know how many times the loop should be run. Here is the output:
$ l1vm prog/hello-for -q
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
You can nest the for loops in each other to do more complex stuff!
do while loop
The do while loop is ran at least once. The check is done at the end of the loop:
// hello-while - Brackets - Hello world! do loop
//
#include <intr.l1h>
(main func)
(set int64 1 zero 0)
(set int64 1 one 1)
(set int64 1 loop 0)
(set int64 1 maxloop 10)
(set int64 1 f 0)
// set string length automatic, by setting "s"
(set string s hello "Hello world!")
// print string
// while
(zero loop =)
(do)
print_s (hello)
// print newline
print_n
((loop one +) loop =)
(((loop maxloop <) f =) f while)
exit (zero)
(funcend)
In the lines:
((loop one +) loop =)
(((loop maxloop <) f =) f while)
“loop” is increased by one. And is compared to “maxloop”. If “loop” is less than “maxloop” then the “do while” loop is ran.
Here is the output:
$ l1vm prog/hello-while -q
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
The “do while” loops can also be nested into more complex loops.