I've been experimenting with using static variables within functions and referencing them outside of the function, and am running into some issues.
I'm using a completely blank project with just one object in the room. In the object's Create event I define a function with a static variable in it
function test() { static num = 1; }
We also want to execute the function at least once so that the static variable gets initialized, so we write test(); in the create event as well
Then, in the objects Key Press - Space event I show a message that prints that static variable
show_message($"test: {test.num}");
Now, we'd expect that pressing the space bar would now show a message containing the static variable as a string like so:
test: 1
But instead, we get this error message
Variable <unknown_object>.num(100003, -2147483648) not set before reading it.
at gml_Object_oGame_KeyPress_32 (line 1) - show_message(test.num);
This seems incorrect, and goes against what the manual says about static variables.
But, if I move the function declaration and the initial execution of said function into the space pressed event, then it fixes the issue, and prints the static variable.
And there is a way to break it again. By changing the function declaration from
function test()
to
test = function()
The error comes back.
Finally, if I move the function declaration to a script asset, then it will print the static variable, but only if I use the function test() syntax
I don't have the time to revert my gamemaker version back to see if that fixes the issue, but I don't see how this isn't a bug with gamemaker.
Is there something obvious I'm missing here?