Search code examples
arrayslualua-table

Popping the first element off an array in Lua


I have an array x in Lua. I would like to set head = x[1] and rest = the rest of the array, so that rest[1] = x[2], rest[2] = x[3], etc.

How can I do this?

(note: I don't care if the original array gets mutated. In Javascript I would do head = x.shift() and x would contain the remaining elements.)


Solution

  • head = table.remove(x, 1)

    "Pop" is a bit of a misnomer, as it implies a cheap operation, and removing the first element of an table requires relocating the rest of the contents--hence the name "shift" in JavaScript and some other languages.