I am attempting to create a matchmaking system for 1v1s that utilizes a server-side queue. You step on a part and get added to a queue list that should update every time a fight is finished.
Here is the code so far:
local Queue = {}
local Queued = false
workspace.Pad.Touched:Connect(function(Hit)
local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
if Hit.Parent:FindFirstChild("Humanoid") then
if Player then
if not Queued then
Queued = true
table.insert(Player.Name, Queue)
end
end
end
end)
repeat wait() until #Queue > 2
local function GetFighters()
local Fighter1, Fighter2
-- Find first two players in queue, assign them as Fighter1/2
table.remove({Fighter1, Fighter2}, Queue)
-- Remove them from table and initiate 1v1
return Fighter1, Fighter2
end
*The problem:
The problem is I am not too familiar with Lua and tables. How can I find the first two players in the queue and assign them as the defined variables (Fighter1 and Fighter2) and remove them from the table and keep the order intact??
You are using table.insert() wrongly. You want to give it the table first then the Value, Example
local PlayerQueue = {}
table.insert(PlayerQueue, Player)
This will add the Player to the last index of the table so to get the first person in the queue you can do
PlayerQueue[1] - First person
PlayerQueue[2] - Second Person
So when you want to remove the first and second to first player you can do
table.remove(PlayerQueue, 1)
table.remove(PlayerQueue, 2)
Since this is a queue you would always be adding elements to the end of the array and removing elements from the front of the array. When you call table.remove(queue, 1), it returns the first in the queue then shifts all elements down to fill the empty space, so you don’t have to increment the index you draw from the array.
I personally like to stay away from premade table methods like table.remove due to the fact that I feel like I have more control when dealing with arrays and tables, so my following code will not be using any of the methods.
What I would do for this would be to use a i, v in pairs() loop. I’m sure there are other ways to go about doing this, though.
function FindTwoPlayersAndRemoveFromQueue(Array)
local ArrayLength = 0
for i, v in pairs(Array) do
ArrayLength += 1
end
if ArrayLength < 2 then return end -- if not enough players, then don't proceed
local Player1, Player2
for i, player in pairs(Array) do
if not Player1 then
Player1 = player
Array[i] = nil
elseif not Player2 then
Player2 = player
Array[i] = nil
break
end
end
print(Player1, Player2)
return Array, Player1, Player2
end
Example on how to retrieve the players using the function
local Fighter1, Fighter2
Queue, Fighter1, Fighter2 = FindTwoPlayersAndRemoveFromQueue(Queue)
For adding a player to the queue, I would really simply just do this:
You can’t simply because that only works with arrays which are using numeral indexes e.g. Array[1], Array[2] etc.
However, in my example I’m using the Player objects.