(0.0.0) Intro To Structs - JujuAdams/Bento GitHub Wiki

Bento uses structs as the main data container (see Elements for specific details). Structs are a new concept and this page serves as a crash course for their use.

 

GameMaker Studio 2.3.0 introduces a new way of organising data called a "struct". This isn't strictly a struct in the C sense, it's perhaps closer to a JavaScript object. Structs are further similar to GameMaker's native map data structures.

Structs in the context of GML can be thought of as objects, albeit with all their events totally stripped out. Structs exist to contain variables: these variables can be simple values, they can be structs or arrays themselves, or they can be functions. When a function is tied to a struct we call it a "method".

Structs do not need to be explicitly memory managed unlike ds_map or ds_list. Once a reference to a struct is lost, the memory allocated for the struct is freed in the background by GameMaker automatically.

 


 

Here's an example of a struct definition:

foo = { //Curly brackets start a struct definition
    a    : 42,
    text : "Hello World!,
}

In this case, the struct foo has two member variables: a and text. Note how we use : colons to associate a value with a variable. We can access these variables in two ways:

show_debug_message(foo.a); //Outputs "42"
with(foo) show_debug_message(text); //Outputs "Hello World!"

Of particular importance is the similarity between a struct and a GameMaker instance. with when combined with structs is very powerful.

We can also set new member variables for a struct by simply setting a value as we would with any instance:

bar = {}; //An empty struct
bar.a = 17;
with(bar) text = "Game over, man, game over!";

Structs and array can be nested inside each other as much as is needed.

root = {
    array : [
        { name : "Alice", age : 9001 },
        { name : "Bob"  , age :   17 },
    ]
}

We can then retrieve values in a single line of code:

show_debug_message(root.array[1].name); //Outputs "Bob"

 


 

Functions can be bound to structs to help organise and simplify how data is manipulated in your game. Previous versions of GameMaker have required the use of many (...many) globally-scoped scripts making for messy, hard to understand code. The use of methods allows us to attach specific functions to specific structs (methods can also be bound to normal instances but this isn't a feature that Bento uses).

foo = {
    hp : 10,
    
    increase_hp : function() {
        hp += 10;
    }
};

foo.increase_hp();
show_debug_message(foo.hp); //Outputs 20