Strtok

From SA-MP Wiki

Jump to: navigation, search

strtok

Image:Farm-Fresh text lowercase.png Note: This function name starts with a lowercase letter.


Image:32px-Ambox_warning_orange.png

Note

This function is deprecated and use of it should be avoided where possible.
Better alternatives like sscanf are available for you to use.


strtok


This (strtok) is used to search a string and find a variable typed after a " " (space), then return it as a string.

strtok(const string[], &index)
{
	new length = strlen(string);
	while ((index < length) && (string[index] <= ' '))
	{
		index++;
	}
 
	new offset = index;
	new result[20];
	while ((index < length) && (string[index] > ' ') && ((index - offset) < (sizeof(result) - 1)))
	{
		result[index - offset] = string[index];
		index++;
	}
	result[index - offset] = EOS;
	return result;
}
Tutorial


Lets try making a simple /kick command. Under your OnPlayerCommandText, for strtok you must include the following code:

new cmd[128], idx;
	cmd = strtok(cmdtext, idx);

On the command, instead of using "cmdtext", we would use "cmd":

if(strcmp(cmd, "/kick", true) == 0)
	{

This is so the command won't return as an "unknown command", as you wont only be typing the command itself, but a, or some, spaces and variables with it.

Now, to start making the command itself. We are going to create a "tmp" variable with a MAX_STRING of 128 cells:

new tmp[128];

We are going to assign that string to strtok:

tmp = strtok(cmdtext, idx);

So, now "tmp" will hold the string value of what was typed "/kick HERE". But, what happens if they didn't type a space? "tmp" will then be strlen (string length) 0. So:

if(strlen(tmp) == 0) return SendClientMessage(playerid, 0xFFFFFFFF, "USAGE: /kick [playerid]");

Now we've sent them a message to tell them the correct syntax, and also "return"'d it, meaning anything after that message won't work. If the strlen was not 0, let us continue.

All we've really got left to do, is kick the player:

Kick(strval(tmp));

We have just kicked the strval (string value) of tmp. You can't kick a string, so strval tells you the value of it.

This is the finished product:

public OnPlayerCommandText(playerid, cmdtext[])
{
	new cmd[128], idx;
	cmd = strtok(cmdtext, idx);
 
	if(strcmp(cmd, "/kick", true) == 0)
	{
		new tmp[128];
		tmp = strtok(cmdtext, idx);
 
		if(strlen(tmp) == 0) return SendClientMessage(playerid, 0xFFFFFFFF, "USAGE: /kick [playerid]");
 
		Kick(strval(tmp));
		return 1;
	}
	return 0;
}

Related Functions

The following Functions might be useful, as they're related to this article in one way or another.

Personal tools