PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Join Team Command

Join Team Command

Jun 26 2018, 11:14 AM PST

This code sample allows any player to chat "/jointeam " where is the name of a team. It uses string manipulation using string.sub and string.lower to make the command case-insensitive and allow for partial matches. For example, “/jointeam red” will match the team “Red Robins”.

local Players = game:GetService("Players")
local Teams = game:GetService("Teams")

-- Command to choose a team (note the trailing space)
local joinCommand = "/jointeam "

local function findTeamByName(name)
	-- First, check for the exact name of a team
	if Teams:FindFirstChild(name) then return Teams[name] end
	-- Let's check for case-insensitive partial matches, like "red" for "Red Robins"
	for _, team in pairs(Teams:GetChildren()) do
		if team.Name:sub(1, name:len()):lower() == name:lower() then
			return team
		end
	end
	-- If we get to this point, no team matched the one we were looking for :(
end

local function onPlayerChatted(player, message, recipient)
	-- Note: string.sub(message, ...) is the same as message:sub(...)
	if message:sub(1, joinCommand:len()):lower() == joinCommand:lower() then
		-- Matched "/JOINTEAM xyz" to our join command prefix "/jointeam "
		local teamName = message:sub(joinCommand:len() + 1) -- Cut out the "xyz" from "/jointeam xyz"
		local team = findTeamByName(teamName)
		if team then
			-- Set the team!
			player.Team = team
			player.Neutral = false
		else
			-- Tell the player that team could not be found :(
			player.Team = nil
			player.Neutral = true
		end
	end
end

local function onPlayerAdded(player)
	player.Chatted:connect(function (...)
		onPlayerChatted(player, ...)
	end)
end

-- Listen for players being added
for _, player in pairs(Players:GetPlayers()) do
	onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)