You can make a table of function, although it’s not the most efficient way:
local Commands = {
set = function() --[[ Command code here ]] end,
admin = function() --[[ Command code here ]] end,
load = function() --[[ Command code here ]] end
--- etc.
}
--// When the player chats
Player.Chatted:Connect(function(Message)
if Commands[string.lower(Message)] then -- Checks if the command is in the table
Commands[string.lower(Message)]() -- Calls the command from the table
end
end)
This method is much more organized, but as I said, performance might be a bit worse, or better. Even if it worse it won’t make much of a difference.
Sadly, this wouldn’t really help because if I wanted to create a “subcommand” (such as set admin and set data) then I would have to either do what I did above (will get messy), or create an entirely new table of subcommands specifically for set (will also get messy). I could do
local handlers = {}
local function addHandler(name, func)
handlers[name] = func
end
local function handle(commandData)
local name = table.remove(commandData, 1)
local handler = assert(handlers[name], "No handler for command: " .. name)
handler(commandData)
end
addHandler("set", function (commandData)
if commandData[1] == "admin" then
-- ...
end
end)
addHandler("load", function (commandData)
-- ...
end)
You can use a dictionary instead of no dictionary:
local Commands = {
["set"] = function() --[[ Command code here ]] end,
["admin"] = function() --[[ Command code here ]] end,
["load"] = function() --[[ Command code here ]] end,
["set admin"] = function() --[[ Command code here ]] end
--- etc.
}
--// When the player chats
Player.Chatted:Connect(function(Message)
if Commands[string.lower(Message)] then -- Checks if the command is in the table
Commands[string.lower(Message)]() -- Calls the command from the table
end
end)
Consider also using a proper library for creating commands. I personally love Cmdr, and it’s got built-in type checking, among other fantastic goodies.