Objects: obj
obj declares your own type: a name for a group of fields that belong together, and the methods that work on them.
obj Person {
name: str
age: int = 0
fn greet(): str {
return "Hi, I'm ${self.name} (${self.age})"
}
fn birthday() {
self.age = self.age + 1
}
}
ann: Person = Person { name: "Ann", age: 30 }
ann.birthday()
print(ann.greet())
print(ann.name)
print(ann)Output:
Hi, I'm Ann (31)
Ann
Person {name: "Ann", age: 31}- The obj’s name is the type:
ann: Person, likecount: int. - Fields are declared like variables,
name: type, with an optional default:age: int = 0. - Methods are functions inside the obj. In a method,
selfis the object the method was called on. printshows an object with its type and fields.
Making objects
Person { name: "Ann", age: 30 } makes a new object. Fields are given by name, in any order; fields that have a default can be left out:
obj Settings {
theme: str = "light"
size: int = 12
tags: [str] = []
}
a: Settings = Settings {}
b: Settings = Settings { size: 16 }
b.tags[] = "big"
print(a)
print(b)Output:
Settings {theme: "light", size: 12, tags: []}
Settings {theme: "light", size: 16, tags: ["big"]}A field without a default must be given, and a name the obj doesn’t have is an error:
p: Person = Person { age: 3 } // error: a Person needs a value for name (it has no default)
p: Person = Person { name: "Bo", mail: "" } // error: a Person has no field mail (it has name, age)A field’s default is fixed when compiling: a literal, a locked value, an empty list, map or set ([], {}), or an object made of such defaults. An empty list or map default is a new one for each object, so a.tags and b.tags above are separate lists.
init: a constructor
When making an object takes more than setting fields, give the obj an init method. Then objects are made by calling the obj’s name like a function, and init runs on the new object:
obj Account {
owner: str = ""
balance: float = 0.0
log: [str] = []
fn init(owner: str, start: float) {
self.owner = owner.trim()
self.balance = start
self.record("opened")
}
fn record(what: str) {
self.log[] = "${what}: ${self.balance}"
}
fn pay(amount: float): bool {
if amount > self.balance {
self.record("refused ${amount}")
return false
}
self.balance = self.balance - amount
self.record("paid ${amount}")
return true
}
}
acc: Account = Account(" Ann ", 100.0)
print(acc.pay(30.0))
print(acc.pay(500.0))
print(acc.log)Output:
true
false
["opened: 100.0", "paid 30.0: 70.0", "refused 500.0: 70.0"]The rules that keep this simple:
- Every field of an obj with
initneeds a default. The defaults are set first, theninitruns, so no field is ever without a value. The one exception: a field whose type is an obj or a trait can go without a default wheninitsets it first, before anything else usesself. - An obj with
initis always made withAccount(...), so thatinitalways runs. Only its own methods can still useAccount { ... }, for example to make a copy. initreturns nothing.
Objects are shared
Like lists and maps, an object is shared, not copied, when it is assigned to another variable or passed to a function. Both names see the same object:
obj Counter {
count: int = 0
}
fn bump(c: Counter) {
c.count = c.count + 1
}
a: Counter = Counter {}
b: Counter = a
bump(a)
bump(b)
print(a.count)Output:
2To have two separate objects, make two: b: Counter = Counter { count: a.count }.
Objects in objects, lists and maps
Fields can be any type, including other objs and lists or maps of objects. An obj can hold a list of its own type, which makes trees:
obj Node {
value: int
children: [Node] = []
fn sum(): int {
total: int = self.value
self.children.walk(child) {
total = total + child.sum()
}
return total
}
}
tree: Node = Node { value: 1, children: [Node { value: 2 }, Node { value: 3 }] }
tree.children[1].children[] = Node { value: 4 }
print(tree.sum())
print(tree.children[1])
points: {str: Node} = {"top": tree}
points["top"].value = 10
print(tree.value)Output:
10
Node {value: 3, children: [Node {value: 4, children: []}]}
10An obj can’t contain itself directly (next: Node): such an object could never be finished, so it’s a compile error. Hold it in a list instead, as children does, or make the field optional, next: ?Node: it starts as nil.
JSON
An object converts to and from json by field name, which is how JSON data gets into your own types:
obj User {
name: str
age: int = 0
tags: [str] = []
}
data: json = convert("{\"name\": \"Ann\", \"tags\": [\"admin\"], \"extra\": true}")
user: User = convert(data)
print(user)
user.age = 30
out: json = user
print(out)Output:
User {name: "Ann", age: 0, tags: ["admin"]}
{"name":"Ann","age":30,"tags":["admin"]}- Keys the obj doesn’t have are ignored.
- A missing key keeps the field’s default; if the field has none, it’s error 11:
cannot convert a json object to a User: it has no key "name". - A value of the wrong kind is error 11, as with any
convertfrom json. schema(User)gives the type’s JSON Schema, which tells an AI model what JSON to give back (see A schema from a type).
Objects from other files
An obj declared with pub obj can be used by the files that import its file. Its type is written with the file’s name, geo.Point, and so are geo.Point { ... } and geo.Point(...):
File geo.luma:
pub obj Point {
x: float = 0.0
y: float = 0.0
fn move(dx: float, dy: float) {
self.x = self.x + dx
self.y = self.y + dy
}
}import "geo"
p: geo.Point = geo.Point { x: 1.0 }
p.move(2.0, 2.0)
print(p)Output:
geo.Point {x: 3.0, y: 2.0}An obj from another file is printed with that file’s name (not the name it was imported as). Its fields and methods are all usable; an obj without pub stays inside its file.
Traits
Several obj types can share methods through a trait: obj Circle: Shape { ... } says a Circle is a Shape, and a [Shape] list can hold circles and rectangles together.
Details
- An obj is declared at the top level of a file, and can be used anywhere in that file, also before the declaration.
objis a reserved word;selfis a built-in name, usable only in methods.- A field and a method can’t have the same name.
- Comparing objects with
==is a compile error: compare their fields. - In an
ifcondition,Name {starts theifblock, so an object literal there needs parentheses:if (Point { x: 1.0 }).x > 0.0 { ... }. - Objects are freed when nothing uses them anymore, like lists. Objects that refer to each other in a circle (a node in its own
children, or two objects in each other’s lists) are never freed; see Memory.
Not available yet
- Destructors (code that runs when an object is freed): write the cleanup as a method, and call it with
deferwhere the object is made. - Comparing objects with
==.
See Limitations.