-
Notifications
You must be signed in to change notification settings - Fork 4
Structs
Structs are a collection of variables and functions. These can be copied in so called Object
s.
To define a new struct you use the struct
command.
struct name {
...
}
Inside of a struct, only a few commands are allowed:
-
new
to define members -
func
to define methods -
struct
to define a struct inside a struct
Such a struct can look like this:
struct Human {
new age 420
new name "victor"
func eat(what :: String) {
print "nom nom nom, " what " is now gone!"
}
func say_hi() {
print "Hi, I'm " name " and " age " years old"
}
}
An object is being created as following:
<struct> <name>()
So, as for the Human
struct above:
Human vic()
All members are private, the only thing we can do is call methods on vic
:
vic.eat("apple") # nom nom nom, apple is now gone!
vic.say_hi() # Hi, I'm victor and 420 years old
Methods are also able to change member variables.
The constructor for a struct is called when the instance get's created and must have the same name as its struct.
A deconstructor can be added using the on_death
command followed by a method name and a set of given arguments you want to pass to that function.
Deconstructors are called once a instance leaves scope.
A struct can has as many deconstructors as you want, but only one constructor.
struct A {
new a
new b
func A(a_,b_) {
a = a_
b = b_
}
func print_memb() {
print a " : " b
}
func calc(l,r) {
print (l + r)
}
on_death calc(1,3)
on_death print_memb()
}
A a(1,2)
This will create a new instance of A
and call it's constructor setting a
and b
.
After that the instance leaves scope, so a
calles calc
and print_memb
.
So the expected output is:
4
1 : 2
Some boilerplate code can be easily generated using the gen_* commands.
Adds a get_<name>()
method with a given member to the current struct.
struct A {
new a
func get_a() => a
# can be replaced with:
gen_get a
}
Adds a set_<name>(<name>_)
method with a given member to the current struct.
struct A {
new a
func set_a(a_) => a = a_
# can be replaced with:
gen_set a
}
Adds both a get_<name>()
as well as a set_<name>(<name>_)
to the struct.
Struct A
matches struct B
if A
has all the members of B
as well as the functions.
A
is allowed to have other members and functions/structs too, but it must useable as if it was a B
.
Example:
struct A {
new a
new b
new c
func foo() => a + b + c
func bar() => c
}
struct B {
new a
new b
func foo() => a + b
}
A a()
B b()
# a can be used as a B
print (a == b) # 1 (true)
# b can NOT be used as a A
print (b == a) # 0 (false)
A struct can inherit members functions and structs from other already existing structs.
This looks like this:
struct A { ... }
struct B { ... }
struct C (A,B) { ... }
struct D (A) { ... }
C
does now always match an A
and B
. A D
now always matches at least an A
.
If B
would have defined something that already exists with the same name in A
, C
would use the one A
provided because it was first in the list.