[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]

## Function for reversing table order Started by gogigoranic8 Feb 23 2016 06:50 AM

1 votes
5 replies to this topic
table order reverse opposite flip

Best Answer StarCrunch , 23 February 2016 - 10:31 AM

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
```

[TOPIC CONTROLS]
This topic has been archived. This means that you cannot reply to this topic.
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

### gogigoranic8

[GLOBAL: userInfoPane.html]
gogigoranic8
• Contributor

• 149 posts
• Corona SDK

Hi all

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!

G

[TOPIC: post.html]
#2

### tomaswesterlund

[GLOBAL: userInfoPane.html]
tomaswesterlund
• Contributor

• 306 posts
• Corona SDK

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

[TOPIC: post.html]
#3

### StarCrunch

[GLOBAL: userInfoPane.html]
StarCrunch
• Contributor

• 829 posts
• Corona SDK

Best Answer

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
```

[TOPIC: post.html]
#4

### gogigoranic8

[GLOBAL: userInfoPane.html]
gogigoranic8
• Contributor

• 149 posts
• Corona SDK

Thanks Thomas!

Thanks StarCrunch, your code works like a charm!

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

[TOPIC: post.html]
#5

### StarCrunch

[GLOBAL: userInfoPane.html]
StarCrunch
• Contributor

• 829 posts
• Corona SDK

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

[TOPIC: post.html]
#6

### gogigoranic8

[GLOBAL: userInfoPane.html]
gogigoranic8
• Contributor

• 149 posts
• Corona SDK

Thanks StarCrunch!

Great explanation

[topic_controls]

[/topic_controls]