There’s nothing specific that I’m currently doing with this, but just out of curiosity, I’m wondering if they’re is a way to reverse the ordering of a tables items.
We have table.sort, but after using that function from the table library, I was wondering on if there was a way to reverse it like table.reverse or something like that.
Not that I know of, but here is something that might help you out.
function ReverseTable(myTable)
if myTable and #myTable > 1 then
local temp = nil
for n = 1,math.floor(#myTable/2) do
temp = myTable[n]
myTable[n] = myTable[#myTable-(n-1)]
myTable[#myTable-(n-1)] = temp
end
end
end
Yes, you can reverse the order of a Lua table using the table library’s table.sort function in combination with a custom comparison function.
local nums = {5, 2, 8, 1, 9}
table.sort(nums)
local function reverseSort(a, b)
return a > b
end
table.sort(nums, reverseSort)
for i, num in ipairs(nums) do
print(num)
end