Quick answer: trying to index a variable which is not an array means your code read v[i] while v held something else: a number, a string, undefined, a struct or a data structure handle. Print typeof(v) on the line before the crash. Then initialise the array in the Create event, stop overwriting it with a scalar, check function results with is_array(), and use the correct accessor for lists, maps, grids and structs.

The variable exists, so GameMaker does not complain that it was never set. It holds a value, just not an array, and the square brackets have nothing to index. That narrows the search: somewhere the variable was given a number, a struct, a list handle or undefined, or it was never turned into an array before the first read. This guide shows the message as the VM and YYC runners print it, a one-line check that tells you what the variable holds, and the fix for each thing it can turn out to be. Code is for GameMaker 2024 and later, where arrays are nested with a[i][j].

The exact error

In a VM build or a run from the IDE, the box names the line and shows the source:

___________________________________________
############################################################################################
ERROR in
action number 1
of Draw Event
for object obj_textbox:
trying to index a variable which is not an array
 at gml_Object_obj_textbox_Draw_0 (line 143) -        var _speaker_x = textbox_x + portrait_x_offset[page];
############################################################################################
gml_Object_obj_textbox_Draw_0 (line 143)

A YYC build has no line information, so you get the event or script name and (line -1):

ERROR in action number 1
of  Step Event0 for object obj_day_manager:
trying to index a variable which is not an array
at gml_Object_obj_day_manager_Step_0
############################################################################################
gml_Object_obj_day_manager_Step_0 (line -1)

Some builds word it slightly differently, and the array functions have their own version that names the function:

trying to index variable that is not an array
array_get :: argument 0 is not an array

