reverse

function reverse( arr ) --> arr

Description

Reverses the order in the array table arr.

Parameters

arr

The array table that should be modified.

Return Values

arr

The modified array table.

Code

--ZFUNC-reverse-v1
local function reverse( arr )
   local i = 1
   local j = #arr
   while i < j do
      arr[ i ], arr[ j ] = arr[ j ], arr[ i ]
      i = i+1
      j = j-1
   end
   return arr
end

return reverse

Examples

local t = require( "tapered" )
local reverse = require( "reverse" )

arr = reverse{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }
t.same( { 9, 8, 7, 6, 5, 4, 3, 2, 1 }, arr )

arr = reverse{}
t.same( {}, arr )

arr = reverse{ 1 }
t.same( { 1 }, arr )

arr = reverse{ 1, 2 }
t.same( { 2, 1 }, arr )

arr = reverse{ 1, 2, 3 }
t.same( { 3, 2, 1 }, arr )

arr = reverse{ 1, 2, 3, 4 }
t.same( { 4, 3, 2, 1 }, arr )

t.done()

See also