一、引言:給你的程序一個"大腦"
在掌握了變量和基本類型之後,我們需要讓程序具備邏輯判斷和重複執行的能力。條件語句、循環和函數就是ObjectSense程序的"大腦"和"肌肉",它們使程序能夠做出決策、自動化重複任務,以及模塊化組織代碼。
二、學會"做選擇":條件語句
條件語句允許程序根據不同的條件執行不同的代碼塊。ObjectSense使用if-elseif-else結構:
if {expr}
" todo
elseif {expr}
" todo
else
" todo
endif
實際示例:
let value = 0
if value >= 1
echo "value >= 1"
elseif value
echo "value < 1 && value not 0"
else
echo "value is 0"
endif
ObjectSense還支持switch分支語句,用於多分支選擇:
Switch type(object) ==
Case v:t_string call object.StaticHello("Hello string.")
Case v:t_dict call object.StaticHello("This is a dictionary.")
Default echo "nothing is matched"
三、告別"重複勞動":循環語句
循環語句讓程序能夠重複執行特定代碼塊,大大提高代碼效率。
for循環:
遍歷列表:
let list = [0, 1, 2, 3, 4]
for item in list
echo item
endfor
遍歷字典:
let dict = {'x':1, 'y':2}
for [key,val] in items(dict)
echo key . '=>' . val
endfor
while循環:
let i = 0
while i < 10
if i == 5
echo "end loop"
break
endif
echo i
let i += 1
endwhile
echo 'done'循環中可以使用break、continue等關鍵字進行流程控制。
四、打造你的"專屬工具":函數
函數是將代碼組織成可重用模塊的基本方式。
函數定義:
function! FuncName(args?) dict?
...
endfunction
函數調用:
function! Sum(x, y)
return a:x + a:y
endfun
let sum = Sum(n1, n2) "Success
lambda表達式:
用於創建簡短的匿名函數:
let RectSize = { rect -> rect.w * rect.h }
echo RectSize( {"w":100,"h":200} )
函數閉包:
支持內部函數和閉包特性:
function! Counter()
let count = 0
function! Increment() closure
let count += 1
return count
endfun
return funcref('Increment')
endfun
五、小結:組合的力量
通過一個簡單的綜合示例展示條件、循環和函數的協同工作:
function! ProcessNumbers(numbers)
let result = 0
for num in a:numbers
if num > 0
let result += num
endif
endfor
return result
endfun
let numbers = [1, -2, 3, -4, 5]
echo "Sum of positive numbers: " . ProcessNumbers(numbers)
這個示例展示瞭如何定義函數、使用循環遍歷列表,以及在循環中進行條件判斷。
條件語句、循環和函數是控制程序流程的核心要素,它們使程序能夠做出智能判斷、高效執行重複任務,並以模塊化的方式組織代碼。掌握這些概念後,你已經具備了編寫基本ObjectSense程序的能力。