Like let’s say I have a table that’s
{“I”, “like”, “tables”}
How would I change that to
{“tables”, “like”, “I”}
?
I’ve been messing around with the table.sort() function and maybe it’s because I’m blind or dumb but I can’t get the result I want. Help?
14 Likes
for i = 1, math.floor(#t/2) do
local j = #t - i + 1
t[i], t[j] = t[j], t[i]
end
67 Likes
Thank you so much!
Can you explain how that works? Because there’s no way I would have figured that out.
2 Likes
It loops up to half of the table and for each position in the first half, swaps it with the corresponding position in the second half.
If t is a table with five elements, it would loop over i = 1, 2, meaning it will swap t[1] with t[5] and t[2] with t[4] and that’s all you have to do. (t[3] doesn’t change since it’s the middle value here) Also works with evenly sized arrays.
19 Likes