跳轉到內容

環/教程/函式

來自華夏公益教科書,開放的書籍,開放的世界
<

在本章中,我們將學習以下內容:

  • 定義函式
  • 呼叫函式
  • 宣告引數
  • 傳遞引數
  • 主函式
  • 變數作用域
  • 程式結構
  • 返回值
  • 遞迴

定義函式

[編輯 | 編輯原始碼]

定義新函式

語法

	func <function_name> [parameters]
		Block of statements

.. 注意:: 不需要關鍵字來結束函式定義。


示例

	func hello
		see "Hello from function" + nl

呼叫函式

[編輯 | 編輯原始碼]

要呼叫不帶引數的函式,鍵入函式名,然後是 ()

.. 提示:: 可以在函式定義和函式程式碼之前呼叫函式。

示例

	hello()

	func hello
		see "Hello from function" + nl


示例

	first()  second()

	func first   see "message from the first function" + nl

	func second  see "message from the second function" + nl

宣告引數

[編輯 | 編輯原始碼]

要宣告函式引數,在函式名之後鍵入引數列表,引數列表是一組用逗號分隔的識別符號。

示例

	func sum x,y
		see x+y+nl

傳遞引數

[編輯 | 編輯原始碼]

要將引數傳遞給函式,在函式名之後鍵入引數,引數位於 () 之內。

語法

	funcname(parameters)

示例

	/* output
	** 8
	** 3000
	*/

	sum(3,5) sum(1000,2000)

	func sum x,y see x+y+nl


主函式

[編輯 | 編輯原始碼]

使用環程式語言,主函式是可選的,當它被定義時,它將在其他語句結束之後執行。

如果沒有任何其他語句單獨存在,主函式將是第一個 `入口點 <http://en.wikipedia.org/wiki/Entry_point>`_

示例

	# this program will print the hello world message first then execute the main function

	See "Hello World!" + nl

	func main
		see "Message from the main function" + nl

變數作用域

[編輯 | 編輯原始碼]

環程式語言使用 `詞法作用域 <http://en.wikipedia.org/wiki/Scope_%28computer_science%29#Lexical_scope_vs._dynamic_scope>`_ 來確定變數的作用域。

在函式內部定義的變數(包括函式引數)是區域性變數。在函式外部定義的變數(在任何函式之前)是全域性變數。

在任何函式內部,除了全域性變數之外,我們還可以訪問在該函式內部定義的變數。

示例

	# the program will print numbers from 10 to 1

	x = 10 				# x is a global variable.

	func main

		for t = 1 to 10		# t is a local variable
			mycounter()	# call function
		next

	func mycounter

		see x + nl		# print the global variable value
		x--			# decrement

.. 注意:: 在 for 迴圈之前使用主函式將 t 變數宣告為區域性變數,建議使用主函式,而不是直接鍵入指令來將新變數的作用域設定為區域性變數。


程式結構

[編輯 | 編輯原始碼]
+--------------------------------+
| Source Code File Sections	 |
+================================+
| Load Files			 |
+--------------------------------+
| Statements and Global Variables|
+--------------------------------+
| Functions 			 |
+--------------------------------+
| Packages and Classes		 |
+--------------------------------+

應用程式可能是 一個或多個檔案。

要在專案中包含另一個原始檔,只需使用 load 命令。


語法

	Load  "filename.ring"

示例

	# File : Start.ring

	Load "sub.ring"

	sayhello("Mahmoud")
	# File : sub.ring

	func sayhello cName
		see "Hello " + cName + nl

返回值

[編輯 | 編輯原始碼]

函式可以使用 Return 命令返回一個值。

語法

	Return [Expression]

.. 提示:: Return 命令之後的表示式是可選的,我們可以使用 Return 命令來結束函式執行,而不返回任何值。

.. 注意:: 如果函式沒有返回顯式值,它將返回 NULL(空字串 = "")。

示例

	if novalue() = NULL	
		See "the function doesn't return a value" + nl
	ok

	func novalue

環程式語言支援 `遞迴 <http://en.wikipedia.org/wiki/Recursion_%28computer_science%29>`_,函式可以使用不同的引數呼叫自身。

示例

	see fact(5)  	# output = 120

	func fact x if x = 1 return 1 else return x * fact(x-1) ok


華夏公益教科書