Hey there guys, I'm new with tables and need some help. My first problem is, how do I get a string, number or bool from a table, for example:
I have this table (I'll use throughout this question):
table = {23451,23456,34567,45678,56789,true,false,"Random","random"}
I want to pick out a random item from the table, would it look something like this:
a = table[math.random,1]
The second thing is, how do I remove something from a table? here's an example:
A player leaves the game, I want his UserId to be removed from the table. Would it look something like this:
game.Players.PlayerRemoved:connect(function(player) for i,v in pairs do if player.userId == v then --How do I remove the number from the table?? end end end
I also want to know how I can add items into a table, for example, a player touches a door, I want his user ID to be in the table:
script.Parent.Touched:connect(function(player) for i,v in pairs do if player.userId ~= #table then --If the player's userId is not in the table --Help here?? Inserting the player's userId into the table end end end
Thanks for your help!
Picking out a random entry in a table
table[math.random(1,#table)]
The above code picks a random number between 1 and the total entries in the table.
Removing an entry from a table
game.Players.PlayerRemoved:connect(function(player) for i,v in pairs (table) do if player.userId == v then table.remove(table, i) end end end
Adding items into a table
script.Parent.Touched:connect(function(player) local check = false for i,v in pairs (table) do if player.userId == v then --If the player's userId is in the table check = true -- we set check to true end end if check == false then -- if check is false, meaning that the userId was not found in the table table.insert(table, player.userId) -- insert the userId into the table end end