The tour, 6 of 11
Structs and Classes
Values and objects, constructors, Methods, Properties, and inheritance.
A Struct is a value: assigning it copies it, like an Int. A Class is an object: assigning
it shares it, and it’s freed the moment nothing refers to it, so there’s no Delete.
Structs
A Struct gets a constructor that takes its Fields in order. A Method that changes the Struct is
ByRef.
Import std.core
Struct Point
Field x: Int
Field y: Int
Method Distance(): Int => Abs(x) + Abs(y)
ByRef Method Move(dx: Int, dy: Int)
x += dx
y += dy
End Method
End Struct
Function Abs(n: Int): Int => n < 0 ? -n : n
Local a = Point(3, -4)
Local b = a // a copy
b.Move(1, 1)
Print("a is ({a.x}, {a.y}), b is ({b.x}, {b.y}), {a.Distance()} steps away")Output
a is (3, -4), b is (4, -3), 7 steps away
Classes
A Class’s New is its constructor, and its Destroy runs when the last reference to it goes.
Import std.core
Class Door
Field name: String
Field open: Bool
New(name: String)
Self.name = name
End New
Method Toggle()
open = !open
Print("{name} is {open ? "open" : "shut"}")
End Method
Method Destroy()
Print("{name} is gone")
End Method
End Class
Local front = Door("the front door")
Local same = front // the same door
same.Toggle()
front.Toggle()
front = Door("the back door")
Print("done")Output
the front door is open the front door is shut done the front door is gone the back door is gone
Properties
A Property looks like a Field from outside and runs code on the inside.
Import std.core
Class Player
Field hp: Int = 100
Property Alive: Bool
Get => hp > 0
End Property
Property Health: Int
Get => hp
Set(value)
hp = value < 0 ? 0 : value
End Set
End Property
End Class
Local p = Player()
p.Health = -20
Print(p.Health, p.Alive)Output
0 False
Inheritance
A Class Extends one other, and a Method marked Override takes the place of its base’s.
Import std.core
Class Enemy
Field name: String
Field hp: Int = 100
New(name: String)
Self.name = name
End New
Method Hurt(amount: Int)
hp -= amount
Print("{name} takes {amount}, {hp} left")
End Method
End Class
Class Boss Extends Enemy
Override Method Hurt(amount: Int)
Super.Hurt(amount / 2) // armor
End Method
End Class
Local enemies: Enemy[] = [Enemy("grunt"), Boss("ogre")]
For e In enemies
e.Hurt(40)
End ForOutput
grunt takes 40, 60 left ogre takes 20, 80 left
Next: nullability.
Report an issue with this page or with FutureBlitz on GitHub.