Hey, so I have a small problem. Basically I have a table/array that keeps track of all players currently in the game. Any time that a player joins the game, they get added to it, and when they leave, they get removed. The problem i’m running into is that for example if the first object got removed in the array, then the second and third stay at second and third index, when I want them to be shifting down to first and second. How can I make the objects above a removed object shift down? Thanks.
Do you mind if I see the code?
Great idea, let me try that. Thanks
Hang on, don’t I need to clear the table first?
Either use table.remove(tbl, index)
or use a quick swap.
local a = {"A", "B", "C", "D", "E"}
table.remove(a, 2) -- Remove "B"
print(a) --> {"A", "C", "D", "E"} -- C, D, and E moved down one
Or a swap-remove, which works much faster, O(1) instead of O(n), but does not preserve array order. It works by taking the index you want to remove & replacing that value with whatever is at the end of the array. And then it sets the end of the array to nil
. So you’re swapping the last value in for the value you want to remove.
local a = {"A", "B", "C", "D", "E"}
local n = #a
a[2] = a[n]
a[n] = nil
print(a) --> {"A", "E", "C", "D"} -- B replaced with last index, and last index trimmed off
For your case (a list of players), table.remove
works perfectly fine.
I am sorry I made a mistake I forgot that you needed to clear the table…
No worries man, i’m testing now. Hope it works!
My idea is very inefficient so I suggest using SleitNick’s one.
The first solution he gave is very clear to me and will work the best rather than my idea of overwriting the table after clearing it.
I am not very good at scripting and I don’t really get the second idea of his but he is a really pro scripter and his code will be very efficient!
It works thank you so much man.
yeah his seems better in the long term but i think yours will work for now as this is just a quick thing im making for a game jam