Creating Commands

From SA-MP Wiki

Jump to: navigation, search

Contents

Introduction

This tutorial will first teach how to make basic commands using the strcmp function, then get onto more advanced command structures (e.g. parameters, dcmd).

Commands are possibly the most used feature for user interaction in PAWN scripts, so being able to create your own command is really a nice asset when you create your own script. They can be created using the OnPlayerCommandText scripting callback.

Tutorial

Basic Commands

An example of a basic teleport command is shown below. This command will display the text "Hello Player!" (without quotes) to the player who typed the command.

public OnPlayerCommandText(playerid, cmdtext[])
 {
     if(strcmp(cmdtext, "/mycommand") == 0) 
     {
        SendClientMessage(playerid, 0xFFFFFFFF, "Hello Player!");
        return 1;
     }
     return 0;
}

This command works when the event OnPlayerCommandText is called. When it's called the playerid and cmdtext (string) is also parsed through, you can control what happens using the if statements.

Basic Teleport Command

An example of a basic command is shown below. This command will Teleport the player who typed the command.

public OnPlayerCommandText(playerid, cmdtext[])
{
     if(strcmp(cmdtext, "/myteleport") == 0) 
     {
         SetPlayerPos(playerid, X, Y, Z);
         return 1;
     }
     return 0;
}

To get your X, Y, Z (floats) co-ordinates, use /save in game have a look on the Debug Guide

Adding strings to commands

Now i will add a message like "name has typed /myteleport"

public OnPlayerCommandText(playerid, cmdtext[]) 
{
    if(strcmp(cmdtext, "/myteleport") == 0) 
    {
        new string[52];
        new name[24];
        GetPlayerName(playerid,name,24);
        SetPlayerPos(playerid, X, Y, Z);
        format(string,sizeof(string),"%s has just typed /myteleport",name);
        SendClientMessageToAll(0xFFFFFFFF,string);
        return 1;
    }
    return 0;
}

Format Strings

Placeholder Meaning
%b Inserts a number at this position in binary radix
%c Inserts a single character.
%d Inserts an integer (whole) number
%f Inserts a floating point number.
%i Inserts an integer.
%s Inserts a string.
%x Inserts a number in hexadecimal notation.
%% Inserts the literal '%'

The values for the placeholders follow in the exact same order as parameters in the call.

You may optionally put a number between the '%' and the letter of the placeholder code. This number indicates the field width; if the size of the parameter to print at the position of the placeholder is smaller than the field width, the field is expanded with spaces.