Examples
18 complete programs, in the order to read them: from a first line through functions, classes and modules to small programs that do a real job. They are the programs in the IDE's Load an example menu. Run one here, or open it in the IDE to change it and run it again. The numbers are those of the engine's own examples; number 15 is left out here because it needs a library that only the native cuffc allows.
1Hello World
Smallest possible CuffScript program.
note: Smallest possible CuffScript program.
print("Hello, CuffScript!")
2Values and text
The basic values, constants and f-strings, and how positions in text and lists are counted.
note: The basic values, constants and f-strings, and how positions in text and lists are counted.
use DLC:string
number age = 25
str name = "Ann"
boolean active = true
list scores = [90, 85, 77]
map profile = {"name": "Ann", "city": "Seoul"}
constant number MAX_AGE = 120
print(name, age, active)
print(scores, profile)
print(f"{name} is {age}; the limit is {MAX_AGE}")
note: change gives an existing variable a new value.
age = age + 1
print(age)
note: Positions start at 1, a negative position counts from the end, and a~b includes both ends.
str city = "Seoul"
print(city[1], city[-1], city[2~4])
print(scores[1], scores[-1], scores[2~3])
note: Text is counted in characters, not bytes.
str hangul = "안녕하세요"
print(length(hangul), hangul[2~3], hangul[-1])
note: Arithmetic: / divides, % is the remainder, ** is a power, and ** binds tighter than a minus.
print(7 / 2, 7 % 3, 2 ** 10, -2 ** 2)
note: empty is the value of "nothing"; find gives it when the pattern is not there.
any digits = find("no digits here", p"[num]+")
print(digits is empty)
3Decisions and loops
Choosing with if, and repeating with loop repeat, loop while and loop each.
note: Choosing with if, and repeating with loop repeat, loop while and loop each.
number temperature = 18
if temperature > 25 do:
print("hot")
else if temperature > 15 do:
print("mild")
else do:
print("cold")
end
note: Every value can be a condition. 0, empty, "", [] and {} are false; everything else is true.
print(to_boolean(0), to_boolean("0"), to_boolean([]), to_boolean([0]))
note: and / or stop as soon as the answer is known and give a boolean; ! reverses a condition.
number hour = 14
if hour >= 9 and hour < 18 do:
print("open")
end
if !(hour is 14) or hour is 3 do:
print("never printed")
end
note: loop repeat counts through a range. A loop does not open a scope, so i is still there afterwards.
loop repeat number i = 1 ~ 3 do:
print(i * i)
end
print("after the loop, i is", i)
note: A range runs backwards when the start is larger.
loop repeat number k = 3 ~ 1 do:
print(k)
end
number n = 1
loop while n < 20 do:
n = n * 3
end
print(n)
note: loop each visits list items, map keys and text characters; skip moves on, stop ends the loop.
loop each str word in ["red", "", "blue", "stop", "green"] do:
if word is "" do:
skip
end
if word is "stop" do:
stop
end
print(word)
end
loop each str key in {"a": 1, "b": 2} do:
print(key)
end
loop each str ch in "한글" do:
print(ch)
end
4Functions
Functions: parameters and their types, defaults, recursion, scope, global and pure.
note: Functions: parameters and their types, defaults, recursion, scope, global and pure.
func sum(number a, number b) do:
return a + b
end
print(sum(2, 3))
note: A function may be called above the line that declares it.
print(double(21))
func double(number x) do: return x * 2 end
note: A parameter may have a default, worked out at each call; it can use the parameters before it.
func greet(str name, str word = "Hello", str line = word + ", " + name + "!") do:
return line
end
print(greet("Ann"))
print(greet("Bob", "Hi"))
print(greet("Cy", "Yo", "custom line"))
note: A function that ends without return gives empty.
func nothing() do:
number unused = 1
end
print(nothing() is empty)
note: Recursion.
func factorial(number n) do:
if n <= 1 do:
return 1
end
return n * factorial(n - 1)
end
print(factorial(10))
note: A function sees only its own variables. global connects a variable of the program.
number counter = 0
func bump() do:
global counter
counter = counter + 1
end
bump()
bump()
print(counter)
note: Without global the name is not visible, and the error can be caught.
func peek() do:
return counter
end
number seen = peek() or_else do:
print("counter is not visible here")
seen = -1
end
print(seen)
note: A pure function may not use globals or call functions that are not pure.
pure func square(number n) do:
return n * n
end
print(square(12))
5Lists and maps
Lists and maps: adding, changing and removing, slicing, nested values, and sharing.
note: Lists and maps: adding, changing and removing, slicing, nested values, and sharing.
list inventory = ["sword", "shield"]
add "potion" to inventory
inventory[1] = "magic staff"
print(inventory)
remove at 2 from inventory
print(inventory)
remove "potion" from inventory
print(inventory)
map profile = {"name": "Bob"}
profile["level"] = 50
print(profile)
remove "level" from profile
print(profile)
note: change, add and remove work on anything that holds a value, however deep.
list grid = [[1, 2], [3, 4]]
add 5 to grid[1]
grid[2][1] = 30
print(grid)
map team = {"scores": [10, 20]}
add 30 to team["scores"]
print(team)
note: Slices take both ends; negative positions count from the end.
list nums = [10, 20, 30, 40, 50]
print(nums[2~4], nums[-1], nums[-3~-1])
str greeting = "Hello World"
print(greeting[1~5], greeting[-5~-1])
note: Lists, maps and objects are shared, not copied. copy makes a separate list, one level deep.
list a = [1, 2, 3]
list b = a
add 4 to b
print(a)
list c = copy(a)
add 5 to c
print(a, c)
note: A position that does not exist is an error, which or_else can catch.
number safe_value = nums[99] or_else do:
print("position 99 does not exist; using 0")
safe_value = 0
end
print(f"safe_value = {safe_value}")
6Text and patterns
Pattern-matching commands from docs/reference/patterns.md, all wired to a real matcher.
note: Pattern-matching commands from docs/reference/patterns.md, all wired to a real matcher.
str log_line = "2026-03-31 [ERROR] 192.168.0.1 - DB Connection Lost"
match parsed = match(log_line, p"<date:[num]4-[num]2-[num]2> \[[one:INFO|WARN|ERROR]\] <ip:[num]1~3\.[num]1~3\.[num]1~3\.[num]1~3> - <msg:[any]+>")
if parsed is not empty do:
print(f"date={parsed['date']}")
print(f"ip={parsed['ip']}")
print(f"msg={parsed['msg']}")
end
str article = "Tickets T-101 T-202 T-303 are booked"
list codes = find_all(article, p"T-[num]3")
print(codes)
str phone_log = "call me at 010-1234-5678 today"
str masked = replace(phone_log, p"[num]4-[num]4", "****-****")
print(masked)
list parts = split("apple, banana,cherry", p",[sp]*")
print(parts)
print(count(article, p"[num]+"))
note: the i flag makes a pattern case-insensitive
str answer = "YES"
if answer matches p"yes"i do:
print("the i flag ignores case")
end
note: the [one:...] alternative token and an escaped dot (\.)
if "photo.jpg" matches p"[str]+\.[one:jpg|png|gif]" do:
print("Image filename pattern matched")
end
note: Patterns work per character, so Hangul counts one by one, and can be written inside a pattern.
str hangul = "안녕하세요"
if hangul matches p"[any]5" do:
print("[any]5 matched five Hangul characters")
end
match who = match("이름: 홍길동", p"이름: <name:[any]+>")
print(f"captured name: {who['name']}")
note: [let], [str] and [word] mean English letters only.
if !(hangul matches p"[let]+") do:
print("[let] does not match Hangul")
end
7Error recovery with or_else
or_else runs a block when the statement before it fails with an error that can be caught.
note: or_else runs a block when the statement before it fails with an error that can be caught.
number a = 10
number b = 0
number result = a / b or_else do:
print("division by zero; using -1")
result = -1
end
print(f"result = {result}")
note: A position that does not exist is an error too.
list items = ["a", "b", "c"]
str safe_item = items[99] or_else do:
safe_item = "(none)"
end
print(f"safe_item = {safe_item}")
note: find finding nothing is not an error: it gives empty, so or_else does not run.
any config = find("no digits here", p"[num]+")
if config is empty do:
config = "default_mode"
end
print(f"config = {config}")
note: or_else guards one statement. Use `as` to get the error as an object.
number n = to_number("abc") or_else as Error err do:
print(err.code)
print(err.message)
n = 0
end
print(n)
8Errors as objects (fail)
Errors as objects: fail raises one, or_else as Error catches it, and classes tell kinds apart.
note: Errors as objects: fail raises one, or_else as Error catches it, and classes tell kinds apart.
class ValidationError extends Error do:
str field = ""
func init(str field, str message) do:
super.init(message)
self.field = field
end
end
class OutOfStock extends Error do:
end
map stock = {"apple": 3, "pear": 0}
func order(str item, number count) do:
global stock
if count < 1 do:
fail ValidationError("count", "an order needs at least one item")
end
if !(item matches p"[low]+") do:
fail ValidationError("item", f"'{item}' is not a valid item name")
end
if stock[item] < count do:
fail OutOfStock(f"only {stock[item]} {item}(s) left")
end
stock[item] = stock[item] - count
return f"ordered {count} {item}"
end
func try_order(str item, number count) do:
print(order(item, count)) or_else as Error err do:
if err isa ValidationError do:
print(f"invalid {err.field}: {err.message}")
else if err isa OutOfStock do:
print(f"sorry, {err.message}")
else do:
print(f"{err.code} {err.message}")
end
end
end
try_order("apple", 2)
try_order("apple", 0)
try_order("Apple!", 1)
try_order("pear", 1)
try_order("plum", 1)
note: errors raised by the engine arrive as the same Error object
print(10 / 0) or_else as Error err do:
print(err.code, err.message)
print(f"at line {err.line}, column {err.column}")
end
note: fail err raises a caught error again, for a caller further out
func checked(str item) do:
order(item, 1) or_else as Error err do:
print("logging:", err.message)
fail err
end
end
checked("pear") or_else as Error err do:
print("caller got", type_of(err))
end
print(stock)
9Async and await
An async function called without await starts a task and gives a Task at once. A task runs when the program waits for something: await of a task, time_sleep, or a network request. While one task waits, the others run, so their waits overlap. await of a call runs the call right there.
note: An async function called without await starts a task and gives a Task at once. A task runs when the
note: program waits for something: await of a task, time_sleep, or a network request. While one task waits,
note: the others run, so their waits overlap. await of a call runs the call right there.
use DLC:time
async func brew(str drink, number seconds) do:
print("[task] " + drink + " started")
time_sleep(seconds)
print("[task] " + drink + " ready")
return drink
end
async func notify(str message) do:
print("[task] note: " + message)
end
print("[main] start")
Task tea = brew("tea", 0.3)
Task coffee = brew("coffee", 0.1)
notify("the kettle is on")
note: nothing has waited yet, so no task has run
print("[main] two drinks ordered; tea done yet? " + to_str(tea.done()))
note: awaiting coffee lets every task run; coffee is ready first
print("[main] got " + await coffee)
print("[main] got " + await tea + ", done: " + to_str(tea.done()))
note: an error in a task is raised again at its await, where or_else can catch it
async func burnt() do:
time_sleep(0.05)
fail "the toast is burnt"
end
Task toast = burnt()
await toast or_else as Error e do:
print("[main] caught: " + e.message)
end
note: await of a call runs it right here, like any call
str cup = await brew("cocoa", 0)
print("[main] end, with " + cup)
10Classes
Classes: fields, methods, a constructor, private state and objects as values.
note: Classes: fields, methods, a constructor, private state and objects as values.
class Player do:
str name = "unknown"
number x = 0
list items = []
private number steps = 0
func init(str name, number x = 0) do:
self.name = name
self.x = x
end
func sayhello() do:
print(f"Hello, I am {self.name}")
end
func turnleft() do:
self.steps = self.steps + 1
end
func walk(number distance) do:
self.x = self.x + distance
self.steps = self.steps + 1
end
func pick(str item) do:
add item to self.items
end
func report() do:
return f"{self.name} is at {self.x} after {self.steps} step(s), carrying {self.items}"
end
func to_str() do:
return f"Player({self.name})"
end
end
Player player1 = Player("Ann")
player1.sayhello()
player1.walk(3)
player1.turnleft()
player1.pick("lamp")
print(player1.report())
note: each object has its own fields
Player player2 = Player("Bob", 10)
player2.pick("map")
print(player1.items, player2.items)
note: objects are shared, not copied, when you assign them
Player alias = player1
alias.walk(2)
print(player1.x, player1 is alias, player1 is player2)
Player twin = player1.copy()
twin.walk(100)
print(player1.x, twin.x)
note: print and f-strings use to_str, and the class name is a type
print(player1)
print(f"{player2} is a {type_of(player2)}")
func describe(Player p) do:
return p.name + " at " + to_str(p.x)
end
print(describe(player2))
note: a name that the class does not declare is an error, which or_else can catch
print(player1.nickname) or_else as Error err do:
print(err.code)
print(err.message)
end
11Inheritance
Inheritance: extends, overriding methods, super, and treating a child as its parent.
note: Inheritance: extends, overriding methods, super, and treating a child as its parent.
class Shape do:
str name = "shape"
func init(str name) do:
self.name = name
end
func area() do:
return 0
end
func describe() do:
return f"{self.name} with area {self.area()}"
end
end
class Rectangle extends Shape do:
number width = 0
number height = 0
func init(number width, number height) do:
super.init("rectangle")
self.width = width
self.height = height
end
func area() do:
return self.width * self.height
end
end
class Square extends Rectangle do:
func init(number side) do:
super.init(side, side)
self.name = "square"
end
func describe() do:
return super.describe() + ", all sides equal"
end
end
class Circle extends Shape do:
number radius = 1
func init(number radius) do:
super.init("circle")
self.radius = radius
end
func area() do:
return 3 * self.radius ** 2
end
end
list shapes = [Rectangle(3, 4), Square(5), Circle(2)]
loop each Shape shape in shapes do:
print(shape.describe())
end
note: isa asks whether an object is of a class or one of its descendants
loop each Shape shape in shapes do:
print(shape.name, shape isa Shape, shape isa Rectangle, shape isa Square)
end
note: a parameter typed with the parent class accepts every child
func total_area(list items) do:
number total = 0
loop each Shape item in items do:
total = total + item.area()
end
return total
end
print(total_area(shapes))
note: the parent's constructor is called explicitly with super.init(...)
Square sq = Square(2)
print(sq.width, sq.height, sq.name)
12The with block
with: call several methods and use fields of one object without repeating its name.
note: with: call several methods and use fields of one object without repeating its name.
class Robot do:
str name = "R2"
number x = 0
number y = 0
str facing = "north"
list log = []
func init(str name) do:
self.name = name
end
func move(number steps) do:
self.y = self.y + steps
add f"moved {steps}" to self.log
end
func turnleft() do:
if self.facing is "north" do:
self.facing = "west"
else if self.facing is "west" do:
self.facing = "south"
else if self.facing is "south" do:
self.facing = "east"
else do:
self.facing = "north"
end
add "turned left" to self.log
end
func status() do:
return f"{self.name} at ({self.x}, {self.y}) facing {self.facing}"
end
end
Robot rover = Robot("Rover")
Robot wall_e = Robot("Wall-E")
with rover do:
move(3)
turnleft()
move(2)
print(status())
end
note: the object's fields come before the outer variables of the same name
number y = 1000
with wall_e do:
y = y + 7
print(y, .y)
print(name)
end
print(y)
note: .name always means the object of the innermost with
with rover do:
with wall_e do:
print(.name, status())
end
print(.name, log)
end
note: a variable made inside the block is gone after it, and return works through it
func faster(Robot a, Robot b) do:
with a do:
number mine = y
with b do:
if mine > .y do:
return a.name
end
end
end
return b.name
end
print(faster(rover, wall_e))
13Modules
use <name> from <folder> loads <folder>/<name>.cuff. Its functions and constants become available.
2 files: main.cuff, lib/greetings.cuff
note: use <name> from <folder> loads <folder>/<name>.cuff. Its functions and constants become available.
use greetings from ./lib
print(greet("CuffScript"))
print(DEFAULT_GREETING)
lib/greetings.cuff
constant str DEFAULT_GREETING = "Hello"
func greet(str name) do:
global DEFAULT_GREETING
return DEFAULT_GREETING + ", " + name + "!"
end
14Libraries
The libraries (DLC): math, string, random, list, map, convert and json.
note: The libraries (DLC): math, string, random, list, map, convert and json.
use DLC:math, DLC:string, DLC:random
use DLC:list
use DLC:map
use DLC:convert
use DLC:json
print(math_sqrt(16), math_abs(-5), math_max(3, 7, 2))
print(str_upper("hello"), str_trim(" padded "))
print(contains("hello world", "world"))
note: Random numbers: with a seed the same program gives the same numbers on one machine.
random_seed(7)
number roll = random_int(1, 6)
print(roll >= 1 and roll <= 6)
note: List functions return new lists and leave the original alone.
list scores = [5, 2, 8, 1, 9, 2]
print(list_sort(scores))
print(list_reverse(scores))
print(list_unique(scores))
print(scores)
print(list_join(["a", "b", "c"], ", "))
note: Map functions.
map ages = {"ann": 31, "bob": 27}
print(map_keys(ages), map_values(ages), map_has_key(ages, "bob"))
note: Conversion between types.
print(to_number("42.5") + 1, to_str(123) + "!", to_boolean(""))
note: JSON text and back.
map config = {"name": "홍길동", "level": 42, "tags": ["a", "b"]}
print(to_json(config))
print(to_json(config, 2))
map loaded = from_json("{\"x\": 1, \"items\": [10, 20]}")
print(loaded["items"][2])
16Program: word frequency
Count how often each word occurs in a text and print the three most common ones.
note: Count how often each word occurs in a text and print the three most common ones.
use DLC:string
use DLC:list
use DLC:map
str text = "The quick brown fox jumps over the lazy dog. The dog sleeps; the fox runs."
note: find_all gives every run of letters; upper case makes "The" and "the" the same word.
list words = find_all(str_upper(text), p"[let]+")
print(f"{length(words)} words, {length(list_unique(words))} different")
map counts = {}
loop each str word in words do:
if map_has_key(counts, word) do:
counts[word] = counts[word] + 1
else do:
counts[word] = 1
end
end
note: Pick the most frequent word three times, taking it out each time. Ties go to the earlier word.
list remaining = list_sort(map_keys(counts))
loop repeat number rank = 1 ~ 3 do:
str best = remaining[1]
loop each str word in remaining do:
if counts[word] > counts[best] do:
best = word
end
end
print(f"{rank}. {best} ({counts[best]})")
remove best from remaining
end
17Program: inventory
A small shop inventory: two classes that work together, and the result written as JSON.
note: A small shop inventory: two classes that work together, and the result written as JSON.
use DLC:json
class Item do:
str name = ""
number price = 0
number quantity = 0
func init(str name, number price, number quantity = 1) do:
self.name = name
self.price = price
self.quantity = quantity
end
func total() do:
return self.price * self.quantity
end
func to_str() do:
return f"{self.quantity} x {self.name} at {self.price}"
end
end
class Inventory do:
list items = []
func add_item(Item item) do:
add item to self.items
end
func total_value() do:
number sum = 0
loop each Item item in self.items do:
sum = sum + item.total()
end
return sum
end
func find_item(str name) do:
loop each Item item in self.items do:
if item.name is name do:
return item
end
end
return empty
end
end
Inventory shop = Inventory()
shop.add_item(Item("apple", 3, 10))
shop.add_item(Item("pear", 4, 5))
shop.add_item(Item("melon", 12))
print(shop.total_value())
Item apples = shop.find_item("apple")
print(apples)
apples.quantity = apples.quantity - 4
print(apples, shop.total_value())
if shop.find_item("kiwi") is empty do:
print("no kiwi in stock")
end
print(to_json(shop))
18Program: bank account
An account that refuses what it cannot do by raising errors, including an error class of its own.
note: An account that refuses what it cannot do by raising errors, including an error class of its own.
use DLC:list
class InsufficientFunds extends Error do:
number shortfall = 0
end
class Account do:
str owner = ""
number balance = 0
private list history = []
func init(str owner, number opening = 0) do:
self.owner = owner
self.balance = opening
end
func deposit(number amount) do:
if amount <= 0 do:
fail "a deposit must be more than zero"
end
self.balance = self.balance + amount
self.record("deposit", amount)
end
func withdraw(number amount) do:
if amount > self.balance do:
InsufficientFunds problem = InsufficientFunds(f"cannot withdraw {amount} from {self.balance}")
problem.shortfall = amount - self.balance
fail problem
end
self.balance = self.balance - amount
self.record("withdraw", amount)
end
func statement() do:
return list_join(self.history, "; ")
end
private func record(str kind, number amount) do:
add f"{kind} {amount}" to self.history
end
end
Account account = Account("Ann", 100)
account.deposit(50)
account.withdraw(30)
account.withdraw(500) or_else as Error err do:
print(err.message)
if err isa InsufficientFunds do:
print("short by", err.shortfall)
end
end
account.deposit(-5) or_else as Error err do:
print(err.code, err.message)
end
account.record("tamper", 1) or_else as Error err do:
print(err.code)
end
print(account.balance)
print(account.statement())
19Program: log summary
Read log lines with a pattern, count them by level and by user, and skip lines that do not fit.
note: Read log lines with a pattern, count them by level and by user, and skip lines that do not fit.
use DLC:list
use DLC:map
list lines = [
"2026-11-02 09:15:01 INFO user=ann action=login",
"2026-11-02 09:15:44 WARN user=bob action=retry",
"this line is not a log entry",
"2026-11-02 09:16:02 INFO user=bob action=login",
"2026-11-02 09:17:30 ERROR user=ann action=upload",
"2026-11-02 09:18:12 INFO user=ann action=logout"
]
pattern entry = p"<date:[num]4-[num]2-[num]2> <time:[num]2:[num]2:[num]2> <level:[up]+> +user=<user:[word]+> action=<action:[word]+>"
map by_level = {}
map by_user = {}
number skipped = 0
loop each str line in lines do:
any found = match(line, entry)
if found is empty do:
skipped = skipped + 1
skip
end
str level = found["level"]
str user = found["user"]
if !map_has_key(by_level, level) do:
by_level[level] = 0
end
if !map_has_key(by_user, user) do:
by_user[user] = 0
end
by_level[level] = by_level[level] + 1
by_user[user] = by_user[user] + 1
end
print("by level:")
loop each str level in list_sort(map_keys(by_level)) do:
print(f" {level}: {by_level[level]}")
end
print("by user:")
loop each str user in list_sort(map_keys(by_user)) do:
print(f" {user}: {by_user[user]}")
end
print(f"skipped {skipped} line(s)")