GML Quicktip: arr(_array, _index)

Here’s a quick short-cut to wrap up some boiler plate code you may write when trying to access elements of arrays. While we can’t chain accessors syntactically, we still can work around the issue in a fairly readable way still. A method I use is adding a function arr(_array, _index) that simply returns the value in _array at _index:

1
2
3
4
///@function arr(_array, _index)
///@desc chaining function for arrays
gml_pragma("forceinline");
return argument0[argument1];

Let’s apply it to game dev…

Let’s say we’re resolving collision and we have an array of bullets that successfully hit their target, the player. We loop through _bullets_hit, where each element is an EBullet Array Object class. one member of EBullet is Damage, representing simply how much damage the target receives.

We want to call a hypothetical do_damage function:

1
2
3
for (var _bullet_index = 0; _bullet_index < _num_hits; ++_bullet_index) {
do_damage(_player, arr(_bullets_hit[_bullet_index], EBullet.Damage));
}

This really just a short cut for writing:

1
2
3
4
for (var _bullet_index = 0; _bullet_index < _num_hits; ++_bullet_index) {
var _bullet = _bullets_hit[_bullet_index];
do_damage(_player, _bullet[EBullet.Damage]);
}

Note about the gml_pragma

Just incase you’re unfamiliar with gml_pragma, I’m using it here with forceinline since the arr function is quite simple, and if we’re getting a ton of utilty out of it, compiling it inline will save us some cycles… we’re basically teling the compiler to paste the code wherever we call arr, rather than call the function.