Introducing Dragonfly Cloud! Learn More

Question: How can you implement a queue in GameMaker?

Answer

GameMaker Language (GML) does not have a built-in queue data type, but it is possible to implement a queue using arrays or lists. Below is an example of how you could implement a queue with an array.

// Create a new queue var queue = []; // Function to add elements to the end of the queue function queue_enqueue(element) { array_push(queue, element); } // Function to remove and return the element at the start of the queue function queue_dequeue() { if (array_length_1d(queue) > 0) { var element = queue[0]; queue = array_delete(queue, 0, 1); return element; } return undefined; // Return undefined if the queue is empty } // Function to get the element at the start of the queue without removing it function queue_peek() { if (array_length_1d(queue) > 0) { return queue[0]; } return undefined; // Return undefined if the queue is empty }

Alternatively, you can use the ds_list data structure as a queue in GameMaker, as it has functions that closely match queue operations: ds_list_add for enqueue, and ds_list_delete for dequeue. Here's an implementation using ds_list:

// Create a new queue var queue = ds_list_create(); // Function to add elements to the end of the queue function queue_enqueue(element) { ds_list_add(queue, element); } // Function to remove and return the element at the start of the queue function queue_dequeue() { if (!ds_list_empty(queue)) { var element = ds_list_find_value(queue, 0); ds_list_delete(queue, 0); return element; } return undefined; // Return undefined if the queue is empty } // Function to get the element at the start of the queue without removing it function queue_peek() { if (!ds_list_empty(queue)) { return ds_list_find_value(queue, 0); } return undefined; // Return undefined if the queue is empty }

Remember to destroy your ds_list when you're done with it to prevent memory leaks:

ds_list_destroy(queue);

In both examples, queue_enqueue adds an element to the end of the queue, queue_dequeue removes and returns the element from the beginning of the queue, and queue_peek gets the element at the front of the queue without removing it.

Choose arrays if you're looking for a faster performance for smaller queues, and ds_list if you require more complex data operations or expect the queue to become quite large.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.