I would also like to point out that Rig
is equal to false
. Let me know if you are trying to retrieve the index name (ex. Rig2)
I do need the name of the index, because for example if Rig2 is false, and it’s chosen I’ll need it’s name to reference it further in the script
that’s good for his use case. it’s the same as what my module is doing, just generalized with functions
I figured. Here is a better way to achieve this, my apologies.
local UsedCharacters = {
["Rig1"] = false,
["Rig2"] = true,
["Rig3"] = false,
["Rig4"] = false
}
local function getRandomRig()
local NewTable = {}
for i,v in pairs(UsedCharacters) do
if v==false then NewTable[#NewTable+1]=i end
end
return NewTable[math.random(1,#NewTable)
end
local Rig = getRandomRig()
print(Rig) -- could be either Rig1, Rig3, or Rig4
I whipped something up! I also put some comments explaining everything. Hope this helps! I also recommend you store the RigContainer in a Module script in ServerStorage, and maybe create a Module that helps you interact with the RigContainer throughout your scripts so it will be much easier for you.
--> Services
local Players = game:GetService("Players")
--> Variables
local RigContainer = {
["Rig1"] = false,
["Rig2"] = false,
["Rig3"] = false,
["Rig4"] = false,
["Rig5"] = false,
["Rig6"] = false,
}
--> Functions
--[[
This helper function simply gets all the Indexs that have the value of false and returns it in a new table, not the original
]]
local function getRigs()
local Rigs = { }
for Index, Value in pairs(RigContainer)do
if(not Value)then
table.insert(Rigs, Index)
end
end
return Rigs
end
--[[
Get thes available rigs using the helper function, then gets a random rig that is available.
Then gets that Index/Rig from the original table and sets its value as the Player
]]
Players.PlayerAdded:Connect(function(Player)
local Rigs = getRigs()
if(#Rigs > 0)then
local randomRig = Rigs[math.random(1, #Rigs)]
RigContainer[randomRig] = Player
print(Player.Name.." now owns rig "..randomRig)
end
end)
--[[
Loops through everything in the original table and checks if any of the values equal to the player, if it does it will be set to false.
]]
Players.PlayerRemoving:Connect(function(Player)
for Key, Value in pairs(RigContainer)do
if(Value == Player)then
RigContainer[Key] = false
end
end
end)
local UsedCharacter = {
["Rig1"] = false,
["Rig2"] = false,
["Rig3"] = false,
["Rig4"] = false
}
local function GetRandomRig()
local RandomNumber
repeat
RandomNumber = math.random(1, 4)
until not UsedCharacter["Rig"..RandomNumber]
UsedCharacter["Rig"..RandomNumber] = true
print("Rig"..RandomNumber)
end
for i = 1, 4 do
GetRandomRig()
end
Hey yall I appreciate all of your guys help, all of your guys input has helped, and I believe I got something that is working the way I’d like it to.