Crash BASIC Control Flow Reference

Quick reference for control flow constructs.

Conditionals

IF / ELSEIF / ELSE

' Single line
IF x > 10 THEN PRINT "Large"

' Multi-line
IF score >= 90 THEN
  PRINT "Grade: A"
ELSEIF score >= 80 THEN
  PRINT "Grade: B"
ELSE
  PRINT "Grade: C"
END IF

SELECT CASE

SELECT CASE grade
  CASE 90 TO 100
    PRINT "A"
  CASE 80 TO 89
    PRINT "B"
  CASE ELSE
    PRINT "C or lower"
END SELECT

Loops

FOR / NEXT

FOR i = 1 TO 10
  PRINT i
NEXT i

FOR x = 0 TO 320 STEP 10
  PSET (x, 100), 15
NEXT

WHILE / WEND

WHILE x < 100
  x = x + 1
WEND

DO / LOOP

' Test at start
DO WHILE x < 10
  x = x + 1
LOOP

' Test at end (runs at least once)
DO
  INPUT "Continue? ", ans$
LOOP UNTIL UCASE$(ans$) = "N"

EXIT (Early Loop Exit)

FOR i = 1 TO 100
  IF i = 50 THEN EXIT FOR
NEXT

DO
  IF done THEN EXIT DO
LOOP

Procedures

SUB (No Return Value)

SUB DrawBox(x1, y1, x2, y2, color)
  LINE (x1, y1)-(x2, y2), color, B
END SUB

CALL DrawBox(10, 10, 50, 50, 15)

FUNCTION (Returns Value)

FUNCTION Add(a AS INTEGER, b AS INTEGER) AS INTEGER
  Add = a + b
END FUNCTION

result = Add(5, 3)

BYVAL vs BYREF

' BYVAL (default) - changes don't affect caller
SUB Test(BYVAL x AS INTEGER)
  x = x + 1  ' Only affects local copy
END SUB

' BYREF - changes DO affect caller
SUB DoubleIt(BYREF n AS INTEGER)
  n = n * 2  ' Modifies original variable
END SUB

value = 5
CALL DoubleIt(value)
PRINT value  ' Prints 10

EXIT SUB / EXIT FUNCTION

SUB CheckValue(n)
  IF n < 0 THEN EXIT SUB
  PRINT n
END SUB

Async Execution

CALL TIMER

' Repeating timer
CALL TIMER GameUpdate() EVERY 16 MILLISECONDS AS "gameLoop"

' One-shot timer
CALL TIMER ShowMessage() AFTER 5 SECONDS AS "reminder"

STOP TIMER "gameLoop"

CALL THREAD

CALL THREAD LoadResources() AS "loader"
STOP THREAD "loader"

CALL RENDER (Synced to Behavior Engine)

' Runs at end of each behavior tick (60 FPS)
' Use for camera tracking, HUD updates
CALL RENDER GameLoop() AS "main"
STOP RENDER "main"

Events

CALL EVENT / EVENT

' Register handler
CALL EVENT OnVictory() AS "player_win"

' Trigger event
IF score >= 1000 THEN EVENT "player_win"

SUB OnVictory()
  PRINT "You won!"
END SUB

Program Control

Statement Purpose
END Terminates program
PAUSE Pauses until keypress
DEBUGGER Triggers debugger breakpoint