Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Popping the first element off an array

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

like image 395
Jason S Avatar asked Feb 05 '11 23:02

Jason S


1 Answers

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.

like image 198
Miles Avatar answered Sep 20 '22 13:09

Miles