Skip to content

Instantly share code, notes, and snippets.

@balaam
Created July 16, 2012 10:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balaam/3122129 to your computer and use it in GitHub Desktop.
Save balaam/3122129 to your computer and use it in GitHub Desktop.
Reverse an ipairs table in Lua (not clever O(n) could be O(n/2) with swapping)
--
-- Reverses an ipairs table
--
--local r = ReverseTable({'a', 'b', 'c'})
--for k, v in ipairs(r) do
-- print(k, v)
--end
--
--
function ReverseTable(t)
local reversedTable = {}
local itemCount = #t
for k, v in ipairs(t) do
reversedTable[itemCount + 1 - k] = v
end
return reversedTable
end
Copy link

ghost commented Oct 23, 2014

tohle funguje

@BTCTaras
Copy link

BTCTaras commented Jan 2, 2016

^ agreed

@max1220
Copy link

max1220 commented Jan 26, 2016

If you don't mind modifying the original talbe, this should do the trick for O(n/2):

function reverse(tbl)
  for i=1, math.floor(#tbl / 2) do
    local tmp = tbl[i]
    tbl[i] = tbl[#tbl - i + 1]
    tbl[#tbl - i + 1] = tmp
  end
end

It's even a line shorter 😄

@moritzbuhl
Copy link

function reverse(tbl)
  for i=1, math.floor(#tbl / 2) do
    tbl[i], tbl[#tbl - i + 1] = tbl[#tbl - i + 1], tbl[i]
  end
end

Isn't this one working too?

@AndreLouisIssa
Copy link

O(n/2) is O(n)
I think you mean n/2, without the O

@RayTwitty
Copy link

RayTwitty commented Jan 9, 2021

function table.reverse(t)
	local len = #t
	for i = len - 1, 1, -1 do
		t[len] = table.remove(t, i)
	end
end

or modified ipairs-function

function rpairs(t)
	return function(t, i)
		i = i - 1
		if i ~= 0 then
			return i, t[i]
		end
	end, t, #t + 1
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment