Euphoria Programming Language Tutorial on Euphoria Functions

euphoria functions are just like procedures, but they return a value, and can be used in an expression. this chapter explains how to write your own functions in euphoria.

function definition

before we use a function we need to define it. the most common way to define a function in euphoria is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block which ends with end function statement. the basic syntax is shown here −

function functionname(parameter-list)

   statements
   ..........
   return [euphoria object]

end function

example

a simple function called sayhello that takes no parameters is defined here −

function sayhello()
   puts(1, "hello there")
   return 1
end function

calling a function

to invoke a function somewhere later in the script, you would simple need to write the name of that function as follows −

#!/home/euphoria-4.0b2/bin/eui

function sayhello()
   puts(1, "hello there")
   return 1
end function

-- call above defined function.
sayhello()

this produces the following result −

hello there

function parameters

till now we have seen function without a parameters. but there is a facility to pass different parameters while calling a function. these passed parameters can be captured inside the function and any manipulation can be done over those parameters.

a function can take multiple parameters separated by comma.

example

let us do a bit modification in our sayhello function. this time it takes two parameters −

#!/home/euphoria-4.0b2/bin/eui

function sayhello(sequence name,atom  age)
   printf(1, "%s is %d years old.", {name, age})
   return 1
end function

-- call above defined function.
sayhello("zara", 8)

this produces the following result −

zara is 8 years old.

the return statement

a euphoria function must have return statement before closing statement end function. any euphoria object can be returned. you can, in effect, have multiple return values, by returning a sequence of objects. for example

return {x_pos, y_pos}

if you have nothing to return, then simply return 1 or 0. the return value 1 indicates success and 0 indicates failure