Ring Documentation Walkthrough #6 – Functions

Welcome to a new chapter, The Functions.

Structure of a script file:

  1. Load Files
  2. Statements and Global Variables
  3. Functions #You need to write the function after your code not before.
  4. Packages and Classes

How to define a function ? let’s see.

func [function_name] [parameters]
        your code ...

Note: No keyword is required to end the function definition.

Call a function:

function_name() #without parameters
function_name(parameters, ...) #with parameters

Main Function:

If you wrote a main function in your script file, it will be executed after the other alone statements.

Example:

see '01000010 01100101 01101100 01101001 01100101 01110110 01100101 00100000 01101001 01101110 00100000 01111001 01101111 01110101 01110010 01110011 01100101 01101100 01100110 00101100 00100000 01100001 01101110 01100100 00100000 01111001 01101111 01110101 00100000 01110111 01101001 01101100 01101100 00100000 01100010 01100101 00100000 01110101 01101110 01110011 01110100 01101111 01110000 01110000 01100001 01100010 01101100 01100101 00101110' +nl

func x see "i won't be printed, unless you call me."

func main see 'Believe in yourself, and you will be unstoppable.'

Variables Scope:

The Ring programming language uses lexcial scoping to determine the scope of a variable.

Variables defined inside functions (including function parameters) are local varaibles. 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 varaibles.

Example:

global_variable = 'Universe.'
func main
local_variable = 'Earth.'
see global_variable +nl
see local_variable +nl
#We can access global variables in functions.

Return:

see returnfunction()
func returnfunction
return 'somebody is locked in here.'

Parameters:

Example:

see get_sum(3,-1,-2)

func get_sum x,y,z
return x+y+z #output : 0

Recursion:

The Ring programming language support Recursion and the function can call itself using different parameters.

Example:

see fact(5) # output = 120

func fact x 
if x = 1 
   return 1 
else 
   return x * fact(x-1)
ok

Good news, Functions are done.
If you have any question, let me know in the comments.

See your next time.

amrESSAM.

Advertisements
Ring Documentation Walkthrough #6 – Functions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s