An Introduction to Dragon/Lessons/Functions
Functions
editIn 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
editTo define a new function:
Syntax:
func <function_name> (parameters)
{
Block of statements
}
Example:
func hello()
{
showln "Hello from function"
}
Call Functions
editTip: 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
editTo declare the function parameters, write them in parentheses.
Example:
func sum(x, y)
{
showln x + y
}
Send Parameters
editTo 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
editThe 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
editThe 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
}