Setting the index to nil
One of the most common ways of removing a value from a table is simply setting it's value to nil. This will completely erase the value's existence and recognition with the script, thus completely removing it. This is done via the following example:
local Array = {'hello','world'}
Array[2] = nil
print(Array[2])
Clearing a table?
An extension of this example could be making a function that wipes all data in an array. Here's an example:
local tab = {"hello","i","am","steve"}
local function ClearTable(t)
for i = 1,#t do
t[i] = nil
end
end
print(unpack(tab))
ClearTable(tab)
print(unpack(tab))
table.remove
There's one handy function of the table library called remove. This function consists of 2 arguments:
- The table you're modifying
- The numeric key you're removing
Now, because we can only pass a number as the second argument of table.remove, this implies our table must be an array. If you don't know what an array is, I explain a bit more about it in this question: https://scriptinghelpers.org/questions/25964/what-are-tables#29555
Now, this function actually has an extra mechanic to it than just removing a value from a table. Once removing a value from a table with this function, it will actually replace that index value with the key that's after it. Here's an example:
local test = {"hello","i","am","steve"}
table.remove(test,2)
print(test[2])
So this function removes the value, with the addition of moving all other elements down the list, replacing the removed value. This is different from just manually setting the index to nil, where manually setting the index to nil leaves a blank space open as nil, where a value used to be. Here's an example demonstrating that:
local text = {"hello","world","i","like","pie"}
table.remove(text,2)
print(text[2])
text[2] = nil
print(text[2])
Your question
Applying all this information, here's a scenario which fits your question:
local players = {"player1","player2","player3","player4","player5"}
local function RemovePlayer(tab,playerName)
for i = 1,#players do
local v = players[i]
if v == playerName then
table.remove(tab,i)
end
end
end
RemovePlayer(players,"player2")
print(players[2])
Hope this helped, let me know if you have any questions.
1 comment
thank you so much! it did :D