Functions, Subs, and Return

Functions and Subs let you group logic into reusable routines. Return is used to leave a routine, and functions can return a value.

Back to Language Reference


Function

Function <name>([<parameter>[, <parameter>...]]) [As <typeName>] <statements> End Function <name> [As <typeName>] Function Add(x As Integer, y) As Integer Return x + y End Function

Classic type suffixes work here too.

Function Add#(left%, right!) Return left% + right! End Function

If you use both a suffix and an As type, they must agree.

Sub

Sub <name>([<parameter>[, <parameter>...]]) <statements> End Sub Sub Render() Graphics 800, 600 End Sub

Array Reference Parameters

A parameter can accept an array of any rank. Write empty parentheses after the parameter name for a one-dimensional parameter, or include commas for higher-rank arrays.

<name>() [As <typeName>] <name>(,) [As <typeName>]

Inside the function or sub body, you can use ArrayLen and index access on the parameter exactly as you would with a regular array variable.

Function Sum(values() As Integer) As Integer Dim total As Integer Dim i As Integer total = 0 For i = 0 To ArrayLen(values) - 1 total = total + values[i] Next i Return total End Function Dim scores(5) As Integer Dim result As Integer scores[0] = 10 scores[1] = 20 result = Sum(scores)

The rank in the declaration must match the rank of the array passed at the call site. Passing a scalar or an array of the wrong rank is a compiler error.

You can also pass a single row of a multi-dimensional array to a one-dimensional array parameter by indexing the first dimension at the call site:

Dim grid(4, 8) As Integer result = Sum(grid[2])

See Arrays for a full beginner-friendly walkthrough, including the sub-array passing pattern.

Return

Return Return <expression>