Welcome to my tutorial, so 1 year ago I saw this function called string.split, it can be used for admin commands but I’ve seen alot of people having trouble with it so I made a tutorial about it, ok now let’s finally start the tutorial.
Why use string.split over string.sub?
it’s your choice, you will find string.split easier to work with than string.sub
Now let’s write an admin command system. A simple one
game.Players.PlayerAdded:Connect(function(plr)
plr.Chatted:Connect(function(msg)
end)
end)
Now, we will write a string.split variable.
game.Players.PlayerAdded:Connect(function(plr)
plr.Chatted:Connect(function(msg)
local split = string.split(msg," ")
end)
end)
Now, we want to make a kick command
game.Players.PlayerAdded:Connect(function(plr)
plr.Chatted:Connect(function(msg)
local split = string.split(msg," ")
if split[1]:lower() == "/kick" then
end
end)
end)
It still does nothing, let’s make it do something, but let me explain first, string.split returns a table of the splitted strings, just to not get confused.
Now, we will kick the player with the second argument.
game.Players.PlayerAdded:Connect(function(plr)
plr.Chatted:Connect(function(msg)
local split = string.split(msg," ")
if split[1]:lower() == "/kick" then
if game.Players:FindFirstChild(split[2]) ~= nil then
game.Players:FindFirstChild(split[2]):Kick()
end
end
end)
end)
Yes, it does work and kicks the player, but what if you want the 3rd argument to be the reason message? This is a tricky one, as you can’t simply just do split[3], if you do it will only capture one word from the sentence, so you would want to get all of the words after the two arguments, but how? We can make a new variable with an empty table, and after the 2 arguments, we will capture all words after the 2 arguments and assign the variable to all of the captured words after the two arguments, here’s how I do it.
local sentencetable = {}
local sentence = ""
sentencetable = split
for i = 1,2 do -- replace the 2 with how much arguments you have
table.remove(sentencetable,i)
end
-- make it to string
for i,v in ipairs(sentencetable) do
sentence = sentence..v
end
the finished code :
game.Players.PlayerAdded:Connect(function(plr)
plr.Chatted:Connect(function(msg)
local split = string.split(msg," ")
if split[1]:lower() == "/kick" then
if game.Players:FindFirstChild(split[2]) ~= nil then
local sentencetable = {}
local sentence = ""
sentencetable = split
for i = 1,2 do -- replace the 2 with how much
arguments you have
table.remove(sentencetable,i)
end
-- make it to string
for i,v in ipairs(sentencetable) do
sentence = sentence..v
end
game.Players:FindFirstChild(split[2]):Kick(sentence)
end
end
end)
end)
However, here’s a condition:
If you want a sentence argument, it must be the last argument and only 1 sentence, unless you change the split keyword
Any feedback is appreciated.