Method Calls
Ghost is deeply object oriented, so most code consists of invoking methods on objects, usually something like this:
dog.speak("Throw the ball!")
You have a receiver expression (here dog) followed by a ., then a name (speak) and an argument list in parentheses (("Throw the ball!")). Multiple arguments are separated by commas:
dog.command("fetch", "ball")
The argument list can also be empty:
dog.sit()
Ghost executes a method call like so:
- Evaluate the receiver and arguments from left to right.
- Look up the method on the receiver's object.
- Invoke it, passing in the argument values.
Methods On Built-in Values
Methods aren't only for class instances. Every built-in type carries its own set, and they're called the same way:
"ghost".toUpperCase(); // >> GHOST
[3, 1, 2].length(); // >> 3
3.14159.round(2) // >> 3.14
See Strings, Lists, and Numbers for what each type offers.
Properties
The same . also reads a value rather than calling something — a field on an instance, a key on a map, or a property on a library module:
dog.name // a field
config.debug // a map key
math.pi // a module property
The difference is the parentheses: math.pi is a property, math.abs(-1) is a method call.
Chaining
A method call is an expression, so its result can be the receiver of the next call:
" Ghost ".trim().toUpperCase() // >> GHOST
Missing Methods
Calling a method a value doesn't have is a property error, reported the moment the call is reached — and Ghost suggests the nearest name the value actually has:
property error: class `Foo` has no method `spek`
--> example.gs:7:5
|
7 | foo.spek()
| ^^^^
|
= help: did you mean `speak`?