< Dragon < Lessons

Functions

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

To define new function

Syntax:

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


Example:

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

Call Functions

.. tip:: We can call the function before the function definition and the function code.

Example:

	hello()

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


Example:

	first()  second()

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

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

Declare parameters

To declare the function parameters, write them in parentheses.

Example:

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

Send Parameters

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)

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


Variables Scope

The Dragon programming language uses `lexical scoping <http://en.wikipedia.org/wiki/Scope_%28computer_science%29#Lexical_scope_vs._dynamic_scope>`_ 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
		

	def mycounter(){

		showln x		// print the global variable value
		x--			//decrement
                }


Return Value

The function can return a value using the Return command.

Syntax:

	return [Expression]


Example:

	showln my(30,40)      //prints 70
       
        def my(a,b)
       { 
          return a+b
       }
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.