ON

Syntax:

on <byte or int index> goto label [ ,label ...]

or:

on <byte or int index> gosub label [ ,label ...]

The ON language construct creates a conditional branch that accepts an index and a list of labels. The expression index will be evaluated and the corresponding label from the list will be passed to GOTO or GOSUB.

If index is an integer, it will be implicitly truncated to a byte. The maximum number of labels in the list is therefore 256.

Note #1: The list of labels is zero-indexed, which means that if index evaluates to 0, the first label will be matched, if it evaluates to 1, the second, etc..

Note #2: The runtime will not check if index is within the number of labels. If index is larger than the number of labels minus one, the program will (most probably) break.

Example:

rem -- i! holds a value between 0 and 2 
on i! goto case0, case1, case2
end
case0:
  print "i! equals 0"
  end
case1:
  print "i! equals 1"
  end
case2:
  print "i! equals 2"
  end
  

Performance tip

An ON … GOTO or ON … GOSUB construct is faster than its IF … THEN GOTO/GOSUB equivalent. It's especially useful when branching on a TRUE/FALSE condition, for example:

rem -- branching using IF ... THEN
rem -- assume x! is a zero or one (TRUE/FALSE) value

if x! = 0 then goto false_case else goto true_case

rem -- same as above but FASTER

on x! goto false_case, true_case