Jump to content

An Introduction to Dragon/Lessons/Functions

From Wikibooks, open books for an open world

Functions

[edit | edit source]

In this chapter we are going to learn about the next topics :-

  • Define functions
  • Call functions
  • Declare parameters
  • Send parameters
  • Variables Scope
  • Return Value

Define Functions

[edit | edit source]

To define a new function:

Syntax:

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


Example:

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

Call Functions

[edit | edit source]

Tip: We can call the function before the function definition.

Example:

	hello()

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


Example:

	first()  second()

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

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

Declare parameters

[edit | edit source]

To declare the function parameters, write them in parentheses.

Example:

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

Send Parameters

[edit | edit source]

To send parameters to function, type the parameters inside () after the function name

Syntax:

	name(parameters)

Example:

	/* output
	** 8
	** 3000
	*/

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

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

Variables Scope

[edit | edit source]

The Dragon programming language uses lexical scoping to determine the scope of a variable.

Variables defined inside functions (including function parameters) are local variables. Variables defined outside functions (before any function) are global variables.

Inside any function we can access the variables defined inside this function beside the global variables.

Example:

	// 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 Value

[edit | edit source]

The function can return a value using the return command.

Syntax:

	return <expression>


Example:

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