標籤:style color os ar for strong 檔案 sp on
if 達 表 式
文法:if <expr1> then <expr2> [else <expr3>]
文法:if <expr1> do <expr2>
<expr1>為測試運算式,其求值結果必須為 True 或 False
如果測試結果為 True,
那麼 then 或 do 之後的<expr2>被執行
其求值結果作為 if 運算式的傳回值
case 達 表 式
case 運算式將一個測試運算式的結果和一系欄標籤運算式的標籤進行比較,根據比較
結果從中選擇一個標籤運算式進行求值
文法:case [<expr>] of(<cases>)
其中<expr>是測試運算式,而<cases>是帶標籤的運算式序列,其文法為:
<factor>:<expr>
default : <expr>
-----------------------------------------------
new_obj = case copy_type.state of
(
2 : copy $foo
3 : instance $foo
default:reference $foo
)
---------------------------------------------------------------
如果用運算式作為標籤,必須用括弧把運算式括起來,例如:
case of
(
(a > b) : print "a is big"
(b < c) : print "b is little"
(c <= d*3) : ...
default: ...
)
while 迴圈
while 和 do 迴圈用來重複執行一個運算式, 直到測試運算式的求值結果為 False
文法:while <expr> do <expr>
其中 while 後面的<expr>為測試運算式,如果測試運算式結果為 True,將一直重複執
行 do 後面的<expr>
--------------------------------
x=10
while x > 0 do
(
print x
x -= 1
)
for 迴圈
文法:for <var_name>(in | =)<sequence>(do | collect)<expr>
<var_name> 為迴圈索引變數名,<sequence>為迴圈的源數值
可以為以下幾種形式:
<expr> to <expr> [by <expr> ] [where <expr> ]
<expr> [where <expr> ]
--------------------------------------------------------
for i = 1 to 10 do print i --數字序列
for item in [able] do x = x+item.height --數組序列
for t in of to loof by 5f do --以幀為單位的時間序列
bigones = for obj in $Box*
where obj.height > 100 collect obj --將高度大於 100 的 Box 放到數組裡
------------------------------------------
<sequence>形式都有一個可選的 where <expr>,其求值結果必須為 True 或 False
where 運算式在執行迴圈之前被求值,只有當它的結果為 True 時,才接著執行迴圈
do <expr> 形式的 for 迴圈簡單地在每次迴圈時對<expr> 裡的運算式依次求一遍值
迴圈變數<var_name>在迴圈體<expr> 裡是可見的
------------------------------------------------
collect <expr> 形式的 for 迴圈收集每次迴圈時<expr> 的求值結果
並把它們儲存在一個數組裡,然後這個數組被作為 for 迴圈的傳回值
continue 語 句
用來在 for、do、while 迴圈中直接跳至迴圈末尾,然後開始下一次迴圈
for i=1 to 8 do(if i == 5 do continue; print i)--列印 1..4, 6..8
-----------------------------------------------
while not eof f do --讀入檔案直至檔案末尾
(
local line=readline f --讀入一行
if line[1] == "-" do continue --如果為注釋行,跳過本行
line1=parser1 line --調用函數 parser1
processobjs line1 --調用函數 processobjs
)
exit 語 句
在 for、do、while 迴圈中提前退出迴圈,即使迴圈測試運算式的值仍為 True
文法:exit [with <expr> ]
其中可選的 with <expr> 讓使用者指定提前退出迴圈時迴圈體的傳回值,
如果未指定 with<expr>,傳回值為 undefined
從一個 for…do 迴圈用 exit with <expr> 退出,傳回值為 ok
從一個 for…collect 迴圈用 exit with <expr> 退出,傳回值為退出前收集的元素組成的數組
----------------------------------------
while x < y do
(
local delta = x - y
if delta <= 0 then exit
$foo.pos.x = compute_x(foo / delta)
x += 0.1
)
try 達 表 式
捕捉程式碼片段裡任何運行錯誤,這樣當錯誤發生時,可以採取相應的反應
文法:try <protected_expr> catch <on_err_expr>
<protected_expr>為要捕捉運行異常的運算式
一旦發現運行錯誤,<on_err_expr>將被執行
如果<protected_expr>為一個塊運算式,執行將停在發生錯誤的那一行
如果沒有發生運行錯誤,<on_err_expr>將不被執行
---------------------------------------------------------------
f = openFile "foo.dat"
try
while not eof f do read_some_data f
catch
(
messageBox "bad data in foo.dat"
results = undefined
)
close f
調用函數 read_some_data()過程中發現的任何錯誤將被捕捉到
然後系統會顯示一個資訊框
基礎文法(if while case for continue exit try)