Logo

Programming-Idioms

History of Idiom 19 > diff from v30 to v31

Edit summary for version 31 by ttmrichter:
[Lua] Added an in-situ approach.

Version 30

2017-05-27, 19:05:34

Version 31

2017-06-06, 08:05:10

Idiom #19 Reverse a list

Reverse the order of the elements of list x .
This may reverse "in-place" and destroy the original ordering.

Idiom #19 Reverse a list

Reverse the order of the elements of list x .
This may reverse "in-place" and destroy the original ordering.

Code
rev = {}
for i=#x, 1, -1 do
	rev[#rev+1] = x[i]
end
Code
rev = {}
for i=#x, 1, -1 do
	rev[#rev+1] = x[i]
end

-- in-situ reversal
function reverse(t)
  local n = #t
  local i = 1
  while i < n do
    t[i],t[n] = t[n],t[i]
    i = i + 1
    n = n - 1
  end
end