Popping the first element off an array

Jason S picture Jason S · Feb 6, 2011 · Viewed 23.9k times · Source

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.)

Answer

Miles picture Miles · Feb 6, 2011

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.