Difference between revisions of "Ru:Introduction to SourcePawn"

From AlliedModders Wiki
Jump to: navigation, search
Line 24: Line 24:
 
*Числовые (могут содержать только произвольные числовые данные), как показано выше.
 
*Числовые (могут содержать только произвольные числовые данные), как показано выше.
 
*Строковые (могут содержать целый ряд текстовых символов)
 
*Строковые (могут содержать целый ряд текстовых символов)
 +
 +
==Functions==
 +
The next important concept is '''functions'''. Functions are symbols or names that perform an action.  That means when you activate them, they carry out a specific sequence of code.  There are a few types of functions, but every function is activated the same way.  "Calling a function" is the term for invoking a function's action.  Function calls are constructed like this:
 +
<pawn>function(<parameters>)</pawn>
 +
 +
Examples:
 +
 +
<pawn>show(56);  //Activates "show" function, and gives the number 56 to it
 +
show();    //Activates "show" function with no data, blank
 +
show(a);    //Activates "show" function, gives a variable's contents as data
 +
</pawn>
 +
 +
Every piece of data passed to a function is called a '''parameter'''.  A function can have any number of parameters (there is a "reasonable" limit of 32 in SourceMod).  Parameters will be explained further in the article.
 +
 +
==Comments==
 +
Note any text that appears after a "//" is considered a "comment" and is not actual code.  There are two comment styles:
 +
*<tt>//</tt> - Double slash, everything following on that line is ignored.
 +
*<tt>/* */</tt> - Multi-line comment, everything in between the asterisks is ignored.  You cannot nest these.
 +
 +
 +
==Block Coding==
 +
The next concept is block coding. You can group code into "blocks" separated by { and }. This effectively makes one large block of code act as one statement. For example:
 +
 +
<pawn>{
 +
  here;
 +
  is;
 +
  some;
 +
  code;
 +
}</pawn>
 +
 +
Block coding using braces is used everywhere in programming.  Blocks of code can be nested within each other.  It is a good idea to adapt a consistent and readable indentation style early on to prevent spaghetti-looking code.
 +
 +
 +
=Language Paradigms=
 +
Pawn may seem similar to other languages, like C, but it has fundamental differences.  It is not important that you immediately understand these differences, but they may be helpful if you're familiar with another language already.
 +
*'''Pawn is not typed.'''  Pawn only has one data type, the '''cell'''.  This will be explained in detail later.  [Below it says that there are two types: cell and string.]
 +
*'''Pawn is not garbage collected.''' Pawn, as a language, has no built-in memory allocation, and thus has no garbage.  If a function allocates memory, you may be responsible for freeing it.
 +
*'''Pawn is not object oriented.''' Pawn is procedural, and relies on subroutines.  It also does not have C structs.
 +
*'''Pawn is not functional.''' Pawn is procedural, and does not support lambda functions or late binding or anything else you might find in a very high-level language, like Python or Ruby.
 +
*'''Pawn is single-threaded.''' As of this writing, Pawn is not thread safe. 
 +
*'''Pawn is not interpreted.''' Well, it "sort of" is.  It gets interpreted at a very low level.  You must run your code through a compiler, which produces a binary.  This binary will work on any platform that the host application uses.  This speeds up loading time and lets you check errors easier.
 +
 +
These language design decisions were made by ITB CompuPhase.  It is designed for low-level embedded devices and is thus very small and very fast.
 +
 +
=Variables=
 +
In Pawn there are two variable types: the '''cell''' and the '''String'''.  A cell can store 32 bits of numerical data.  A String is a sequential/flat list of UTF-8 text characters.
 +
 +
A '''cell''' has no inherent type, however, cells can be '''tagged'''.  A tag lets you enforce where certain cells can be used.  The default tags are:
 +
*(nothing), or '''_''' - No tag.  Usually used for whole numbers ([http://en.wikipedia.org/wiki/Integer Integers]).
 +
*'''Float''' - Used for floating point (fractional) numbers.
 +
*'''bool''' - Used for storing either '''true''' or '''false'''.
 +
 +
Strings are different and will be explained in the next sections.
 +
 +
==Declaration==
 +
Examples of different valid variable declarations:
 +
<pawn>
 +
new a = 5;
 +
new Float:b = 5.0;
 +
new bool:c = true;
 +
new bool:d = 0;      //Works because 0 is false
 +
</pawn>
 +
 +
Invalid variable usage:
 +
<pawn>
 +
new a = 5.0;        //Tag mismatch.  5.0 is tagged as Float
 +
new Float:b = 5;    //Tag mismatch.  5 is not tagged.
 +
</pawn>
 +
 +
If a variable is not assigned upon declaration, it will be set to 0.  For example:
 +
<pawn>
 +
new a;        //Set to 0
 +
new Float:b;  //Set to 0.0
 +
new bool:c;  //Set to false
 +
</pawn>
 +
 +
==Assignment==
 +
Variables can be re-assigned data after they are created.  For example:
 +
<pawn>new a, Float:b, bool:c;
 +
 +
a = 5;
 +
b = 5.0;
 +
c = true;
 +
</pawn>
 +
 +
 +
=Arrays=
 +
An array is a sequence of data in a sequential list.  Arrays are useful for storing multiple pieces of data in one variable, and often greatly simplify many tasks. 
  
 
..в стадии перевода
 
..в стадии перевода
  
 
[[Category:Russian]]
 
[[Category:Russian]]

Revision as of 03:35, 23 December 2008

Это руководство призвано дать Вам самые основные представления по основам написания сприптов в SourcePawn. Pawn это "скриптовый" язык используемый для внедрения функциональности в других программах. Это означает, что это не самостоятельный язык, как C++ или Java, и его элементы будут отличаться в различных приложениях. SourcePawn это вариация языка Pawn используемая в SourceMod.

Это руководство не расскажет Вам как писать SourceMod плагины; оно предназначено для получения общих представлений о синтаксисе и семантике этого языка. Читайте отдельную статью, Introduction to SourceMod Plugins для введения в SourceMod API.

Введение для новичков

Этот раздел создан не для программистов. Если Вы по прежнему в замешательстве, Вы можете прочитать книги о других языках программирования, таких как PHP, Python, или Java, чтобы получить более полное представление о программировании.

Идентификаторы/Ключевые слова

Идентификаторы представляет собой набор букв, цифр и/или нижнего подчеркивания, что представляет собой нечто уникальное. Идентификаторы вводятся с учетом регистра (в отличие от PHP, где иногда это не требуется). Идентификаторы не начинаются с какого-либо специального символа, но они должны начинаться с буквы.

Есть несколько зарезервированных символов, которые имеют особое значение. Например, if, for, и return специальные конструкции в языке, которые будут описаны позднее. Они не могут быть использованы в качестве названий идентификаторов.

Переменные

Существует несколько важных конструкций, которые Вы должны знать, прежде чем приступить к написанию сценария. Во-первых, это переменные. Переменная это идентификатор, который содержит данные. Например, переменная "a" может содержать числа "2", "16", "0", и так далее. Переменные создаются для хранения данных внутри программы. Переменные должны быть объявлены до их использования, с помощью ключевого слова "new". Данные можно присвоить переменной, используя знак равенства (=). Пример:

new a, b, c, d;
 
a = 5;
b = 16;
c = 0;
d = 500;

В SourcePawn, переменные бывают двух типов, которые будут более подробно описаны далее.

  • Числовые (могут содержать только произвольные числовые данные), как показано выше.
  • Строковые (могут содержать целый ряд текстовых символов)

Functions

The next important concept is functions. Functions are symbols or names that perform an action. That means when you activate them, they carry out a specific sequence of code. There are a few types of functions, but every function is activated the same way. "Calling a function" is the term for invoking a function's action. Function calls are constructed like this:

function(<parameters>)

Examples:

show(56);   //Activates "show" function, and gives the number 56 to it
show();     //Activates "show" function with no data, blank
show(a);    //Activates "show" function, gives a variable's contents as data

Every piece of data passed to a function is called a parameter. A function can have any number of parameters (there is a "reasonable" limit of 32 in SourceMod). Parameters will be explained further in the article.

Comments

Note any text that appears after a "//" is considered a "comment" and is not actual code. There are two comment styles:

  • // - Double slash, everything following on that line is ignored.
  • /* */ - Multi-line comment, everything in between the asterisks is ignored. You cannot nest these.


Block Coding

The next concept is block coding. You can group code into "blocks" separated by { and }. This effectively makes one large block of code act as one statement. For example:

{
   here;
   is;
   some;
   code;
}

Block coding using braces is used everywhere in programming. Blocks of code can be nested within each other. It is a good idea to adapt a consistent and readable indentation style early on to prevent spaghetti-looking code.


Language Paradigms

Pawn may seem similar to other languages, like C, but it has fundamental differences. It is not important that you immediately understand these differences, but they may be helpful if you're familiar with another language already.

  • Pawn is not typed. Pawn only has one data type, the cell. This will be explained in detail later. [Below it says that there are two types: cell and string.]
  • Pawn is not garbage collected. Pawn, as a language, has no built-in memory allocation, and thus has no garbage. If a function allocates memory, you may be responsible for freeing it.
  • Pawn is not object oriented. Pawn is procedural, and relies on subroutines. It also does not have C structs.
  • Pawn is not functional. Pawn is procedural, and does not support lambda functions or late binding or anything else you might find in a very high-level language, like Python or Ruby.
  • Pawn is single-threaded. As of this writing, Pawn is not thread safe.
  • Pawn is not interpreted. Well, it "sort of" is. It gets interpreted at a very low level. You must run your code through a compiler, which produces a binary. This binary will work on any platform that the host application uses. This speeds up loading time and lets you check errors easier.

These language design decisions were made by ITB CompuPhase. It is designed for low-level embedded devices and is thus very small and very fast.

Variables

In Pawn there are two variable types: the cell and the String. A cell can store 32 bits of numerical data. A String is a sequential/flat list of UTF-8 text characters.

A cell has no inherent type, however, cells can be tagged. A tag lets you enforce where certain cells can be used. The default tags are:

  • (nothing), or _ - No tag. Usually used for whole numbers (Integers).
  • Float - Used for floating point (fractional) numbers.
  • bool - Used for storing either true or false.

Strings are different and will be explained in the next sections.

Declaration

Examples of different valid variable declarations:

new a = 5;
new Float:b = 5.0;
new bool:c = true;
new bool:d = 0;      //Works because 0 is false

Invalid variable usage:

new a = 5.0;         //Tag mismatch.  5.0 is tagged as Float
new Float:b = 5;     //Tag mismatch.  5 is not tagged.

If a variable is not assigned upon declaration, it will be set to 0. For example:

new a;        //Set to 0
new Float:b;  //Set to 0.0
new bool:c;   //Set to false

Assignment

Variables can be re-assigned data after they are created. For example:

new a, Float:b, bool:c;
 
a = 5;
b = 5.0;
c = true;


Arrays

An array is a sequence of data in a sequential list. Arrays are useful for storing multiple pieces of data in one variable, and often greatly simplify many tasks.

..в стадии перевода