Storing array values in different variables using for loop

Hi :)

Let's say I have an array arr_power_up_pool = ["magnet","heart","triple_shot"]

The length of arr_power_up_pool changes over the course of the game, meaning that it is empty at the beginning and could have up to 20 or more entries (no fix maximum).
I want to be able to store the values one after the other inside the "pos_01" - "pos_03" variables (in this case01- 03, but this would of course go up to whatever the amount inside the array is).
I know that I can store specific positions of an array in a new variable using array_get. But how do I get something like

pos_01 = "magnet"
pos_02 = "heart"
pos_03 = "triple_shot"

I came up with the following:
power_up_pool_length = array_length(arr_power_up_pool);

if(!(array_length(arr_power_up_pool) == 0))
    for(i = 0; i < power_up_pool_length; i += 1) {
        pos_ = array_get(arr_power_up_pool,i);
The problem is, it stores the whole array in pos_, instead of the individual values. And I have no idea how to tell Game Maker to automatically name "pos_" correctly (pos_ + 01, 02, 03 and so on), depending on which position inside arr_power_up_pool the value is.


As a side, if array_length returns zero, that for loop won't run, so you don't need the if check.

Instead of array_get, just use the array name and the index, but you would be best storing the string into a ds_map, if that's really what you want. Personally it seems a bad idea though, and you would be better using an array or ds_list with an index, rather than a string named pos_##. It all depends on what you plan to do with all of these "pos_##" strings.


You could just copy the array over and using pos with the index:
pos = arr_power_up_pool;

// then you can use
// and so on
but then you could have just used it directly (but a short name is helpful at times)

But just to answer the question:
for(var i=0;i<array_length(arr_power_up_pool);i++){
    variable_instance_set(id, "pos_"+string(i), arr_power_up_pool[i]);
Might have to add a "0" if i is less then 10
or do some string_format stuff
Last edited:
Thanks to both of you. I think you're right, could have just used the name and the index... I haven't used ds_maps so far (fairly new to game maker). So far I have only used arrays to store multiple values. Haven't figured out when to use ds_maps instead.

Will have a look once I'm home again. Thanks.


You should consider ds maps only if you want to use strings as indices instead of numbers (as GML arrays cannot use string indices, aka associative arrays in some other languages) or when you need functionalities only ds maps have - which I can't offhand recall. And in former case, it should be considered whether a struct instead of a ds map is a better idea.