API RegisterUserCommand
RegisterUserCommand
Definition:
RegisterUserCommand(string commandname, func callback(dataarg, {arguments1, ..}), data) -> nil
Description:
hook up object to command
Arguments:
commandname string containing the command
callback function accepting two arguments to run when command is executed
dataarg see data
arguments1 arguments of the command (Note: if there are no arguments the table is nil not an empty table.)
data data to pass callback
Example:
<source lang="lua">
-- function to call when the command is entered
local function printfunc(data, args)
-- data contains the third parameter of RegisterUserCommand local str = tostring(data) -- if the command was entered without parameters args is nil otherwise a table containing the parameters if args then str = str..tostring(args[1]) end print(str)
end
RegisterUserCommand("printsomething", printfunc, "test")</source>
Registers the command "printsomething" that calls a function that prints the text "test" and the first argument appended
Additional information
If you are authoring a plugin, please consider only using this function once within your code. Below is an example of how this might be done.
<source lang="lua">
-- myplugin/main.lua
declare("myplugin", {})
myplugin.commands = {}
myplugin.commands.start = function(args)
-- handle start print("Starting")
end myplugin.commands.stop = function(args)
-- handle stop print("Stopping")
end
RegisterUserCommand("myplugin", function(_, args)
if(args ~= nil) then
local func = myplugin.commands[args[1]]
if (func ~= nil) then
table.remove(args, 1)
func(args)
return
end
print("Invalid command")
end
-- do something if no sub-command is requested
print("myplugin v1.0")
end)</source>
This setup allows a plugin user to access the functions with /myplugin start, and /myplugin stop.