Enqueue values at the back and dequeue them from the front in first-in, first-out order.

Algorithm

The replay uses the same three values in every language, so this Lua DSA implementation can be compared directly with the rest of the DSA track.

front The front is the oldest value still waiting in the queue.
FIFO A queue removes values in first-in, first-out order.

Visual walkthrough

The queue keeps the oldest value at the front and adds new values at the back.

Step 1 - Enqueue 10, 20, 30

New values join at the back. The oldest value, 10, stays at the front.

Queue after three enqueues: front 10, then 20, then back 30.nextnext10front2030back

Step 2 - Dequeue removes 10

Removing from the front returns 10 and makes 20 the new front.

After one dequeue: removed is 10; front moves to 20.next10removed20front30back

Basic Implementation

basic.lua
local function render(values)
    local parts = {}
    for i, value in ipairs(values) do parts[i] = tostring(value) end
    return table.concat(parts, " -> ")
end

local queue = {}
for _, value in ipairs({10, 20, 30}) do table.insert(queue, value) end
local removed = {}
while #queue > 0 do table.insert(removed, table.remove(queue, 1)) end
print(render(removed))

Complexity

  • Time: O(n) per front dequeue here because table.remove(queue, 1) shifts the dense table; O(1) per operation with a real queue
  • Space: O(n)

Implementation notes

  • local queue = {} starts as an empty Lua table, and the trace records [].
  • Enqueue uses table.insert(queue, value) while iterating ipairs({10, 20, 30}), so values append at the back in that order.
  • After enqueue, the queue state is [10, 20, 30].
  • Lua's front position here is index 1; dequeue uses table.remove(queue, 1).
  • table.remove(queue, 1) returns the removed front value and shifts the remaining dense-table values left.
  • Removed values are collected with table.insert(removed, ...).
  • The first dequeue returns 10, leaving queue = [20, 30] and removed = [10].
  • The remaining dequeues return 20 and 30, leaving queue = [] and removed = [10, 20, 30].
  • render(removed) uses ipairs and table.concat(parts, " -> "), so print(render(removed)) outputs 10 -> 20 -> 30.