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.
| Namespace | Purpose |
|---|---|
Rand | Random choices, chances, and dice |
Date | Dates and the current time |
Duration | Amounts of elapsed time |
Id | Unique identifiers |
Item | Inventory and host Item operations |
Lore | Lore balances and changes |
Session | Session 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()callsnowfrom theDatenamespace.prompts.len()calls thelenmethod on the value stored inprompts.HOST.namereads thenameproperty from theHOSTvalue.
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.