Learn SugarBeginner

Functions and namespaces

Call named operations, pass arguments, use returned values, and distinguish namespaces from object properties.

A function is a named operation. Calling a function tells Sugar to run that operation.

Call a function

A function call places parentheses after its name:

upper("hello")

upper() returns the string "HELLO". Because the call produces a value, it is also an expression.

The value supplied between the parentheses is an argument:

round(4.7)

Separate several arguments with commas:

clamp(health, 0, 100)

This passes three values to clamp(). The function returns health limited to the range from 0 through 100.

A function that needs no arguments still uses parentheses:

timeOfDay()

Use the returned value

A returned value can appear anywhere another value of that type could appear:

let loudMessage = upper("critical hit");
let safeHealth = clamp(health, 0, 100);

text "{loudMessage}: {safeHealth} HP";

Not every function returns a value. Some functions perform an effect. Later lessons introduce those functions only after explaining the feature they affect.

Group functions in a namespace

A namespace groups related functions under one name. Sugar’s random functions belong to Rand:

Rand::pick("Truth", "Dare")
Rand::chance(25)
Rand::roll("1d20")

The :: operator accesses a name inside a namespace. Read Rand::chance(25) as “call chance from Rand with the argument 25.”

Namespaces keep broad names such as pick, use, and new attached to the feature that gives them meaning.

NamespacePurpose
RandRandom choices, chances, and dice
DateDates and the current time
DurationAmounts of elapsed time
IdUnique identifiers
ItemInventory and host Item operations
LoreLore balances and changes
SessionSession lifecycle operations

Each namespace is taught with its feature. This table is a map, not a list to memorize.

Namespace access, methods, and properties

These three forms mean different things:

Date::now()
prompts.len()
HOST.name
  • Date::now() calls now from the Date namespace.
  • prompts.len() calls the len method on the value stored in prompts.
  • HOST.name reads the name property from the HOST value.

A method is a function reached through a value. A property is information stored on a compound value. Both use ., but a method call has parentheses.

The next lesson teaches how to declare your own functions, including the difference between parameters in a declaration and arguments in a call.