Control flow
Make decisions with if, repeat work with for, loop, while and until, and leave loops early.
Programs make decisions and repeat things. OSL does both with a small set of statements, and every block, the code a statement controls, goes in round brackets.
if, else if, else#
int temperature = 23
if temperature > 30 (
log "hot"
) else if temperature > 15 (
log "warm"
) else (
log "cold"
)The ( that opens a block goes at the end of the line that owns it. else can sit on the same line as the ) before it, as here, or start the next line.
Conditions are combined with and and or, and flipped with !:
int age = 20
boolean member = false
if age >= 18 and !member (
log "adult, not a member"
)
if age < 13 or member (
log "discount"
)Choosing a value#
When you want a value rather than to run statements, use if as an expression, with then and else:
int count = 3
string noun = if count == 1 then "item" else "items"
log `${count} ${noun}`
int score = 72
string grade = if score >= 90 then "A"
else if score >= 70 then "B"
else "C"
log gradeGuards#
A condition followed by return, break or continue can sit on one line. These guards keep the main path of a function flat:
def describe(int n) string (
if n < 0 return "negative"
if n == 0 return "zero"
return "positive"
)
log describe(-4)
log describe(0)
log describe(9)Anything else in an if needs a block.
Repeating a number of times#
loop repeats a block. for does the same and also counts, from 1 up to the number:
loop 3 (
log "hip hip"
)
log "hooray"
for i 4 (
log i * i
)Looping over things#
for ... in goes through the items of an array, the characters of a string or the entries of an object. Give it two names to get the position as well:
string[] tasks = ["write", "test", "ship"]
for task in tasks (
log "- " ++ task
)
for n, task in tasks (
log `${n}. ${task}`
)To count between two numbers, loop over a range:
for year in 2020 to 2023 (
log year
)while and until#
while repeats as long as its condition is true. until repeats until its condition becomes true:
int n = 27
int steps = 0
while n != 1 (
n = if n % 2 == 0 then n / 2 else (n * 3) + 1
steps++
)
log steps
int tries = 0
until tries == 3 (
tries++
)
log triesLeaving early#
break leaves the loop it's in. continue skips to the next time round:
for n in 1 to 10 (
if n % 2 == 0 continue
if n > 7 break
log n
)Blocks and names#
A variable declared inside a block belongs to that block, and disappears when it ends:
boolean ready = true
if ready (
string message = "inside"
)
log messageDeclare it before the block when you need it afterwards:
boolean ready = true
string message = "before"
if ready (
message = "changed inside"
)
log messageHow many times does for i 5 ( ... ) run its block, and what is i the first time?
Which of these is a complete, valid statement?
FizzBuzz
Print the numbers 1 to 15, but print Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both.
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz