From SA-MP Wiki
Jump to: navigation, search
Contents
- 1 General Pawn Error List
- 2 Error categories
- 2.1 Errors
- 2.2 Fatal errors
- 2.3 Warnings
- 3 Common Errors
- 3.1 001: expected token
- 3.2 002: only a single statement (or expression) can follow each “case”
- 3.3 004: function «x» is not implemented
- 3.4 025: function heading differs from prototype
- 3.5 035: argument type mismatch (argument x)
- 3.6 036: empty statement
- 3.7 046: unknown array size (variable x)
- 3.8 047: array sizes do not match, or destination array is too small
- 3.9 055: start of function body without function header
- 4 Common Fatal Errors
- 4.1 100: cannot read from file: «<file>»
- 5 Common Warnings
- 5.1 202: number of arguments does not match definition
- 5.2 203: symbol is never used: «symbol»
- 5.3 204: symbol is assigned a value that is never used: «symbol»
- 5.4 209: function should return a value
- 5.5 211: possibly unintended assignment
- 5.6 213: tag mismatch
- 5.7 217: loose indentation
- 5.8 219: local variable «foo» shadows a variable at a preceding level
- 5.9 225: unreachable code
- 5.10 235: public function lacks forward declaration (symbol «symbol»)
- 6 External Links
General Pawn Error List
This pages contains the most common errors and warnings produced by the pawn compiler when creating SA:MP scripts.
When the compiler finds an error in a file, it outputs a message giving, in this order:
- the name of the file
- the line number were the compiler detected the error between parentheses, directly behind the filename
- the error class (error, fatal error or warning)
- an error number
- a descriptive error message
For example:
hello.pwn(3) : error 001: expected token: ";", but found "{"
Note: The error may be on the line ABOVE the line that is shown, since the compiler cannot always establish an error before having analyzed the complete expression.
Error categories
Errors are separated into three classes:
Errors
- Describe situations where the compiler is unable to generate appropriate code.
- Errors messages are numbered from 1 to 99.
Fatal errors
- Fatal errors describe errors from which the compiler cannot recover.
- Parsing is aborted.
- Fatal error messages are numbered from 100 to 199.
Warnings
- Warnings are displayed for unintended compiler assumptions and common mistakes.
- Warning messages are numbered from 200 to 299.
Common Errors
001: expected token
A required token is missing.
Example:
error 001: expected token: ";", but found "return"
main() { print("test") // This line is missing a semi-colon. That is the token it is expecting. return 1; // The error states that it found "return", this is this line it is referring to, // as it is after the point at which the missing token (in this case the semi-colon) should be. }
002: only a single statement (or expression) can follow each “case”
Every case in a switch statement can hold exactly one statement.
To put multiple statements in a case, enclose these statements
between braces (which creates a compound statement).
Example:
error 002: only a single statement (or expression) can follow each "case"
main() { switch(x) { case 0: print("hello"); print("hello"); } return 1; }
The above code also produces other warnings/errors:
error 002: only a single statement (or expression) can follow each "case" warning 215: expression has no effect error 010: invalid function or declaration
Fixed:
main() { switch(x) { case 0: { print("hello"); print("hello"); } } return 1; }
004: function «x» is not implemented
Most often caused by a missing brace in the function above.
025: function heading differs from prototype
This usually happen when new sa-mp version comes with new addition of argument to a function, like OnPlayerGiveDamage from 0.3x to 0.3z. The scripter must add «bodypart» argument to OnPlayerGiveDamage callback on their script.
Caused by either the number of arguments or the argument name is different.
Example:
forward MyFunction(playerid); public MyFunction(player, vehicleid)
Fixed:
forward MyFunction(playerid, vehicleid); public MyFunction(playerid, vehicleid)
035: argument type mismatch (argument x)
An argument passed to a function is of the wrong ‘type’.
For example, passing a string where you should be passing an integer.
Example:
error 035: argument type mismatch (argument 1)
Kick("playerid"); // We are passing a STRING, we should be passing an INTEGER
Fixed:
Kick(playerid);
036: empty statement
Caused by a rogue semicolon (;), usually inadvertently placed behind an if-statement.
046: unknown array size (variable x)
For array assignment, the size of both arrays must be explicitly defined, also if they are passed as function arguments.
Example:
new string[];
string = "hello";
Fixed:
new string[6];
string = "hello";
047: array sizes do not match, or destination array is too small
For array assignment, the arrays on the left and the right side of the
assignment operator must have the same number of dimensions.
In addition:
- for multi-dimensional arrays, both arrays must have the same size;
- for single arrays with a single dimension, the array on the left side of the assignment operator must have a size that is equal or bigger than the one on the right side.
new destination[8]; new msg[] = "Hello World!"; destination = msg;
In the above code, we try to fit 12 characters in an array that can only support 8. By increasing the array size of the destination, we can solve this. Note that a string also requires a null terminator so the total length of «Hello World!» plus the null terminator is, in fact, 13.
new destination[13]; new msg[] = "Hello World!"; destination = msg;
055: start of function body without function header
This error usually indicates an erroneously placed semicolon at the end of the function header.
Common Fatal Errors
100: cannot read from file: «<file>»
The compiler cannot find, or read from, the specified file. Make sure that the file you are trying to include is in the proper directory (default: <server directory>pawnoinclude).
| Tip
|
Multiple copies of pawno can lead to this problem. If this is the case, don’t double click on a .pwn file to open it. Open your editor first, then open the file through the editor. |
Common Warnings
202: number of arguments does not match definition
The description of this warning is pretty self-explanatory. You’ve passed either too few or too many parameters to a function. This is usually an indication that the function is used incorrectly. Refer to the documentation to figure out the correct usage of the function.
This usually happen on GetPlayerHealth function with PAWNO function auto completion as it confuses with the NPC GetPlayerHealth function that only has ‘playerid’ argument.
Example:
GetPlayerHealth(playerid);
Fixed:
new Float:health; GetPlayerHealth(playerid, health);
203: symbol is never used: «symbol»
You have created a variable or a function, but you’re not using it. Delete the variable or function if you don’t intend to use it. This warning is relatively safe to ignore.
The stock keyword will prevent this warning from being shown, as variables/functions with the stock keyword are not compiled unless they are used.
stock SomeFunction() { // Blah } // There will be no warning if this function is never used
204: symbol is assigned a value that is never used: «symbol»
Similar to the previous warning. You created a variable and assigned it a value, but you’re not using that value anywhere. Use the variable, or delete it. This warning, too, is relatively safe to ignore.
209: function should return a value
You have created a function without a return value
SomeFunction() { // Blah }
but you used it to assign on variable or function argument,
new result = SomeFunction(); // expected value = 1
Fixed:
SomeFunction() { // Blah return 1; }
211: possibly unintended assignment
The assignment operator (=) was found in an if-statement, instead of the equality operator (==). If the assignment is intended, the expression must be wrapped in parentheses. Example:
if(vehicle = GetPlayerVehicleID(playerid)) // warning if(vehicle == GetPlayerVehicleID(playerid)) // no warning if((vehicle = GetPlayerVehicleID(playerid))) // no warning; the value returned by the function will be assigned to the variable and the expression is then evaluated.
213: tag mismatch
A tag mismatch occurs when:
- Assigning to a tagged variable a value that is untagged or that has a different tag
- The expressions on either side of a binary operator have different tags
- In a function call, passing an argument that is untagged or that has a different tag than what the function argument was defined with
- Indexing an array which requires a tagged index with no tag or a wrong tag name
Usually happen on a new variable created with missing tag on the required function such as Float:, Text3D:, Text:, etc. Example,
Bad:
new health; GetPlayerHealth(playerid, health);
Good:
new Float:health; GetPlayerHealth(playerid, health);
217: loose indentation
The compiler will issue this warning if the code indentation is ‘loose’, example:
Good:
if(condition) { action(); result(); }
Bad:
if(condition) { action(); result(); }
Indentation means to push (indent) text along from the left of the page (by pressing the TAB key). This is common practice in programming to make code easier to read.
This warning also exists to avoid dangling-else problem.
219: local variable «foo» shadows a variable at a preceding level
A local variable, i.e. a variable that is created within a function or callback, cannot have the same name as a global variable, an enum specifier, a function, or a variable declared higher up in the same function. The compiler cannot tell which variable you’re trying to alter.
It is customary to prefix global variables with ‘g’ (e.g. gTeam). However, global variables should be avoided where possible.
new team[MAX_PLAYERS]; // variable declared in the global scape function(playerid) { new team[MAX_PLAYERS]; // declared in the local scope, shadows the variable in the global scope, warning 219 team[playerid] = random(5); // which variable are we trying to update here? }
225: unreachable code
The indicated code will never run, because an instruction before (above) it causes a jump out of the function, out of a loop or elsewhere. Look for return, break, continue and goto instructions above the indicated line. Unreachable code can also be caused by an endless loop above the indicated line.
Example:
CMD:jetpack(playerid, params[]) { #pragma unused params if(IsPlayerAdmin(playerid)) { SetPlayerSpecialAction(playerid, SPECIAL_ACTION_USEJETPACK); return 1; // jumps out the command } else { SendClientMessage(playerid, -1, "You are not admin!"); return 1; // jumps out the command } SendClientMessage(playerid, -1, "You typed command /jp"); // this code is not reachable and will not run. }
Fixed:
CMD:jetpack(playerid, params[]) { #pragma unused params if(IsPlayerAdmin(playerid)) { SetPlayerSpecialAction(playerid, SPECIAL_ACTION_USEJETPACK); } else { SendClientMessage(playerid, -1, "You are not admin!"); } SendClientMessage(playerid, -1, "You typed command /jp"); // this code will run. return 1; // jumps out the command }
235: public function lacks forward declaration (symbol «symbol»)
Your public function is missing a forward declaration.
Bad:
public MyFunction() { // blah }
Good:
forward MyFunction(); public MyFunction() { // blah }
External Links
- pawn-lang.pdf
Список часто встречаемых ошибок в pawno
Данная тема содержет наиболее распространенные ошибки и предупреждения в pawno при создании скриптов sa-mp
Когда компилятор находит ошибку в файле, то выводится сообщение, в таком порядке:
- Имя файла
- номер строки компилятора были обнаружены ошибки в скобках, непосредственно за именем
- класс error (ошибка, фатальная ошибка или предупреждение)
- номер ошибки
- описание ошибки
Например:
hello.pwn(3) : error 001: expected token: ";", but found "{"
Примечание: эта ошибка может быть на линии, над линией, что показано, так как компилятор не всегда может установить ошибку перед проанализировав полное выражение.
Категории ошибок
Ошибки разделяются на три класса:
Ошибки (errors)
- Описание ситуации когда компилятор не может скомпилировать код
- Ошибки номеруются от 1 до 99
Критические ошибки (Fatal errors)
- Критические ошибки и описание, от которых компилятор не может восстановиться.
- Парсинг прерывается (нет отклика программы).
- Критические ошибки номеруются от 100 до 199.
Предупреждения ( Warings )
- Предупреждения указывают на возможную причину возникновения багов, вылетов.
- Предупреждения номеруются от 200 до 299.
Распространенные ошибки
001: expected token (ожидаемый знак)
Обязательный знак отсутствует
Пример:
error 001: expected token: ";", but found "return"
main()
{
print("test") // тут должна быть точка с запятой ";"
return 1;
}
002: only a single statement (or expression) can follow each “case” (только одно выражение может быть в одной строке с «case»
В каждом case оператора switch без фигурных скобок может содержаться только один оператор если больше нужно ставить скобки.
Пример:
error 002: only a single statement (or expression) can follow each "case"
main()
{
switch(x)
{
case 0: print("hello"); print("hello");
}
return 1;
}
Так же могут быть еще и предупреждения и дополнительные ошибки:
error 002: only a single statement (or expression) can follow each "case" warning 215: expression has no effect error 010: invalid function or declaration
Вот так это можно исправить:
main()
{
switch(x)
{
case 0:
{
print("hello");
print("hello");
}
}
return 1;
}
004: function «x» is not implemented (Функция «x» не используется
Часто бывает что в функции выше пропущена скобка.
025: function heading differs from prototype
Это проиходит когда в функции не совпадают аргументы.
К примеру:
forward MyFunction(playerid); public MyFunction(player, vehicleid);
Исправляем:
forward MyFunction(playerid, vehicleid); public MyFunction(playerid, vehicleid);
035: argument type mismatch (argument x) (не совпадение типов аргумента(ов)
К примеру когда в место playerid — integer аргумента стоит «playerid» — string или 0.5 — float
Пример:
error 035: argument type mismatch (argument 1)
Kick("playerid"); // Как видите в место целого числа (integer) стоит строка
Исправляем:
Kick(playerid);
046: unknown array size (variable x)
Не указан размер массива.
Пример:
new string[]; string = "pawno";
Исправляем:
new string[6]; string = "pawno";
047: array sizes do not match, or destination array is too small
Размер массива мал или не совпадает.
- Многомерные массивы должны иметь одинаковый размер
- Одномерные массив к которому присваивают(правый должен иметь больше размер чем левый.
new destination[8]; new msg[] = "Hello World!"; destination = msg;
В приведенном выше коде размер строки «Hello world!» ровна 12 байт а массив к которому присваиваем имеет размер 8 байт из этого и складывается ошибка.
Если увеличить размер массива destination до 13 байт то ошибка исправится.
new destination[13]; new msg[] = "Hello World!"; destination = msg;
055: start of function body without function header
Начало тела функции без функции заголовка.
Критические ошибки (FATAL ERRORS)
100: cannot read from file: "<file>"
Компилятор не может найти или прочитать указанный файл, убедитесь что он находится по адресу (<папка с сервером>pawnoinclude).
Пример:
#include <a_sam>
Исправляем:
#include <a_samp>
Совет
Не нужно открывать ваш код дважды, не нужно тыкать несколько раз на файл. Откройте сначала редактор, потом ваш проект.
Предупреждения( Warnings )
202: number of arguments does not match definition
Описание ошибки довольно понятное, это значит что вы используете слишком мало или слишком много аргументов в функции, обычно это признак того что функция используется не правильно, обратитесь к документации.
Функция GetPlayerHealth согласно официальному источнику wiki.sa-mp.com имеет два аргумента playerid и Float:health ссылка
Пример:
GetPlayerHealth(playerid);
Исправляем:
new Float:health; GetPlayerHealth(playerid, health);
203: symbol is never used: «symbol»
Вы создали переменную или функцию и она ни где не используется тогда ищите в окне компилятора это предупреждение, это не как не влияет на код и не угражает ему, так что если вы удалите переменную или функцию которая не используется, то вы сэкономите память.
Пример:
stock SomeFunction()
{
// Blah
}
204: symbol is assigned a value that is never used: «symbol»
Это предупреждение аналогично к предыдущему, разница в том что к переменной что то присвоено и оно не как не используется, это безопасно 
209: function should return a value
Функция ничего не возвращает, вы создали её:
SomeFunction()
{
// Blah
}
Решили её присвоить к чему нибудь к примеру:
new result = SomeFunction(); // ожидает 1
Вот так исправить
SomeFunction()
{
// Blah
return 1;
}
211: possibly unintended assignment
Если вы введете оператор присваивания в условии и оно не будет в круглых скобках то будет предупреждение
if(vehicle = GetPlayerVehicleID(playerid)) // ошибка
if(vehicle == GetPlayerVehicleID(playerid)) // все норм
if((vehicle = GetPlayerVehicleID(playerid))) // все норм, так значение функции присвоится к переменной потом выражение вычесляется { то есть это как if(IsPlayerConnected(playerid)}
213: tag mismatch ( несовпадение тегов)
Это происходит когда:
- Тип переменной указан не верно или не имеет его
- Выражения по обе стороны бинарного оператора имеют разные теги
- В пременную возвращен не верный тип переменной или не имеющий его.
- Индексирование массива, который требует тегами индекс без тега или неправильное имя тега
Часто это бывает на 3d текстах или тексдравах Text3D, Text
Не правильно:
new health; GetPlayerHealth(playerid, health);
Правильно:
new Float:health; GetPlayerHealth(playerid, health);
217: loose indentation
Компилятор выдаст ошибку если не соблюдены отступы.
Правильно:
if(condition)
{
action();
result();
}
Не правильно:
if(condition)
{
action();
result();
}
Отступы делаются по нажатью кнопки TAB это практика в программировании для удобного чтения кода.
219: local variable «foo» shadows a variable at a preceding level
Локальная переменная в тени глобальной то есть над локальной переменной создана точно такая же глобальная. В практике программирования префиксом глобальной переменной является «g» в начале переменной к примеру
new gPlayerMoney
любыми способами избегайте их.
К примеру:
new team[MAX_PLAYERS]; // объявляем глобальную переменную
function(playerid)
{
new team[MAX_PLAYERS]; // создаем еще одну, и получаем статью 219 кодекса ошибок :D
team[playerid] = random(5);
}
Решение:
Просто переименуйте локальную переменную team.
225: unreachable code ( недоступный код )
Это происходит тогда когда вы пишите какой нибудь код после return, после return’а код не выполняется и он считается бесполезным
Пример:
#include <zcmd.inc>
CMD:jetpack(playerid, params[])
{
#pragma unused params
if(IsPlayerAdmin(playerid))
{
SetPlayerSpecialAction(playerid, SPECIAL_ACTION_USEJETPACK);
return 1; // завершаем процесс
}
else
{
SendClientMessage(playerid, -1, "Вы не администратор");
return 1; // завершаем процесс
}
SendClientMessage(playerid, -1, "Вы ввели команду /jp"); // Этот код не доступен он не будет выполнятся.
}
Решение:
CMD:jetpack(playerid, params[])
{
#pragma unused params
if(IsPlayerAdmin(playerid))
{
SetPlayerSpecialAction(playerid, SPECIAL_ACTION_USEJETPACK);
}
else
{
SendClientMessage(playerid, -1, "Вы не администратор");
}
SendClientMessage(playerid, -1, "Вы ввели команду /jp"); // этот код запустится
return 1; // завершаем процесс
}
235: public function lacks forward declaration (symbol «symbol»)
Отсутствует forward.
Не правильно:
public MyFunction()
{
}
Правильно:
forward MyFunction();
public MyFunction()
{
}
Надеюсь эта статья поможет вам в языке программирования, желаю вам не повторять ошибок дважды и что бы ваш код был быстрым, надежным!
Оставляйте ваши отзывы, ставьте плюсы, пишите недостатки ошибки, недостатки статьи или их недочеты. Удачи в мире PAWNO!
@maldex Вот:
Цитата
case NARAD1: { if(!response) return 1; if (PlayerInfo[playerid][pWork] == 0) // В этой строке ошибка { PlayerInfo[playerid][pWork] = 1; SetPlayerSkin(playerid,16); SendClientMessage(playerid,COLOR_WHITE,"Ïîçäðàâëÿåì. Òåïåðü èäèòå íà {0bda51}÷åêïîèíò{FFFFFF}, ÷òîáû ñðóáèòü äåðåâî."); SetPlayerCheckpoint(playerid,-744.4242,-151.5473,66.944,1.0); SetPlayerAttachedObject(playerid,0,341,6); } else if(PlayerInfo[playerid][pWork] == 1) { PlayerInfo[playerid][pWork] = 0; SetPlayerSkin(playerid, PlayerInfo[playerid][pChar]); PlayerInfo[playerid][pMoney] += AllPlayerDrova[playerid]*3; format(string, sizeof(string), "Âû çàêîí÷èëè ðàáîòó. Âàø çàðàáîòîê: {00FF00}$%d", AllPlayerDrova[playerid]*3); SendClientMessage(playerid, -1, string); format(string, sizeof(string), "~b~+%d", AllPlayerDrova[playerid]*3); GameTextForPlayer(playerid, string, 3000, 1); if(IsPlayerAttachedObjectSlotUsed(playerid,0)) RemovePlayerAttachedObject(playerid,0); if(IsPlayerAttachedObjectSlotUsed(playerid,1)) RemovePlayerAttachedObject(playerid,1); if(IsPlayerAttachedObjectSlotUsed(playerid,2)) RemovePlayerAttachedObject(playerid,2); DisablePlayerCheckpoint(playerid); AllPlayerDrova[playerid] = 0; SetPlayerSpecialAction(playerid, 0); return true; }
Ошибка: error 001: expected token: «;», but found «бла-бла»
Решение: Идём на строку выше той, что указана в ошибке и ставим в конце ; (точку с запятой).
Ошибка: error 021: symbol already defined: «бла-бла» или warning 219: local variable «бла-бла» shadows a variable at a preceding level
Решение: Ошибка появляется, если вы несколько раз создали одну и ту же переменную,stock,public.Для решения вам просто требуется удалить дубликат.
Ошибка: error 024: «break» or «continue» is out of context
Решение: break,continue используется только в цикле (for), данная ошибка появляется, если вы использовали их не в цикле. Для решения вам нужно просто заменить их.
Ошибка: error 032: array index out of bounds (variable «cartek»)
Решение: Ошибка появляется, если у вас превышен индекс массива. Для решение вам просто надо увеличить ‘число’ в создании массива.
Ошибка: error 040: duplicate «case» label (value %d)
Решение: Ошибка появляется, если вы два раза используете case с одним и тем же параметром.
Ошибка: fatal error 100: cannot read from file: «бла-бла»
Решение: Ошибка появляется, если вы подключили инклуд и не добавили в папку pawno/include. Для решения вам просто надо добавить в папку данный инклуд.
Ошибка: warning 203: symbol is never used: «бла-бла»
Решение: Ошибка появляется, если созданная переменная нигде не используется. Для решения вам просто требуются ещё удалить.
Ошибка: warning 209: function «бла-бла» should return a value
Решение: Для решения проблемы в данной функции/команде вам следует добавить в конец return true/return false.
Ошибка: warning 217: loose indentation
Решение: Для решения проблемы выровняйте строки.
Ошибка: warning 235: public function lacks forward declaration (symbol «бла-бла»)
Решение: Ошибка появляется, если вы создали public,а forward нет. Для решения вам просто надо создать forward к public’y.
По мере возможности тема будет дополняться
Содержание
- Errors List
- From SA-MP Wiki
- Contents
- General Pawn Error List
- Error categories
- Errors
- Fatal errors
- Warnings
- Common Errors
- 001: expected token
- 002: only a single statement (or expression) can follow each “case”
- 004: function «x» is not implemented
- 025: function heading differs from prototype
- 035: argument type mismatch (argument x)
- 036: empty statement
- 046: unknown array size (variable x)
- 047: array sizes do not match, or destination array is too small
- 055: start of function body without function header
- Common Fatal Errors
- 100: cannot read from file: » «
- Common Warnings
- 202: number of arguments does not match definition
- 203: symbol is never used: «symbol»
- 204: symbol is assigned a value that is never used: «symbol»
- 209: function should return a value
- 211: possibly unintended assignment
- 213: tag mismatch
- 217: loose indentation
- 219: local variable «foo» shadows a variable at a preceding level
- 225: unreachable code
- 235: public function lacks forward declaration (symbol «symbol»)
- Error 001 expected token but found return
- Вопросы
- Error 001 expected token but found return
- Поделиться сообщением
- 7 ответов на этот вопрос
- Последние посетители 0 пользователей онлайн
- Похожий контент
- Исправляем ошибки/предупреждения
- Batka1337
- Форум Pawn.Wiki — Воплоти мечту в реальность!: error 001: expected token: «;», but found «return» — Форум Pawn.Wiki — Воплоти мечту в реальность!
Errors List
From SA-MP Wiki
Contents
General Pawn Error List
This pages contains the most common errors and warnings produced by the pawn compiler when creating SA:MP scripts.
When the compiler finds an error in a file, it outputs a message giving, in this order:
- the name of the file
- the line number were the compiler detected the error between parentheses, directly behind the filename
- the error class (error, fatal error or warning)
- an error number
- a descriptive error message
Note: The error may be on the line ABOVE the line that is shown, since the compiler cannot always establish an error before having analyzed the complete expression.
Error categories
Errors are separated into three classes:
Errors
- Describe situations where the compiler is unable to generate appropriate code.
- Errors messages are numbered from 1 to 99.
Fatal errors
- Fatal errors describe errors from which the compiler cannot recover.
- Parsing is aborted.
- Fatal error messages are numbered from 100 to 199.
Warnings
- Warnings are displayed for unintended compiler assumptions and common mistakes.
- Warning messages are numbered from 200 to 299.
Common Errors
001: expected token
A required token is missing.
002: only a single statement (or expression) can follow each “case”
Every case in a switch statement can hold exactly one statement.
To put multiple statements in a case, enclose these statements
between braces (which creates a compound statement).
The above code also produces other warnings/errors:
004: function «x» is not implemented
Most often caused by a missing brace in the function above.
025: function heading differs from prototype
This usually happen when new sa-mp version comes with new addition of argument to a function, like OnPlayerGiveDamage from 0.3x to 0.3z. The scripter must add «bodypart» argument to OnPlayerGiveDamage callback on their script.
Caused by either the number of arguments or the argument name is different.
035: argument type mismatch (argument x)
An argument passed to a function is of the wrong ‘type’. For example, passing a string where you should be passing an integer.
036: empty statement
Caused by a rogue semicolon ( ; ), usually inadvertently placed behind an if-statement.
046: unknown array size (variable x)
For array assignment, the size of both arrays must be explicitly defined, also if they are passed as function arguments.
047: array sizes do not match, or destination array is too small
For array assignment, the arrays on the left and the right side of the assignment operator must have the same number of dimensions. In addition:
- for multi-dimensional arrays, both arrays must have the same size;
- for single arrays with a single dimension, the array on the left side of the assignment operator must have a size that is equal or bigger than the one on the right side.
In the above code, we try to fit 12 characters in an array that can only support 8. By increasing the array size of the destination, we can solve this. Note that a string also requires a null terminator so the total length of «Hello World!» plus the null terminator is, in fact, 13.
055: start of function body without function header
This error usually indicates an erroneously placed semicolon at the end of the function header.
Common Fatal Errors
100: cannot read from file: » «
The compiler cannot find, or read from, the specified file. Make sure that the file you are trying to include is in the proper directory (default: pawnoinclude).
Multiple copies of pawno can lead to this problem. If this is the case, don’t double click on a .pwn file to open it. Open your editor first, then open the file through the editor.
Common Warnings
202: number of arguments does not match definition
The description of this warning is pretty self-explanatory. You’ve passed either too few or too many parameters to a function. This is usually an indication that the function is used incorrectly. Refer to the documentation to figure out the correct usage of the function.
This usually happen on GetPlayerHealth function with PAWNO function auto completion as it confuses with the NPC GetPlayerHealth function that only has ‘playerid’ argument.
203: symbol is never used: «symbol»
You have created a variable or a function, but you’re not using it. Delete the variable or function if you don’t intend to use it. This warning is relatively safe to ignore.
The stock keyword will prevent this warning from being shown, as variables/functions with the stock keyword are not compiled unless they are used.
204: symbol is assigned a value that is never used: «symbol»
Similar to the previous warning. You created a variable and assigned it a value, but you’re not using that value anywhere. Use the variable, or delete it. This warning, too, is relatively safe to ignore.
209: function should return a value
You have created a function without a return value
but you used it to assign on variable or function argument,
211: possibly unintended assignment
The assignment operator (=) was found in an if-statement, instead of the equality operator (==). If the assignment is intended, the expression must be wrapped in parentheses. Example:
213: tag mismatch
A tag mismatch occurs when:
- Assigning to a tagged variable a value that is untagged or that has a different tag
- The expressions on either side of a binary operator have different tags
- In a function call, passing an argument that is untagged or that has a different tag than what the function argument was defined with
- Indexing an array which requires a tagged index with no tag or a wrong tag name
Usually happen on a new variable created with missing tag on the required function such as Float:, Text3D:, Text:, etc. Example,
217: loose indentation
The compiler will issue this warning if the code indentation is ‘loose’, example:
Indentation means to push (indent) text along from the left of the page (by pressing the TAB key). This is common practice in programming to make code easier to read. This warning also exists to avoid dangling-else problem.
219: local variable «foo» shadows a variable at a preceding level
A local variable, i.e. a variable that is created within a function or callback, cannot have the same name as a global variable, an enum specifier, a function, or a variable declared higher up in the same function. The compiler cannot tell which variable you’re trying to alter.
It is customary to prefix global variables with ‘g’ (e.g. gTeam). However, global variables should be avoided where possible.
225: unreachable code
The indicated code will never run, because an instruction before (above) it causes a jump out of the function, out of a loop or elsewhere. Look for return, break, continue and goto instructions above the indicated line. Unreachable code can also be caused by an endless loop above the indicated line.
235: public function lacks forward declaration (symbol «symbol»)
Your public function is missing a forward declaration.
Источник
Error 001 expected token but found return
Вопрос от RASTAMAN , 3 сентября, 2017
Вопросы
- VIP Сообщений: 883
Регистрация: 28.07.2017
КПД: 73%
Ошибка: error 001: expected token: «;», but found «]»(пример)
Решение: Идём на строку выше той, что указана в ошибке и ставим в конце: ;
Ошибка: error 021: symbol already defined: «понятно в общем» или warning 219: local variable «тоже» shadows a variable at a preceding level
Решение: Ошибка появляется, если вы несколько раз создали одну и ту же переменную, stock, public.Для решения вам просто требуется удалить дубликат.
Ошибка: error 024: «break» or «continue» is out of context
Решение: break, continue используется только в цикле (for), данная ошибка появляется, если вы использовали их не в цикле. Для решения вам нужно заменить их.
Ошибка: error 032: array index out of bounds (variable «cartek»)
Решение: Ошибка появляется, если у вас превышен индекс массива. Для решения вам просто надо увеличить число в создании массива.
Ошибка: error 040: duplicate «case» label (value %d)
Решение: Ошибка появляется, если вы два раза используете case с одним и тем же параметром.
Ошибка: fatal error 100: cannot read from file: «понятно»
Решение: Ошибка появляется, если вы подключили инклуд и не добавили в папку pawno/include. Для решения вам просто надо добавить в папку данный инклуд.
Ошибка: warning 203: symbol is never used: «гы»
Решение: Ошибка появляется, если созданная переменная нигде не используется. Для решения вам просто требуются ещё удалить.
Ошибка: warning 209: function «ясно» should return a value
Решение: Для решения проблемы в данной функции/команде вам следует добавить в конец return true/return false.
Ошибка: warning 217: loose indentation
Решение: Для решения проблемы выровняйте строки.
Ошибка: warning 235: public function lacks forward declaration (symbol «ясно»)
Решение: Ошибка появляется, если вы создали public,а forward нет. Для решения вам просто надо создать forward к public’y.
Ошибка: fatal error 107: too many error messages on one line
Решение: Исправьте ошибки, которые даны выше, в частности в 1 строке. Именно поэтому выходит такая ошибка.
Ошибка: fatal error 100: cannot read from file: «%s»
Решение: Возможно вы удалили какую-то строку/файл, которую нужно добавить и проблема будет решена, вместо %s вам будет дана это строка/файл. Насколько я помню
Автор: Transcend
Тему можно дополнять!
Источник
Error 001 expected token but found return
- Активный Сообщений: 207
Регистрация: 05.11.2017
КПД: 9%
Добрый день помогите исправить ошибки !
Вот что я добавлял перед этими ошибкам.
А именно ругается вот на эту строчку.
Поделиться сообщением
Ссылка на сообщение
Опубликовал DENIS.P. ,Опубликовано 4 января, 2018
7 ответов на этот вопрос
Последние посетители 0 пользователей онлайн
Ни одного зарегистрированного пользователя не просматривает данную страницу
Похожий контент
Работает на IPS Community Suite 4
2017 — н.в. PAWNO-RUS.RU
При копировании материалов с сайта ссылка на наш форум обязательна!
Вы видите это сообщение, так как вы не вошли или не зарегистрировались. Чтобы получить более расширенные возможности войдите или зарегистрируйтесь.
Однако без регистрации Вы также сможете пользоваться форумом.
Источник
Исправляем ошибки/предупреждения
Batka1337
Хацкер-программист
Ошибка: error 001: expected token: «;», but found «бла-бла»
Решение: Идём на строку выше той, что указана в ошибке и ставим в конце ; (точку с запятой).
Ошибка: error 021: symbol already defined: «бла-бла» или warning 219: local variable «бла-бла» shadows a variable at a preceding level
Решение: Ошибка появляется, если вы несколько раз создали одну и ту же переменную,stock,public.Для решения вам просто требуется удалить дубликат.
Ошибка: error 024: «break» or «continue» is out of context
Решение: break,continue используется только в цикле (for), данная ошибка появляется, если вы использовали их не в цикле. Для решения вам нужно просто заменить их.
Ошибка: error 032: array index out of bounds (variable «cartek»)
Решение: Ошибка появляется, если у вас превышен индекс массива. Для решение вам просто надо увеличить ‘число’ в создании массива.
Ошибка: error 040: duplicate «case» label (value %d)
Решение: Ошибка появляется, если вы два раза используете case с одним и тем же параметром.
Ошибка: fatal error 100: cannot read from file: «бла-бла»
Решение: Ошибка появляется, если вы подключили инклуд и не добавили в папку pawno/include. Для решения вам просто надо добавить в папку данный инклуд.
Ошибка: warning 203: symbol is never used: «бла-бла»
Решение: Ошибка появляется, если созданная переменная нигде не используется. Для решения вам просто требуются ещё удалить.
Ошибка: warning 209: function «бла-бла» should return a value
Решение: Для решения проблемы в данной функции/команде вам следует добавить в конец return true/return false.
Ошибка: warning 217: loose indentation
Решение: Для решения проблемы выровняйте строки.
Ошибка: warning 235: public function lacks forward declaration (symbol «бла-бла»)
Решение: Ошибка появляется, если вы создали public,а forward нет. Для решения вам просто надо создать forward к public’y.
По мере возможности тема будет дополняться
Источник
Форум Pawn.Wiki — Воплоти мечту в реальность!: error 001: expected token: «;», but found «return» — Форум Pawn.Wiki — Воплоти мечту в реальность!
- Pawn скриптинг
- Первая помощь
- Проблемы с компилированием
- Правила форума
- Просмотр новых публикаций
- Группа: Пользователи
- Сообщений: 4
- Регистрация: 10 апреля 16
Я так понимаю 215 строка нужна
Сообщение отредактировал Sound: 13 апреля 2016 — 21:41
Причина редактирования: Тема закрыта. Ответ был дан
- Группа: Администраторы
- Сообщений: 7 298
- Регистрация: 14 августа 11
Точку с запятой забыл:
- Группа: Активные пользователи
- Сообщений: 398
- Регистрация: 24 ноября 14
- Группа: Vip
- Сообщений: 1 570
- Регистрация: 18 февраля 15
- Группа: Vip
- Сообщений: 1 165
- Регистрация: 19 июля 15

1. Ты не используешь макрос, а он, как не странно, может изменится с выходом новой версии (если она будет, вообще). И да, функция Kick сама проверяет наличие игрока на сервере.
2. Вроде бы в компиляторе не от Zeex’а будет ошибка, зависание и т.п..
P.S.: Бесполезно использовать ASM, если ты не работаешь напрямую с памятью.
Сообщение отредактировал VVWVV: 10 апреля 2016 — 20:33
- Группа: Vip
- Сообщений: 1 570
- Регистрация: 18 февраля 15
Боже, перестань, я же в «шутку» ответил на предыдущий пост, конечно такой способ использовать бессмыслено, когда можно просто на прямую вызвать функцию кика. Любишь же ты придратся)
На счет адреса за место макроса — это просто выебоны
UPD:
Сообщение отредактировал Sound: 10 апреля 2016 — 22:21
- Группа: Vip
- Сообщений: 1 165
- Регистрация: 19 июля 15

Боже, перестань, я же в «шутку» ответил на предыдущий пост, конечно такой способ использовать бессмыслено, когда можно просто на прямую вызвать функцию кика. Любишь же ты придратся)
На счет адреса за место макроса — это просто выебоны
UPD:
Вызывает, но если использовать вызов этой функции ранее, чем вызов ее через опкод sysreq, то зависания не будет.
Ты заявил о том, что мой стиль кода не очень, в инклуде so_func, когда я сделал проверку на компилятор от Zeex’a, хотя это и называется обходом зависания
Источник
| Author |
Message |
|||
|
Junior Member |
|
|||
|
|
![]() |
||||
|
Veteran Member |
|
|||
|
|
|
![]() |
||||
|
Junior Member |
|
|||
|
|
![]() |
||||
|
Veteran Member |
|
|||
|
|
![]() |
||||
|
Senior Member |
|
|||
|
|
![]() |
||||
|
Junior Member |
|
|||
|
|
- Регистрация
- 21 Май 2016
- Сообщения
- 19
- Лучшие ответы
- 0
- Репутация
- 4
- Возраст
- 23
-
#1
ошибочки вылетают(
C:UsersAdminDesktopMagnetgamemodesmagnet.pwn(4109) : error 001: expected token: «*then», but found «;»
C:UsersAdminDesktopMagnetgamemodesmagnet.pwn(4109) : error 036: empty statement
C:UsersAdminDesktopMagnetgamemodesmagnet.pwn(4112) : error 035: argument type mismatch (argument 2)
C:UsersAdminDesktopMagnetgamemodesmagnet.pwn(4113) : error 076: syntax error in the expression, or invalid function call
4 Errors.
JavaScript:
case 22837:
{
if AhelpNom[playerid]++;
else AhelpNom[playerid]--;
if(AhelpNom[playerid] < 1 || AhelpNom[playerid] > 6) return 1;
SCM(144,"Админ команды %i уровня", AhelpNom[playerid]);
SPD(playerid, 22837, DIALOG_STYLE_MSGBOX, SCM, AHelpik[AhelpNom[playerid]], "Далее", "Назад");
return 1;
}
Как исправить Error
Автор: neka
Значение Error можно посмотреть здесь.
error 040: duplicate «case» label (value 28)
Это означает что case стаким значением повторяется. Решение этой проблемы простое — нам нужно цифру 28 изменит на другую (в той строчке на которую жалуется )
error 032: array index out of bounds (variable «JoinPed»)
Это означает что индекс массива превышен (но не всегда, смотрим дальше) Пример:
131 — массив поигравшись с ним я понял что дело не в нем, а в чём же спросите вы? Пример данной ошибки:
Код: Выделить всё
else if(SelectCharPlace[playerid] == 2) { SetPlayerSkin(playerid, JoinPed[123][0]); SelectCharPlace[playerid] = 3; InviteSkin[playerid] = JoinPed[98][0]; }
как видим — JoinPed[123] сначало с таким значением, а потом JoinPed[98]. Решение простое: JoinPed[123] число в данных скобках должно быть одинаковым. Пример:
Код: Выделить всё
else if(SelectCharPlace[playerid] == 2) { SetPlayerSkin(playerid, JoinPed[123][0]); SelectCharPlace[playerid] = 3; InviteSkin[playerid] = JoinPed[123][0]; }
error 037: invalid string (possibly non-terminated string)
Это означает что строка неправильная, а точнее где то допущена ошибка:
Код: Выделить всё
else if(PlayerInfo[targetid][pRank] == 4) { rangz = "Зам.модера; }
как видим нам после слова «модера» не хватает «. Правим:
Код: Выделить всё
else if(PlayerInfo[targetid][pRank] == 4) { rangz = "Зам.модера"; }
error 001: expected token: «,», but found «;»
Это значит что мы пропустили знак или скобку (в данном примере скобку) Пример:
Код: Выделить всё
public SaveProdykts()
{
new idx;
new File: file2;
while (idx < sizeof(ProdyktsInfo))
{
new coordsstring[256];
format(coordsstring, sizeof(coordsstring), "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%dn",
ProdyktsInfo[idx][prSous],
ProdyktsInfo[idx][prPizza],
ProdyktsInfo[idx][prMilk],
ProdyktsInfo[idx][prJuice],
ProdyktsInfo[idx][prSpirt],
ProdyktsInfo[idx][prChicken],
ProdyktsInfo[idx][prKolbasa],
ProdyktsInfo[idx][prFish],
ProdyktsInfo[idx][prIceCream],
ProdyktsInfo[idx][prChips],
ProdyktsInfo[idx][prZamProd];
if(idx == 0)
{
file2 = fopen("[prodykts]/prodykts.cfg", io_write);
}
else
{
file2 = fopen("[prodykts]/prodykts.cfg", io_append);
}
fwrite(file2, coordsstring);
idx++;
fclose(file2);
}
return 1;
}
смотрим на:
и вим что мы ппропустили )
Правим:
И в итоге:
Код: Выделить всё
public SaveProdykts()
{
new idx;
new File: file2;
while (idx < sizeof(ProdyktsInfo))
{
new coordsstring[256];
format(coordsstring, sizeof(coordsstring), "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%dn",
ProdyktsInfo[idx][prSous],
ProdyktsInfo[idx][prPizza],
ProdyktsInfo[idx][prMilk],
ProdyktsInfo[idx][prJuice],
ProdyktsInfo[idx][prSpirt],
ProdyktsInfo[idx][prChicken],
ProdyktsInfo[idx][prKolbasa],
ProdyktsInfo[idx][prFish],
ProdyktsInfo[idx][prIceCream],
ProdyktsInfo[idx][prChips],
ProdyktsInfo[idx][prZamProd]);< ----------- И вот наша скобка
if(idx == 0)
{
file2 = fopen("[prodykts]/prodykts.cfg", io_write);
}
else
{
file2 = fopen("[prodykts]/prodykts.cfg", io_append);
}
fwrite(file2, coordsstring);
idx++;
fclose(file2);
}
return 1;
}
error 002: only a single statement (or expression) can follow each «case»
Это означает что у вас после «case» идет if(dialogid == ). Пример:
Код: Выделить всё
case 7507:
{
if(response) ClothesSex[playerid] = 1;
else ClothesSex[playerid] = 2;
ShowPlayerDialog(playerid,7504,2,"??????? ??????","{A0B0D0}?????????? ?????? {7CC000}300$n{A0B0D0}??????? ?????? {7CC000}300$n{A0B0D0}???????????? ?????? {7CC000}300$n{A0B0D0}?????","???????","?????");
return 1;
}
if(dialogid == 7504) <------------------- вот наша и ошибка
{
if(response)
{
SetCameraBehindPlayer(playerid); TogglePlayerControllable(playerid, 1);
SetPlayerSkin(playerid, PlayerInfo[playerid][pModel]);
ClothesRun[playerid] = 0;
return 1;
}
Решение простое: if(dialogid == 7504) это нам нужно заменить на case как и последующий диалог !
Код: Выделить всё
case 7504: <------------------- вот так это выглядит
{
if(response)
{
SetCameraBehindPlayer(playerid); TogglePlayerControllable(playerid, 1);
SetPlayerSkin(playerid, PlayerInfo[playerid][pModel]);
ClothesRun[playerid] = 0;
return 1;
}
error 004: function «%s» is not implemented
Это означает что мы пропустили скобку. Мой совет:
- проверить весь код в ручную
- на форуме был урок как найти не по ставленую скобку
- Можно воспользоватся notepad++ там показы линии открытых скобок и тогда можно найти эту скобку
error 017: undefined symbol %s
Это означает что мы не поставили переменную new. Пример:
Решение — ко всем new добавим:
На чтение 2 мин. Просмотров 113 Опубликовано 15.12.2019
Самые известные баги стандартного компилятора «Pawno» и их исправление.
return «Some string»;
Проблема
Возвращая строки напрямую компилятор падает ( краш ).
Решение
Создайте для вашей строки массив, далее возвратите её ( не рекомендуется возвращать большие строки ).
static const
some_text[] = «Some String»;
string = (a == 5) ? «это пять» : «это не пять»;
Проблема
Строки конкатенируются (объединяются, соединяются) компилятором в одну, например это будет скомпилировано в одну строку «Hello World»:
string = «Hello» » » «World»;
Однако компилятор на засчитывает «:» как часть тернарного оператора и компилятор засчитывает это за ошибку скриптера. Обычно в таких случаях ( а обычно это так и есть ) появляется вот такая ошибка:
errors.pwn(11) : error 001: expected token: «-string end-«, but found «-identifier-»
Pawn compiler 3.2.3664 Copyright (c) 1997-2006, ITB CompuPhase
1 Error.
Решение
Чтобы это исправить, просто заключите строки в круглые скобки, хочу заметить, что на работоспособность кода это никак не влияет.
string = (a == 5) ? («это пять») : («это не пять»);
new
gGlobalVariable = SomeFunction();
Проблема
Вызывая функцию для инициализации глобальной переменной компилятор падает ( краш ).
Решение
Вызовите функцию для инициализации переменной в «OnGameModeInit», «OnFilterScriptInit», или «main»:
public OnGameModeInit()
<
gGlobalVariable = SomeFunction();
// некоторый код
>
Проблема
Максимальная длина строки в компиляторе 512 символов ( считая с завершающим символом ‘’ ).
Решение
Сократить текст со строкой. Обычно люди делают это так:
format(str, sizeof(str),
«Очень длинная строка»,
other,
parameters);
Это разделяет вызов функции на 4 строки, делая её короче. Однако это решение далеко не хорошее. Даже иногда может откуда не возьмись возникнуть падения компилятора ( краш ).
stock SomeFunction()
<
#if defined main
gVar = (gVar ? 0 : 1);
#endif
main()
<
return SomeFunction() ? 0 : 1;
>
Проблема
Данный код будет генерироваться следующим образом: Сначала сгенерируется код в функции ( SomeFunction ), далее сгенерируется код в main (изначально компилятор «не знает», что «main» инициализируется позже). В результате, по неизвестной причине, любые другие тернарные операторы в вашем скрипте неверно сгенерируются и это приведёт к падению компилятора ( краш ).
Решение
Не используйте тернарный оператор для проверки на существование функции если функция ещё не определена или будет определена позже.
Автор урока: Y_Less
Перевод и дополнение: Londlem (http://pro-pawn.ru/member.php?2057-Londlem)
Оригинал: http://forum.sa-mp.com/showthread.php?t=355877 (http://forum.sa-mp.com/showthread.php?t=355877)
Специально для: Pro-Pawn.Ru (http://pro-pawn.ru)
Копирование данной статьи без разрешения автора запрещено!









