Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Functions

FUNCTION area(width, height)
    RETURN width * height
END FUNCTION

PRINT area(3, 4)
12

A function can be used above the line it’s written on. I read the whole program before running any of it, so the order doesn’t matter.

Defaults, and as many as you like

A parameter can have a value to fall back on. And a last parameter with ... after it collects everything else into a list.

FUNCTION greet(who, greeting = "Hello", mark = "!")
    RETURN greeting + ", " + who + mark
END FUNCTION

FUNCTION total(first, rest...)
    LOCAL sum = first             // LOCAL: more on that in a moment
    FOR value = rest
        sum = sum + value
    END FOR
    RETURN sum
END FUNCTION

PRINT greet("Ada")
PRINT greet("Bob", "Howdy")
PRINT total(1, 2, 3, 4)
Hello, Ada!
Howdy, Bob!
10

** goes the other way: it spreads a list out into arguments in order, or a map into arguments by name.

FUNCTION greet(who, greeting = "Hello", mark = "!")
    RETURN greeting + ", " + who + mark
END FUNCTION

words = ["Cy", "Welcome"]
options = {mark: "?", greeting: "Is that you"}
PRINT greet(**words)
PRINT greet("Di", **options)
Welcome, Cy!
Is that you, Di?

From Python: rest... is your *args, and ** spreads both lists and maps.

From JavaScript: rest... is your ...rest, and ** is your spread.

From Lua: rest... is your ..., already packed into a list.

Whose variable is it?

This one matters, so slow down. A variable you give a value to is shared by the whole program — even if the line is inside a function. LOCAL makes one that belongs to the function alone.

score = 0

FUNCTION win(points)
    LOCAL bonus = points * 2     // only exists in here
    score = score + bonus        // the program's score
END FUNCTION

win(5)
win(1)
PRINT score
12

Parameters are the function’s own, like a LOCAL.

From BASIC: Just like you’re used to, except it’s LOCAL for the function’s own.

From Python: The other way round from you! No global needed to change a shared variable — and you need LOCAL to not share one.

From JavaScript: LOCAL is your let. Leaving it off is like assigning to a global.

From Lua: Exactly your rule: shared unless you say LOCAL.

A function is a keyword already

A line can call a function without the parentheses. That’s all PRINT is doing.

FUNCTION cheer(who, times = 1)
    PRINT "Go " + who + "!" * times
END FUNCTION

cheer("Ada", 2)
cheer "Bob", 3
Go Ada!!
Go Bob!!!

Telling people about it

A comment with three slashes above a function is its documentation. Editors show it when someone hovers over the name, and I can turn a whole program’s worth into a reference page.

/// How much room a rectangle takes up.
/// !returns: the width times the height
/// !example: PRINT area(3, 4)
FUNCTION area(width, height)
    RETURN width * height
END FUNCTION

PRINT area(5, 5)
25