Difference between revisions of "AddCommandHandler"

From Multi Theft Auto: Wiki
Jump to: navigation, search
(Example)
 
(37 intermediate revisions by 17 users not shown)
Line 3: Line 3:
 
{{Note_box|It is strongly advised that you do not use the same name for your handler function as the command name, as this can lead to confusion if multiple handler functions are used. Use a name that describes your handler's purpose more specifically.}}
 
{{Note_box|It is strongly advised that you do not use the same name for your handler function as the command name, as this can lead to confusion if multiple handler functions are used. Use a name that describes your handler's purpose more specifically.}}
 
This function will attach a scripting function (handler) to a console command, so that whenever a player or administrator uses the command the function is called.
 
This function will attach a scripting function (handler) to a console command, so that whenever a player or administrator uses the command the function is called.
 +
'''Note:''' You cannot use "check", "list" or "test" as a command name.
  
 
Multiple command handlers can be attached to a single command, and they will be called in the order that the handlers were attached. Equally, multiple commands can be handled by a single function, and the ''commandName'' parameter used to decide the course of action.
 
Multiple command handlers can be attached to a single command, and they will be called in the order that the handlers were attached. Equally, multiple commands can be handled by a single function, and the ''commandName'' parameter used to decide the course of action.
Line 13: Line 14:
  
 
==Syntax==  
 
==Syntax==  
 +
 
<section name="Server" class="server" show="true">
 
<section name="Server" class="server" show="true">
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
bool addCommandHandler ( string commandName, function handlerFunction, [bool restricted = false, bool caseSensitive = true] )
+
bool addCommandHandler ( string commandName, function handlerFunction [, bool restricted = false, bool caseSensitive = true ] )
 
</syntaxhighlight>  
 
</syntaxhighlight>  
  
 
===Required Arguments===
 
===Required Arguments===
 
*'''commandName:''' This is the name of the command you wish to attach a handler to. This is what must be typed into the console to trigger the function.
 
*'''commandName:''' This is the name of the command you wish to attach a handler to. This is what must be typed into the console to trigger the function.
*'''handlerFunction:''' This is the function that you want the command to trigger, which has to be defined before you add the handler. This function can take two parameters, playerSource and commandName, followed by as many parameters you expect after your command (see below). These are all optional.
+
*'''handlerFunction:''' This is the function that you want the command to trigger, which has to be defined before you add the handler. This function can take two parameters, playerSource and commandName, followed by as many parameters as you expect after your command (see below). These are all optional.
 
===Optional Arguments===  
 
===Optional Arguments===  
 
{{OptionalArg}}  
 
{{OptionalArg}}  
*'''restricted:''' Specify whether or not this command should be restricted by default. Use this on commands that should be inaccessible to everyone as default except special users specified in the ACL (Access Control List). This is to make sure admin commands such as ie. 'punish' won't be available to everyone if a server administrator forgets masking it in ACL. This argument defaults to false if nothing is specified.
+
*'''restricted:''' Specify whether or not this command should be restricted by default. Use this on commands that should be inaccessible to everyone as default except special users specified in the ACL (Access Control List). This is to make sure admin commands such as ie. 'punish' won't be available to everyone if a server administrator forgets masking it in ACL. Make sure to add the command to your ACL under the proper group for it to be usefull (i.e <right name="command.killEveryone" access="true"></right>). This argument defaults to false if nothing is specified.
 
{{New feature|3|1.0|
 
{{New feature|3|1.0|
 
*'''caseSensitive:''' Specifies if the command handler will ignore the case for this command name.
 
*'''caseSensitive:''' Specifies if the command handler will ignore the case for this command name.
Line 29: Line 31:
  
 
</section>
 
</section>
 +
 +
 
<section name="Client" class="client" show="true">
 
<section name="Client" class="client" show="true">
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
bool addCommandHandler ( string commandName, function handlerFunction, [bool caseSensitive = true] )
+
bool addCommandHandler ( string commandName, function handlerFunction [, bool caseSensitive = true ] )
 
</syntaxhighlight>  
 
</syntaxhighlight>  
  
 
===Required Arguments===
 
===Required Arguments===
 
*'''commandName:''' This is the name of the command you wish to attach a handler to. This is what must be typed into the console to trigger the function.
 
*'''commandName:''' This is the name of the command you wish to attach a handler to. This is what must be typed into the console to trigger the function.
*'''handlerFunction:''' This is the function that you want the command to trigger, which has to be defined before you add the handler. This function can take two parameters, playerSource and commandName, followed by as many parameters you expect after your command (see below). These are all optional.
+
*'''handlerFunction:''' This is the function that you want the command to trigger, which has to be defined before you add the handler. This function can take commandName parameter, followed by as many parameters as you expect after your command (see below). These are all optional.
 
===Optional Arguments===  
 
===Optional Arguments===  
 
{{OptionalArg}}  
 
{{OptionalArg}}  
Line 47: Line 51:
 
These are the parameters for the handler function that is called when the command is used.
 
These are the parameters for the handler function that is called when the command is used.
 
<section name="Server" class="server" show="true">
 
<section name="Server" class="server" show="true">
<syntaxhighlight lang="lua">player playerSource, string commandName, [string arg1, string arg2, ...] </syntaxhighlight>
+
<syntaxhighlight lang="lua">player playerSource, string commandName [, string arg1, string arg2, ... ] </syntaxhighlight>
  
* '''playerSource:''' The player who triggered the command. If not triggered by a player (e.g. by admin), this will be ''false''.
+
* '''playerSource:''' The player who triggered the command or the [[Element/Console|server console]]. If not triggered by a player (e.g. by admin) or server console, this will be ''false''.
 
* '''commandName:''' The name of the command triggered. This is useful if multiple commands go through one function.
 
* '''commandName:''' The name of the command triggered. This is useful if multiple commands go through one function.
* '''arg1, arg2, ...:''' Each word after command name in the original command is passed here in a seperate variable. If there is no value for an argument, its variable will contain [[nil]]. You can deal with a variable number of arguments using the vararg expression, as shown in '''Example 3''' below.
+
* '''arg1, arg2, ...:''' Each word after command name in the original command is passed here in a seperate variable. If there is no value for an argument, its variable will contain [[nil]]. You can deal with a variable number of arguments using the vararg expression, as shown in '''Server Example 2''' below.
 
</section>
 
</section>
  
 
<section name="Client" class="client" show="true">
 
<section name="Client" class="client" show="true">
<syntaxhighlight lang="lua"> string commandName, [string arg1, string arg2, ...] </syntaxhighlight>
+
<syntaxhighlight lang="lua">string commandName [, string arg1, string arg2, ... ] </syntaxhighlight>
 
* '''commandName:''' The name of the command triggered. This is useful if multiple commands go through one function.
 
* '''commandName:''' The name of the command triggered. This is useful if multiple commands go through one function.
* '''arg1, arg2, ...:''' Each word after command name in the original command is passed here in a seperate variable. If there is no value for an argument, its variable will contain [[nil]]. You can deal with a variable number of arguments using the vararg expression, as shown in '''Example 3''' below.
+
* '''arg1, arg2, ...:''' Each word after command name in the original command is passed here in a seperate variable. If there is no value for an argument, its variable will contain [[nil]]. You can deal with a variable number of arguments using the vararg expression, as shown in '''Server Example 2''' below.
 
</section>
 
</section>
  
Line 63: Line 67:
 
Returns ''true'' if the command handler was added successfully, ''false'' otherwise.
 
Returns ''true'' if the command handler was added successfully, ''false'' otherwise.
  
==Example==  
+
==Examples==  
 
<section name="Server" class="server" show="true">
 
<section name="Server" class="server" show="true">
 
'''Example 1:''' This example defines a command handler for the command ''createmarker''. This will create a red marker at the position of the player player who uses it.
 
'''Example 1:''' This example defines a command handler for the command ''createmarker''. This will create a red marker at the position of the player player who uses it.
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
 
-- Define our function that will handle this command
 
-- Define our function that will handle this command
function consoleCreateMarker ( playerSource )
+
function consoleCreateMarker ( playerSource, commandName )
 
-- If a player triggered it (rather than the admin) then
 
-- If a player triggered it (rather than the admin) then
 
if ( playerSource ) then
 
if ( playerSource ) then
Line 82: Line 86:
 
addCommandHandler ( "createmarker", consoleCreateMarker )
 
addCommandHandler ( "createmarker", consoleCreateMarker )
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
</section>
  
'''Example 2:''' A simple health setting command. If a player types ''/sethealth X'' in the chatbox his health will be set to X. Note that the function [[setElementHealth]] is used rather than something like "setPlayerHealth". This function is more generic and can also be used to set the health of vehicles.
+
<section name="Server" class="server" show="hide">
<syntaxhighlight lang="lua">
+
'''Example 2:''' This example makes use of Lua's vararg expression to implement a ''check_parameters'' command to count the number of parameters passed, merge them all into a single string and output it. This is also shows you how you can use table.concat to merge all the passed arguments. This is particularly useful when you want to read in a sentence of text passed from the user.  
function consoleSetHealth(playerSource, commandName, health)
 
setElementHealth(playerSource, tonumber(health))
 
end
 
addCommandHandler("sethealth", consoleSetHealth)
 
</syntaxhighlight>
 
 
 
'''Example 3:''' This example implements a ''set_vehicle_color'' command.
 
<syntaxhighlight lang="lua">
 
-- Define our function that will handle this command
 
function consoleSetVehicleColor ( playerSource, commandName, col1, col2, col3, col4 )
 
-- If a player triggered this in-game
 
if ( playerSource ) then
 
-- Get the player's vehicle
 
local playerVehicle = getPedOccupiedVehicle ( playerSource )
 
-- If the player is in a vehicle and we've got at least 1 parameter
 
if ( playerVehicle and col1 ) then
 
-- Get the vehicle's existing color and use it if fewer than 4 arguments were passed
 
local exCol1, exCol2, exCol3, exCol4 = getVehicleColor ( playerVehicle )
 
 
 
if not col2 then col2 = exCol2 end
 
if not col3 then col3 = exCol3 end
 
if not col4 then col4 = exCol4 end
 
 
 
-- Set the vehicle's color
 
setVehicleColor ( playerVehicle, col1, col2, col3, col4 )
 
else
 
-- If we didn't get at least 1 parameter or the player doesn't have a vehicle, display some help text
 
outputConsole ( "This function will set your current vehicle's colors. A vehicle can have up to 4 colors.", playerSource )
 
outputConsole ( "Syntax: set_vehicle_color color1 [ color2 color3 color4 ]", playerSource )
 
outputConsole ( "You must be in a vehicle to use this function.", playerSource )
 
end
 
end
 
end
 
-- Attach the 'consoleSetVehicleColor' function to the "set_vehicle_color" command
 
addCommandHandler ( "set_vehicle_color", consoleSetVehicleColor )
 
</syntaxhighlight>
 
 
 
'''Example 4:''' This example makes use of Lua's vararg expression to implement a ''check_parameters'' command to count the number of parameters passed, merge them all into a single string and output it. This is also shows you how you can use table.concat to merge all the passed arguments. This is particularly useful when you want to read in a sentence of text passed from the user.  
 
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
 
-- Define our function that will handle this command (which can accept a variable number of arguments after commandName)
 
-- Define our function that will handle this command (which can accept a variable number of arguments after commandName)
Line 128: Line 95:
 
-- If a player, not an admin, triggered it,
 
-- If a player, not an admin, triggered it,
 
if playerSource then
 
if playerSource then
-- Pack all extra arguments passed in a table
+
local arg = {...}
local parametersTable = {...}
+
-- Get the number of arguments in the arg table (arg table is the same as: {...})
-- Get the number of arguments in that table
+
local parameterCount = #arg
local parameterCount = #parametersTable
 
 
-- Output it to the player's chatbox
 
-- Output it to the player's chatbox
 
outputChatBox ( "Number of parameters: " .. parameterCount, playerSource )
 
outputChatBox ( "Number of parameters: " .. parameterCount, playerSource )
 
-- Join them together in a single comma-separated string
 
-- Join them together in a single comma-separated string
local stringWithAllParameters = table.concat( parametersTable, ", " )
+
local stringWithAllParameters = table.concat( arg, ", " )
 
-- Output this parameter list to the player's chatbox
 
-- Output this parameter list to the player's chatbox
 
outputChatBox ( "Parameters passed: " .. stringWithAllParameters, playerSource )
 
outputChatBox ( "Parameters passed: " .. stringWithAllParameters, playerSource )
Line 143: Line 109:
 
addCommandHandler ( "check_parameters", consoleCheckParameters )
 
addCommandHandler ( "check_parameters", consoleCheckParameters )
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
</section>
  
'''Example 5:''' This example shows using a single function to handle multiple command handlers. This isn't advised for general usage, as it makes code harder to understand, but where multiple command handlers share some logic, it can be a useful way of reducing duplicated code. Generally, it would be preferable to put this shared logic in a separate function instead, as this gives you more control over the flow.
+
<section name="Server" class="server" show="hide">
 +
'''Example 3:''' This example shows using a single function to handle multiple command handlers. This isn't advised for general usage, as it makes code harder to understand, but where multiple command handlers share some logic, it can be a useful way of reducing duplicated code. Generally, it would be preferable to put this shared logic in a separate function instead, as this gives you more control over the flow.
 
<!-- commands are case sensitive by default, in this example too -->
 
<!-- commands are case sensitive by default, in this example too -->
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
 
-- make the function
 
-- make the function
function moneyCmd(player, cmd, amount)
+
function moneyCmd(player, commandName, amount)
 
     if getElementData(player, "canUseMoneyFunctions") then -- the shared logic
 
     if getElementData(player, "canUseMoneyFunctions") then -- the shared logic
         if cmd == "givemoney" then
+
         if commandName == "givemoney" then
 
             amount  = tonumber(amount)
 
             amount  = tonumber(amount)
 
             if amount then
 
             if amount then
Line 157: Line 125:
 
                 outputChatBox("[usage] /givemoney [amount]", player)
 
                 outputChatBox("[usage] /givemoney [amount]", player)
 
             end
 
             end
         else if cmd == "takemoney" then
+
         else if commandName == "takemoney" then
 
             amount = tonumber(amount)
 
             amount = tonumber(amount)
 
             if amount then
 
             if amount then
Line 174: Line 142:
 
</syntaxhighlight>
 
</syntaxhighlight>
 
</section>
 
</section>
<section name="Client" class="client" show="true">
 
'''Example 1:''' This creates a GUI window and allows a player to change its alpha (transparency) value with a command. Note that, in a clientside script, the player using the command is not passed as a parameter to the handler function, since it is always the local player.
 
  
<syntaxhighlight lang="lua">--Create a window
+
<section name="Client" class="client" show="false">
myWindow = guiCreateWindow ( 0.30, 0.10, 0.5, 0.60, "GUI window title", true )
+
'''Example 1:''' This example warps the local player to a random nearby location (useful for when a player gets stuck somewhere).
  
--Add a command handler to change the alpha of the GUI window. Usage example: 'alpha 0.15'
+
<syntaxhighlight lang="lua">function escapeMe ( commandName )
function changeAlpha ( commandName, alphaAmount )
+
local x, y, z = getElementPosition ( localPlayer ) --Get player's position
-- All command parameters are strings, so we'll convert the value to a number first
+
setElementPosition ( localPlayer, x+(math.random(-10,10)), y+(math.random(-10,10)), z+(math.random(1,15)) ) --Move a player randomly to a nearby location. X is current x + a number between -10, 10 and so on.
alphaAmount = tonumber(alphaAmount)
+
end  
guiSetAlpha ( myWindow, alphaAmount )
+
addCommandHandler ( "escape", escapeMe ) --When player types "/escape" in chatbox or "escape" in console
end
 
addCommandHandler ( "alpha", changeAlpha )
 
 
</syntaxhighlight>
 
</syntaxhighlight>
 
</section>
 
</section>
Line 192: Line 156:
 
==See Also==
 
==See Also==
 
{{Server functions}}
 
{{Server functions}}
 +
 +
[[hu:addCommandHandler]]

Latest revision as of 13:23, 11 August 2018

Note: It is strongly advised that you do not use the same name for your handler function as the command name, as this can lead to confusion if multiple handler functions are used. Use a name that describes your handler's purpose more specifically.

This function will attach a scripting function (handler) to a console command, so that whenever a player or administrator uses the command the function is called. Note: You cannot use "check", "list" or "test" as a command name.

Multiple command handlers can be attached to a single command, and they will be called in the order that the handlers were attached. Equally, multiple commands can be handled by a single function, and the commandName parameter used to decide the course of action.

For users, a command is in the format:

commandName argument1 argument2

This can be triggered from the player's console or directly from the chat box by prefixing the message with a forward slash (/). For server side handlers, the server admin is also able to trigger these directly from the server's console in the same way as they are triggered from a player's console.

Syntax

Click to collapse [-]
Server
bool addCommandHandler ( string commandName, function handlerFunction [, bool restricted = false, bool caseSensitive = true ] )

Required Arguments

  • commandName: This is the name of the command you wish to attach a handler to. This is what must be typed into the console to trigger the function.
  • handlerFunction: This is the function that you want the command to trigger, which has to be defined before you add the handler. This function can take two parameters, playerSource and commandName, followed by as many parameters as you expect after your command (see below). These are all optional.

Optional Arguments

NOTE: When using optional arguments, you might need to supply all arguments before the one you wish to use. For more information on optional arguments, see optional arguments.

  • restricted: Specify whether or not this command should be restricted by default. Use this on commands that should be inaccessible to everyone as default except special users specified in the ACL (Access Control List). This is to make sure admin commands such as ie. 'punish' won't be available to everyone if a server administrator forgets masking it in ACL. Make sure to add the command to your ACL under the proper group for it to be usefull (i.e <right name="command.killEveryone" access="true"></right>). This argument defaults to false if nothing is specified.
  • caseSensitive: Specifies if the command handler will ignore the case for this command name.


Click to collapse [-]
Client
bool addCommandHandler ( string commandName, function handlerFunction [, bool caseSensitive = true ] )

Required Arguments

  • commandName: This is the name of the command you wish to attach a handler to. This is what must be typed into the console to trigger the function.
  • handlerFunction: This is the function that you want the command to trigger, which has to be defined before you add the handler. This function can take commandName parameter, followed by as many parameters as you expect after your command (see below). These are all optional.

Optional Arguments

NOTE: When using optional arguments, you might need to supply all arguments before the one you wish to use. For more information on optional arguments, see optional arguments.

  • caseSensitive: Specifies if the command handler will ignore the case for this command name.

Handler function parameters

These are the parameters for the handler function that is called when the command is used.

Click to collapse [-]
Server
player playerSource, string commandName [, string arg1, string arg2, ... ] 
  • playerSource: The player who triggered the command or the server console. If not triggered by a player (e.g. by admin) or server console, this will be false.
  • commandName: The name of the command triggered. This is useful if multiple commands go through one function.
  • arg1, arg2, ...: Each word after command name in the original command is passed here in a seperate variable. If there is no value for an argument, its variable will contain nil. You can deal with a variable number of arguments using the vararg expression, as shown in Server Example 2 below.
Click to collapse [-]
Client
string commandName [, string arg1, string arg2, ... ] 
  • commandName: The name of the command triggered. This is useful if multiple commands go through one function.
  • arg1, arg2, ...: Each word after command name in the original command is passed here in a seperate variable. If there is no value for an argument, its variable will contain nil. You can deal with a variable number of arguments using the vararg expression, as shown in Server Example 2 below.

Returns

Returns true if the command handler was added successfully, false otherwise.

Examples

Click to collapse [-]
Server

Example 1: This example defines a command handler for the command createmarker. This will create a red marker at the position of the player player who uses it.

-- Define our function that will handle this command
function consoleCreateMarker ( playerSource, commandName )
	-- If a player triggered it (rather than the admin) then
	if ( playerSource ) then
		-- Get that player's position
		local x, y, z = getElementPosition ( playerSource )
		-- Create a size 2, red checkpoint marker at their position
		createMarker ( x, y, z, "checkpoint", 2, 255, 0, 0, 255 )
		-- Output it in his chat box
		outputChatBox ( "You got a red marker", playerSource )
	end
end
-- Attach the 'consoleCreateMarker' function to the "createmarker" command
addCommandHandler ( "createmarker", consoleCreateMarker )
Click to expand [+]
Server
Click to expand [+]
Server
Click to expand [+]
Client

See Also