Function for reversing table order

Hi all  :slight_smile:

I am looking for a function for reversing (flip) table order?

So for example if you have:

local tableA = {1, 5, 3}

I am looking for a function revereseOrder to get following after applying it to tableA:

local tableA = {3, 5, 1}

How to do that?

Many thanks!  :slight_smile:

G

Doesn’t seem to be a built-in way: http://stackoverflow.com/questions/11716248/reverse-string-in-lua

But you can easily implement it with a for loop.

Best regards,

Tomas

Slightly adapted from this:

function Reverse (arr) local i, j = 1, #arr while i \< j do arr[i], arr[j] = arr[j], arr[i] i = i + 1 j = j - 1 end end

Thanks Thomas!

Thanks StarCrunch, your code works like a charm!  :slight_smile:

I do not fully get the code.

  1. First you set i and j to 1?

  2. Then you increase i, but decrease j to negative values?

I understand the flipping part, but not i and j part…

Many thanks.

G

This line

local i, j = 1, #arr

is equivalent to doing

local i = 1 local j = #arr -- number of elements in array, i.e. the last slot

This should clarify point #2, as well.

The loop works from the outside towards the center: flipping the first and last elements, then the second and second-to-last ones, etc. It ends either when i < j (even number of elements) or i == j (odd, but you would only “swap” the middle element with itself).

Thanks StarCrunch!

Great explanation  :slight_smile:

Doesn’t seem to be a built-in way: http://stackoverflow.com/questions/11716248/reverse-string-in-lua

But you can easily implement it with a for loop.

Best regards,

Tomas

Slightly adapted from this:

function Reverse (arr) local i, j = 1, #arr while i \< j do arr[i], arr[j] = arr[j], arr[i] i = i + 1 j = j - 1 end end

Thanks Thomas!

Thanks StarCrunch, your code works like a charm!  :slight_smile:

I do not fully get the code.

  1. First you set i and j to 1?

  2. Then you increase i, but decrease j to negative values?

I understand the flipping part, but not i and j part…

Many thanks.

G

This line

local i, j = 1, #arr

is equivalent to doing

local i = 1 local j = #arr -- number of elements in array, i.e. the last slot

This should clarify point #2, as well.

The loop works from the outside towards the center: flipping the first and last elements, then the second and second-to-last ones, etc. It ends either when i < j (even number of elements) or i == j (odd, but you would only “swap” the middle element with itself).

Thanks StarCrunch!

Great explanation  :slight_smile: