If plot is taken it will randomize to a plot that isn't?

How should I make it randomize to a plot that isn’t taken if a plot that was taken was chosen?

local PlotService = require(game.ReplicatedStorage.PlotService)

local Homes = game.ServerStorage.Homes:GetChildren()
local Plots = workspace.HomePlots:GetChildren()

game.Players.PlayerAdded:Connect(function(player)

local RandomPlot = math.random(#Plots)
local ChosenPlot = game.Workspace.HomePlots:FindFirstChild("Plot"..RandomPlot)
print(ChosenPlot)

if ChosenPlot.Owner.Value == nil then
	ChosenPlot.Owner.Value = player
	
	local RandomHome = math.random(#Homes)
	local ChosenHome = game.ServerStorage.Homes:FindFirstChild(RandomHome):Clone()
	
	ChosenHome.Parent = ChosenPlot.Home
	ChosenHome:SetPrimaryPartCFrame(ChosenPlot.CFrame)
	print(ChosenHome)
else
	-- ( If the chosen plot was taken randomize to one that isn't
	
end
end)
local PlotService = require(game.ReplicatedStorage.PlotService)

local Homes = game.ServerStorage.Homes:GetChildren()
local Plots = workspace.HomePlots:GetChildren()

function randomize()
	local randomNumber = math.random(#Plots)
	local ChosenPlot = game.Workspace.HomePlots:FindFirstChild("Plot"..randomNumber)
	
	if ChosenPlot.Owner.Value ~= nil then
		return randomize()
	else
		return ChosenPlot
	end
end

game.Players.PlayerAdded:Connect(function(player)

	local RandomPlot = math.random(#Plots)
	local ChosenPlot = game.Workspace.HomePlots:FindFirstChild("Plot"..RandomPlot)
	print(ChosenPlot)

	if ChosenPlot.Owner.Value == nil then
		ChosenPlot.Owner.Value = player

		local RandomHome = math.random(#Homes)
		local ChosenHome = game.ServerStorage.Homes:FindFirstChild(RandomHome):Clone()

		ChosenHome.Parent = ChosenPlot.Home
		ChosenHome:SetPrimaryPartCFrame(ChosenPlot.CFrame)
		print(ChosenHome)
	else
		local ChosenPlot = randomize()
		print(ChosenPlot)
	end
end)

This should work however I don’t have a way to test it without a place file. In theory though, it would work because if the chosen plot is taken, it would return the calling of the function until it finds a plot that is not taken.

Edit
Just tested my example with this piece of code. This is not relevant to the current problem and is only to show my testing.

Test Code
local tab = {
	[1] = false;
	[2] = true;
	[3] = false;
}

function randomize()
	local randomNumber = math.random(1, 3)
	local ChosenPlot = tab[randomNumber]
	
	if ChosenPlot == false then
		return randomize()
	else
		return randomNumber
	end
end

print(randomize()) --> 2
1 Like

Works great! Thank you : ) 30char

1 Like