Hello,
I’m trying to make an admin commands script using a function, but there is a problem with it, when i added a command called “print (message}” which will pretty much just print something to the output, it only prints the first word of it, for example when im saying “-print This is a test command”, it only prints “This”. Can anyone help me with this? The code is below. Thank you!
local lp = game.Players.LocalPlayer
local prefix = "-"
local cmds = {}
function addcmd(i, v, k, func) cmds[i] = {name = i, argfm = v, desc = k, func = func} end
lp.Chatted:Connect(function(msg)
local args = msg:split(" ")
local cmd = args[1]
table.remove(args, 1)
if msg:sub(1, #prefix) ~= prefix then return end
local _cmd = cmd:sub(#prefix + 1):split(" ")[1]
cmd = cmds[_cmd]
if not cmd then
print(("Invalid command (%s)"):format(_cmd))
return end
cmd.func(unpack(args))
end)
addcmd("print", "Prints a message to the output.", "message", function(message)
print(message)
end)
Your function to the print cmd you have was only set to print the first parameter passed to its func. Use a variadic argument instead.
local lp = game.Players.LocalPlayer
local prefix = "-"
local cmds = {}
function addcmd(i, v, k, func)
cmds[i] = {
name = i,
argfm = v,
desc = k,
func = func
}
end
lp.Chatted:Connect(function(msg)
if not (msg:sub(1, #prefix) == prefix) then
return
end
msg = msg:sub(#prefix + 1, #msg)
local args = msg:split(" ")
local _cmd = table.remove(args, 1) -- popping the first argument out of the args array
local cmd = cmds[_cmd]
if not cmd then
print(("Invalid command (%s)"):format(_cmd))
end
cmd.func(unpack(args))
end)
addcmd("print", "Prints a message to the output.", "message", function(...)
print(...)
end)
This splits your string into an ordered table (args) by spaces. When you call cmd.func (The function created when addcmd is called) you’re calling unpack(args). This returns the contents of args in order. The function you connect for print however accepts one argument, message, whereas it’s being fed any number of strings containing each individual word.
You can tackle this problem from either side either changing the cmd.func call to simply provide the table args and read it from there, or by changing your function into a Variadic Function and packing the arguments into a table. I suggest changing the cmd.func call to cmd.func(args) instead however and connecting functions that accept a table of arguments.