跳轉到內容

Dragon 語言入門 / 課程 / 函式

來自華夏公益教科書,自由的教科書

在本章中,我們將學習以下主題:-

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

定義函式

[編輯 | 編輯原始碼]

要定義一個新的函式

語法

	func <function_name> (parameters)
	{
		Block of statements
	}


示例

	func hello()
	{
		showln "Hello from function"
	}

呼叫函式

[編輯 | 編輯原始碼]

提示:我們可以在函式定義之前呼叫函式。

示例

	hello()

	func hello()
	{
		showln "Hello from function"
	}


示例

	first()  second()

	func first() {
		showln "message from the first function" 
	}

	func second() {
		showln "message from the second function" 
	}

宣告引數

[編輯 | 編輯原始碼]

要宣告函式引數,請在括號中寫出引數。

示例

	func sum(x, y)
	{
		showln x + y
	}

傳遞引數

[編輯 | 編輯原始碼]

要向函式傳遞引數,請在函式名後的 () 內輸入引數

語法

	name(parameters)

示例

	/* output
	** 8
	** 3000
	*/

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

	func sum(x, y)
	{
		showln x + y
	}

變數作用域

[編輯 | 編輯原始碼]

Dragon 程式語言使用 詞法作用域 來確定變數的作用域。

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

在任何函式內部,我們都可以訪問定義在該函式內部的變數,以及全域性變數。

示例

	// the program will print numbers from 10 to 1
	
	x = 10                    // x is a global variable.
	
	for(t = 1, t < 11, t++)   // t is a local variable
		mycounter()           // call function

	func mycounter() {
		showln x              // print the global variable value
		x--                   //decrement
	}

返回值

[編輯 | 編輯原始碼]

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

語法

	return <expression>


示例

	showln my(30, 40)      // prints 70
	
	func my(a, b)
	{ 
		return a + b
	}


華夏公益教科書