I have variables that are used to store arrays of numbers.
I want to be able to push new values onto those arrays (and splice them out when no longer needed).
Currently I'm using the method below to push the value of variable 16 onto the array variable 15:
var tempArray = $gameVariables.value(15) || [];
tempArray.push($gameVariables.value(16));
$gameVariables.setValue(15, tempArray);
I'm wondering if there's a more direct way to do this (without a temporary variable).
Thanks!
Huh, thanks! I didn't realize you could push directly onto .value(). I guess I assumed .value() would pass by value, not reference. This is an area I can learn more about!
Since .value() in this case returns the array that gives you access to all the array functions. 🙂
This is the code I wound up with, in case of interest. This allows the array to be initialized if it hasn't been (since a non-array variable here would break the game) but also allows the array to already have existing values. And neatly avoids a temporary variable.
if ( !$gameVariables.value(15) ) { $gameVariables.setValue(15, []) };
$gameVariables.value(15).push( $gameVariables.value(16) );
You can always define your own variables too, although that doesn't solve the actual question 😀
For instance I use gameVariables only for eventing, when I need a variable for something, I define my own variables.
You can use a plugin to define them, but that is impractical, so use a script box quite often.
Allow me to demonstrate the difference between local and global variables though.
Local variables are defined by var. Their scope of use is only inside a program or, if they are defined inside a function, inside that function. The reason why var defined in script boxes are local is because the script box is in fact a function consisting of an eval command (which allows it to execute whatever code you type in).
However, if you define a variable without using var, then you defined a global variable. This variable can be stored inside a browser travelling from site to site, which can, if site designers aren't careful, cause bugs (although this happens pretty rarely, both due to browser evolution and the chance of you hitting upon a variable that the other site uses in a code but forgets to define), but in computer games they are completely harmless.
For example
x = 3 - I have defined a global variable x.
Don't need a global variable anymore? No problem, simply
x = "undefined"