English 中文(简体)
Euphoria - Functions
  • 时间:2024-12-22

Euphoria - Functions


Previous Page Next Page  

Euphoria functions are just pke 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 pst 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-pst)

   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

Calpng 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 facipty to pass different parameters while calpng 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

Advertisements