Types
A map is fine until you want every monster to have the same fields. A TYPE
says what the fields are and what each starts as.
TYPE Monster
name AS STRING = "slime"
hp AS INTEGER = 20
pos AS COORDINATE
loot AS ARRAY
END TYPE
blob = Monster() // everything as it starts
boss = Monster({name: "dragon", hp: 500}) // some of it filled in
boss.pos.x = 12
PUSH boss.loot, "gold"
PRINT blob
PRINT boss.name, boss.hp, boss.pos, boss.loot
Monster {name: slime, hp: 20, pos: (0, 0), loot: []}
dragon 500 (12, 0) [gold]
You make one by calling the type like a function, with a map of whatever you
want to set. A field with no value of its own starts as its kind does: 0, an
empty string, (0, 0), an empty list.
Functions that belong to a type
Write the type’s name, ::, and the function’s. Inside, SELF is the one it
was called on.
TYPE Monster
name AS STRING = "slime"
hp AS INTEGER = 20
END TYPE
FUNCTION Monster::Hit(damage)
SELF.hp = SELF.hp - damage
RETURN SELF.hp > 0
END FUNCTION
FUNCTION Monster::Describe()
RETURN SELF.name + " (" + SELF.hp + " hp)"
END FUNCTION
blob = Monster()
PRINT blob.Describe()
still_up = blob.Hit(15)
PRINT blob.Describe(), still_up
slime (20 hp)
slime (5 hp) 1
Types inside types
A field can be another type. Give it a map and I’ll turn the map into that type for you, filling in the rest.
TYPE Weapon
name AS STRING = "fists"
power AS INTEGER = 1
END TYPE
TYPE Hero
name AS STRING
weapon AS Weapon
END TYPE
ada = Hero({name: "Ada", weapon: {name: "sword", power: 7}})
bob = Hero({name: "Bob"})
PRINT ada.name, ada.weapon.name, ada.weapon.power
PRINT bob.name, bob.weapon.name, bob.weapon.power
Ada sword 7
Bob fists 1
From BASIC:
TYPE ... END TYPEas you know it, plus defaults and functions of its own.
From Python: A
TYPEis a small class: fields with defaults, and methods.SELFisself, and you don’t list it as a parameter. There’s no inheritance.
From JavaScript:
SELFisthis, without the surprises. There are no prototypes and nonew.
From Lua: No metatables to set up.
thing.Hit(5)passesSELFfor you, so there’s no:to remember.
Crash-tan’s Tip: The
AS STRINGpart tells readers — and the documentation — what a field is for. I don’t police it while the program runs.