Skip to content

Instantly share code, notes, and snippets.

@Buy-One
Last active April 12, 2022 08:36
Show Gist options
  • Save Buy-One/0698f48eea32599e8e29a5dc4bf1a846 to your computer and use it in GitHub Desktop.
Save Buy-One/0698f48eea32599e8e29a5dc4bf1a846 to your computer and use it in GitHub Desktop.
Reverse indexed table
function reverse_indexed_table1(t) -- around the last value
if not t then return end
for i = 1, #t-1 do -- loop as many times as the table length less 1, since the last value won't need moving
local v = t[#t-i] -- store value
table.remove(t, #t-i) -- remove it
t[#t+1] = v -- insert it as the last value
end
end
function reverse_indexed_table2(t)
if not t then return end
local fin = #t -- separate var because using #t in the loop won't work due to the table length increase
for i = fin,1,-1 do
t[#t+1] = t[i] -- append all values starting from the last to the end of current table
end
for i = 1, fin do
table.remove(t,1) -- remove 1st field as many times as the length of the orig table, with each removal next field becomes 1st
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment