Variables
:= makes a variable. Its type comes from the value:
name := "noa" // string
hp := 100 // int
alive := true // bool
print(name, hp, alive)
noa 100 true
You can also write the type first, like in C:
int.long big := 5
unsigned int count := 7
char letter := 'A'
print(big, count, letter)
5 7 A
Without a value, a variable starts at zero: 0, false, or an empty string.
int score
string note
print(score, "[{note}]")
0 []
Changing a value
= changes the value of a variable that exists:
hp := 100
hp = 70
hp -= 20
print(hp)
50
Using = on a name that doesn't exist yet is an error, so a typo can't quietly make a new variable.
Replacing a variable
:= on a name that already exists replaces the variable. The old one is gone, the new one gets a new place in memory, and its type may change:
x := 5
first := x.address
x := "five"
print(x, x.address != first)
five true
:= replaces the variable wherever it was made, also from inside an if, a loop or a function:
score := 10
won := true
if won {
score := 500
}
print(score)
500
Inside an if, loop, switch or function, the replacement has to keep the type. Otherwise nobody could know the type after the block:
x := 5
lucky := true
if lucky { x := "seven" }This doesn't compile.
Constants
const MAX_HP := 100
const NAME := "corfli"
print(MAX_HP, NAME)
100 corfli
A constant's value is worked out when compiling, so it can only use literals and other constants.
address
x.address is where the variable is in memory. Printing it shows a hexadecimal number like 0x7ffd5e10.
destroy
x.destroy() overwrites the variable with zeros, frees its memory, and removes the name:
base := "hunter"
password := "{base}2"
password.destroy()
password := "new"
print(password)
new
The zeros are always written; the compiler never removes them. Using the name after destroy is a compile error:
pin := "1234"
pin.destroy()
print(pin)This doesn't compile.
A copy made earlier (b := a) is its own variable and needs its own destroy.
Top-level variables and functions
Variables made at the top level of main.cfl can be used and changed by the functions in that file:
total := 0
fn add(int n) { total += n }
add(5)
add(10)
print(total)
15