All of them say the same thing. The expression before the [ was evaluated, and the result was not an array. The message does not tell you which variable (a line can index several) or what it held instead. Those are the two things to find out.

Reads fail, writes replace

The error comes from reading. Writing behaves differently, and that difference explains a lot of confusing cases:

score_list = 0;

score_list[3] = 50;          // no error: score_list is replaced by a new array
var _first = score_list[0];  // fine now, it is an array

inventory = 0;
var _item = inventory[0];    // error: reading an index from a number
inventory[0] += 1;           // error as well: += reads before it writes

An indexed assignment to a variable that is not an array quietly turns it into one and throws the old value away. So code that only ever writes never crashes, and the first read elsewhere does. With nested arrays the check applies at every level: grid[2][5] fails with this message when grid is an array but grid[2] is a number.

A variable that does not exist at all gives a different error, covered in Variable not set before reading it. An array that is too short gives a third, covered in Array index out of bounds.

Find out what the variable holds

Put one line directly above the failing line, for each variable that is indexed there:

show_debug_message($"portrait_x_offset is {typeof(portrait_x_offset)}: {portrait_x_offset}");

The type is the diagnosis:

typeof() printsWhat happenedGo to
numberDeclared or reset as a number, or a function returned -1 or nooneFix 1 or Fix 2
undefinedA function returned nothing, a struct member or map key is missing, or an argument was not passedFix 2
refIt is a handle: a DS list, map or grid, an instance, an assetFix 3
structParsed JSON or a struct literal where an array was expectedFix 3
stringText. Characters are read with string_char_at(), not bracketsFix 2
arrayThe outer variable is fine. An inner element is the problem, or the line reads a different instance’s variableFix 4 or Fix 5

If the line never prints, the crash is in a different event than you think: check the event name in the box again. In a YYC build, reproduce from the IDE to get a line number. For a crash that happens rarely, run in debug mode with a breakpoint on the line and inspect the variable in the Locals or Instance window. The debugger shows arrays, structs and data structures with an expand arrow, so a plain value is obvious at a glance.

Fix 1: make it an array in Create and keep it one

The classic version is a variable “declared” with a placeholder number:

// Create event, broken
inventory = 0;
portrait_x_offset = 0;

// Create event, fixed
inventory = [];
portrait_x_offset = array_create(8, 0);

The second classic is a reset that forgets the type. Search the whole project for the variable name followed by an equals sign, and look at every assignment, including Room Creation Code and other objects writing through obj_player.inventory:

// Broken: clearing the inventory on death
inventory = 0;

// Fixed: either of these keeps it an array
inventory = [];
array_resize(inventory, 0);

Reusing a name does the same damage. path, list, items and data are popular for arrays and just as popular for a counter or a handle a few events later. Timing is the third variant: one object’s Step or Draw event reads other_object.targets[0] before the code that fills targets has run. Give the variable its array in the Create event, even an empty one, and fill it later.

Fix 2: check what a function gave you

A function that returns an array on success and something else on failure will be indexed on the failure path sooner or later. A bare return; and a branch with no return at all both produce undefined:

// Broken
function find_spawn_point(_tag)
{
    with (obj_spawn)
    {
        if (tag == _tag) return [x, y];
    }
}

var _pos = find_spawn_point("boss");
x = _pos[0];                      // no spawn with that tag: _pos is undefined

// Fixed
var _pos = find_spawn_point("boss");
if (is_array(_pos))
{
    x = _pos[0];
    y = _pos[1];
}

The same applies to missing arguments. A parameter the caller left out is undefined inside the function, so give array parameters a default and guard them:

function total_weight(_items = [])
{
    if (!is_array(_items)) return 0;

    var _sum = 0;
    for (var _i = 0; _i < array_length(_items); _i++)
    {
        _sum += _items[_i].weight;
    }
    return _sum;
}

Look-ups behave the same way. data[$ "enemies"] and map[? "enemies"] return undefined for a key that is not there, and chaining [0] onto that result raises this error. Strings are not arrays of characters in GML either: name[0] fails, string_char_at(name, 1) works (string positions start at 1).

Fix 3: use the right accessor for lists, maps, grids and structs

Square brackets with nothing after the [ are for arrays only. Everything else has its own symbol:

The value isRead it with
Arrayarr[i]
DS listlist[| i] or ds_list_find_value(list, i)
DS mapmap[? "key"]
DS gridgrid[# x, y]
Structdata.name or data[$ "name"]
enemies = ds_list_create();
ds_list_add(enemies, obj_slime);

var _first = enemies[0];      // error: a list handle is not an array
var _first = enemies[| 0];    // correct

Mixing them up is common in projects that are moving from data structures to arrays one system at a time. If a list no longer needs to be a list, convert it fully. If an id you pass around stops working instead, see Data structure with index does not exist.

JSON is the other source. json_parse() returns an array when the document’s top level is a list and a struct when it is an object, and most save files are objects:

// File contents: { "version": 2, "items": ["sword", "potion"] }
var _data = json_parse(_text);

var _first = _data[0];          // error: _data is a struct
var _first = _data.items[0];    // correct

Bad save data produces the same crash on a player’s machine: an older save version where items was a single value, or a file edited by hand. Validate with is_array(_data.items) after loading and replace anything else with an empty array.

Fix 4: check whose variable the line reads

Inside with, a bare variable name belongs to the instance the block is running on, and the instance that wrote the code becomes other:

// obj_player has an array named targets. obj_enemy has a number named targets.
with (obj_enemy)
{
    var _t = targets[0];          // reads obj_enemy.targets: error
    var _t = other.targets[0];    // reads the player's array
}

Local variables shadow instance variables with the same name. A function parameter or a var called inventory hides the instance array for the rest of that function, and if it holds a number the index fails even though the instance variable is perfectly good. Prefixing locals and parameters with an underscore, as GameMaker’s own examples do, removes the whole class of mistake. Collision events and instance_nearest() results deserve the same check: other.slots[0] is only valid if every object that can be other defines slots as an array.

Fix 5: build every row of a nested array

A two-dimensional array is an array whose elements are arrays. Creating only the outer one leaves numbers where the rows should be:

// Broken: five numbers, no rows
grid = array_create(5, 0);
var _cell = grid[2][3];           // error: grid[2] is 0

// Fixed: each row is its own array
grid = array_create(5);
for (var _row = 0; _row < 5; _row++)
{
    grid[_row] = array_create(8, 0);
}
var _cell = grid[2][3];

Do not shorten that to array_create(5, array_create(8, 0)). It passes one inner array and stores the same reference in all five slots, so writing to one row changes every row. Older projects may still contain the comma form grid[2, 3]; it is legacy syntax for the same nested access, and grid[2][3] is the form to write now. Rows of different lengths are legal, which means a row that was never created is legal too, right up to the moment you read it.

A guard for data you do not control

For values that come from saves, mods or the network, read through a helper that cannot throw:

/// @func array_get_safe(_array, _index, _default)
function array_get_safe(_array, _index, _default = undefined)
{
    if (!is_array(_array)) return _default;
    if (_index < 0 || _index >= array_length(_array)) return _default;
    return _array[_index];
}

var _name = array_get_safe(save_data.party, 0, "Nobody");

Keep this at the edges. Inside your own systems a guard on every access hides the real bug, which is that the variable changed type. There it is better to crash in development and fix the assignment.

How to confirm the fix

When it only happens to players

This crash depends on state, so the report from a player is often the only reproduction you get. Bugnet’s GameMaker SDK registers an exception_unhandled_handler in bugnet_init(). It writes the message, the stack, the room name and the game version to a file, and files the report on the next launch, because GameMaker closes the game when the handler returns. From a YYC build the stack contains script and event names without line numbers, which is still enough to know which array to look at. Every occurrence of this message is stacked into one entry, whatever script raised it, so open the individual occurrences and compare their stacks before assuming it is one bug. Setup is in the SDK docs.

Frequently asked questions

What does trying to index a variable which is not an array mean?

Your code used square brackets to read an element from a variable that does not hold an array at that moment. The variable exists, but its value is a number, a string, undefined, a struct or a data structure handle, so there is nothing to index.

Why does the error appear when I read the array but not when I write to it?

An indexed assignment to a variable that is not an array replaces the variable with a new array, so writes never fail. Reads do. That is why code that fills a variable can run for a long time before a read in another event crashes.

How do I check if a variable is an array in GameMaker?

Use is_array(variable), which returns true or false. To see what the variable holds instead, print typeof(variable), which returns names such as number, string, undefined, struct, ref or array.

Can I use square brackets on a ds_list or ds_map?

Not plain ones. A data structure handle is not an array. Use the accessors: list[| index] for lists, map[? key] for maps and grid[# x, y] for grids. Structs use dot access or struct[$ name].

Is the old two-dimensional array syntax still valid?

The comma form a[i, j] from before version 2.3 is legacy syntax. Arrays are now nested, so write a[i][j] and create each row as its own array. Reading a row that was never created as an array raises this same error.

Print typeof() of the variable on the line before the crash. The answer (number, undefined, ref, struct or string) tells you which of the five fixes you need before you read any other code.