Structs
This section describes how to use named structures to store multiple types in one variable.
Foundations
Section titled “Foundations”A Struct is a custom structure container of other types. You can use it so that one variable can store a bunch of other member variables inside it. Member variables can be any type, including other custom structs.
A struct signature is: struct struct_name { … }. Inside the ”…” are normal variable declarations. Then to instantiate a variable of the custom type you just use: struct_name variable_name;
Note, structures must be defined at the namespace scope, i.e. outside of other braces { } that are not used for namespacing.
The following example creates a custom struct type with different member types.
// blueprintstruct weapon { i32 price; f32 power; string name;}
// constructionweapon sword;Struct members are accessed by placing a period between the structure variable name and the member variable name: variable_name.member_name
All structure members are zero initialized when constructed.
println(sword.price); // 0sword.price = 200;println(sword.price); // 200Member values can be individually set like the example above or all at once using an initializer list [ ] expression.
weapon sword = [ 200, 5.5, "Great Sword" ];println(sword.price); // 200println(sword.power); // 5.500000println(sword.name); // Great SwordStruct variables can be cloned (deep copy) using assignment.
weapon sword2 = sword;println(sword2.price); // 200println(sword2.power); // 5.500000println(sword2.name); // Great SwordComposition and Membership
Section titled “Composition and Membership”You can build structures from other structures using composition or membership. Membership uses a member variable with a struct type. Composition uses a struct type without giving it a member name.
Both strategies are useful for building structures. Membership is more hierarchical and can make large structures more organized. Whereas composition is more flat, requires less typing, and can be slightly faster to execute.
// other structure we want to usestruct position { f32 x, y;}
// adding x,y variables using membershipstruct player { position pos; // has variable name}player p;p.pos.x = 1.0; // x and y added using a position member variablep.pos.y = 2.0;println("{p.pos.x}, {p.pos.y}"); // 1.00000, 2.00000
p.pos = [ 3.0, 4.0 ]; // update using initializer listprintln("{p.pos.x}, {p.pos.y}"); // 3.00000, 4.00000
// adding x,y variables using compositionstruct beast { position; // no variable name}beast b;b.x = 1.0; // x and y added directly to the beast structureb.y = 2.0;println("{b.x}, {b.y}"); // 1.00000, 2.00000
b = [ 3.0, 4.0 ]; // update using initializer listprintln("{b.x}, {b.y}"); // 3.00000, 4.00000