I am trying to make command arguments in Roblox. For example, /kill playername
. The problem is I don\'t know how to parse the playername from the string /kill
If you want this to be more flexible to more commands in the future, I suggest you take both lhf's and BotOfWar's suggestions and combine them.
local function executeCommandInMessage(message)
-- do a quick regex of the message to see if it is formatted as a command
-- all we care about is the command, any arguments are optional.
local command, arguments = string.match(message, "^/(%w+)[%s]?([%w%s]+)$")
if command ~= nil then
-- we've found a command, parse the arguments into groups of non-space characters
-- then store each word in the parts array
local parts = {}
for w in arguments:gmatch("%S+") do
table.insert(parts, w)
end
-- handle each command individually
if command == "kill" then
local player = parts[1]
print(string.format("Killing %s", player))
elseif command == "setdata" then
local player = parts[1]
local value = parts[2]
local amount = parts[3]
print(string.format("Setting %s on %s to %s", value, player, amount))
-- add any further commands to the list..
-- elseif command == "" then
end
end
end
-- listen for any message submitted by players
game:GetService("Players").PlayerAdded:Connect(function(Player)
Player.Chatted:Connect(function(msg)
-- check for any commands
executeCommandInMessage(msg)
end)
end)
In the future, if you need a better regex to parse the message, I suggest you take a look at how to do Lua pattern matching. They're pretty easy to read once you know what to look at.
I suggest splitting the string with the string.split
method to get the segments, then check if the first value is what you want.
game:GetService("Players").PlayerAdded:Connect(function(Player)
Player.Chatted:Connect(function(Message)
local segments = Message:split(" ")
if((#segments >= 1) and (segments[1] == "/kill")) then
-- The rest of the arguments can be accessed like this:
local args = {unpack(segments, 2)} -- Gets every argument after the first value,
-- which is the command.
end
end)
end)
Use string.match
:
Message=" /kill playername "
command, arg = Message:match("%s*/(.-)%s+(.*)%s*$")