# Ring/Printable version

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Ring

# Lessons/Introduction
## Introduction

Welcome to the Ring programming language!
In this chapter we are going to discuss the goals behind the language design and implementation.

# Lessons/Motivation
## Motivation

In Nov. 2011, I started to think about creating a new version of the Programming Without Coding Technology (PWCT) software from scratch.
I was interested in creating multi-platform edition of the software beside adding support for Web & Mobile development. Most of the PWCT source code was written in VFP and the software comes with a simple scripting language for creating the components called (RPWI). The software contains components that support code generation in programming languages like Harbour, C, Supernova & Python.
What i was looking for is a programming language that can be used to build the development environment, provides multi-platform support, more productivity, better performance, can be used for components scripting & can be used for developing different kinds of applications.
Instead of using a mix of programming languages, I decided to use one programming language for creating the development environment, for components scripting & for creating the applications.
I looked at many programming languages like C, C++, Java, C#, Lua, PHP, Python & Ruby. I avoided using C or C++ directly because i want high-level of productivity more than the level provided by these languages, also a language behind visual programming environment for novice programmers or professionals must be easy to use & productive.
Java & C# are avoided for some reason too! I wanted to use a dynamic programming language and these languages are static typing, Java is multi-platform, also C# through Mono, but the use of huge number of classes and forcing the use of Object-Orientation, using a verbose language is not right for me. I need a small language, but fast and productive, also I need better control on the Garbage Collector (GC), I need a better one that is designed for fast applications.
Lua is small and fast, but it’s avoided because I need more powerful language for large applications.
PHP is a Web programming language and it’s syntax is very similar to C, this leads to a language not general as I want and not simple as I need to have.
Python & Ruby are more like what I need, but I need something more simple, smaller, faster & productive.
Python and Ruby are Case-Sensitive, the list index start counting from 0, you have to define the function before calling it, Ruby usage of Object-Orientation and message passing is more than what I need and decrease performance, Python syntax (indentation, using self, :, pass & _) is not good for my goals.
All of these languages are successful languages, and very good for their domains, but what I need is a different language that comes with new ideas and intelligent implementation (Innovative, Ready, Simple, Small, Flexiable and Fast).

# Lessons/History
## History

In Sept. 2013 I started the design and the implementation of the Ring programming language. After 21 months of development, In May 2015 the language Compiler & Virtual Machine were ready for use!
After that i spent three months testing the language again, trying to discover any bug to fix, writing better tests, by the end of August 2015, all know bugs were fixed, Writing many tests and testing automation using batch files and diff.exe helped a lot in getting a stable product.
In 12 September 2015, most of the documentation was written. Before releasing the language i started the marketing by writing a post in Arabic language about it to my facebook profile page asking for contributors interested in the language idea after reading a short description, in the same day i got a lot of emails from developers and friends interested to contribute!
The first version of the language Ring 1.0 is released in January 25, 2016

# Lessons/Features
## Features

The Ring language comes with the next features
.. tip:: One of the main goals behind the first release is creating a useful language ready for production!
* Free Open Source (MIT License)
* Interpreter - Hybrid Implementation (Compiler+VM)
* Declarative programming on the top of Object-Oriented programming
* No explicit end for statements (No ; or ENTER is required)
* A small language (Around 100,000 lines of code)
* The compiler + The Virtual Machine are 15,000 lines of C code * The other 85,000 lines of code are related to libraries! * 10,000 lines of C code * 50,000 lines of C++ code * 25,000 lines of Ring code
* Written in ANSI C (The code is generated)
* Developed using Visual Programming (PWCT)
* Optional Printing for Tokens/Grammar/Byte-Code during execution
* Portable (Windows, Linux & Mac OS X)
* Comments (One line & Multi-lines)
* Not Case-Sensitive
* Dynamic Typing
* Weakly typed
* Lexical Scoping (Global, Local & Object State)
* Default scope for variables inside functions (Local)
* Default scope for variables outside functions (global)
* Garbage Collector - Automatic Memory Management (Escape Analysis and Reference Counting)
* Structure Programming
* Rich control structures & Operators
* For in get item by reference not value, you can read/edit the item
* Use exit to go outside from more than one loop
* Procedures/Functions
* Main Function (optional)
* Call Function before the definition
* Recursion
* Multi-line literals
* Access (read/write) string letter by index
* The list index start by 1
* No keyword to end Functions/Classes/Packages
* Range operator ex: 1:10 and "a":"z"
* First Class Variables, Lists, Objects and Functions
* Store/Copy Lists/Objects by value (Deep Copy)
* Pass Lists/Objects by reference
* Native Object-Oriented Support
* Encapsulation * Setter/Getter (optional) * private state (optional) * Instantiation * Polymorphism * Composition * Inheritance (Single Inheritance) * Operator Overloading * Packages
* using { } to access objects and use attributes/methods as variables/functions
* Reflection and Meta-programming
* Clear program structure (Statements then functions then packages & classes)
* Exception Handling
* Eval to execute code during run-time
* 8-bit clean, work on binary data directly
* I/O commands
* Math functions
* String functions
* List functions
* File processing functions
* Database support (ODBC & MySQL)
* Security Functions (OpenSSL)
* Internet Functions (LibCurl)
* CGI Library (Written in Ring)
* HTTP Get * HTTP Post * File upload * Cookies * URL Encode * HTML Templates * HTML Special Characters * HTML Generation using Functions * HTML Generation using Classes * CRUD Example (using MVC) * Users Example (Register, Login and Check)
* Extension using C/C++ (Simple API)
* Embedding the language in C/C++ programs
* Comes with code generator (Written in Ring) to quickly wrap C/C++ Libraries
* Used to Support Allegro by creating RingAllegro * Used to Support Qt by creating RingQt
* Create 2D Games (Using the Allegro Library)
* Create GUI Applications for Desktop and Mobile (Using the Qt Framework)

# Lessons/Variables
## Variables

To create a new variable, you just need to determine the variable name & value. The value will determine the variable type and you can change the value to switch between the types using the same variable name.
Syntax:
.. tip::
The operator '=' is used here as an Assignment operator and the same operator can be used in conditions, but for testing equality of expressions.
.. note::
The Variable will contains the real value (not a reference). This means that once you change the variable value, the old value will be removed from memory (even if the variable contains a list or object).

## Dynamic Typing

Ring is a dynamic programming language that uses `Dynamic Typing <http://en.wikipedia.org/wiki/Type_system>`_.

## Deep Copy

We can use the assignment operator '=' to copy variables. We can do that to copy values like strings & numbers. Also, we can copy complete lists & objects. The assignment operator will do a complete duplication for us. This operation called `Deep Copy <http://en.wikipedia.org/wiki/Object_copy#Deep_copy>`_

## Weakly Typed

Ring is a `weakly typed language <http://en.wikipedia.org/wiki/Strong_and_weak_typing>`_, this means that the language can automatically convert between data types (like string & numbers) when that conversion make sense.
Rules:
.. note::
The same operator '+' can be used as an arithmetic operator or for string concatenation.
Example:

# Lessons/Operators
## Operators

In this chapter we will introduce the operators provided by the Ring programming language.

## Arithmetic Operators

The next table presents all of the arithmetic operators provided by the Ring language. Assume variable X=50 and variable Y=10 then:

## Relational Operators

The next table presents all of the relational operators provided by the Ring language. Assume variable X=50 and variable Y=10 then:

## Logical Operators

The next table presents all of the logical operators provided by the Ring language. Assume variable X=True and variable Y=False then:

## Bitwise Operators

The next table presents all of the bitwise operators provided by the Ring language. Assume variable X=8 and variable Y=2 then:

## Assignment Operators

The next table presents all of the assignment operators provided by the Ring language.
Assume variable X=8 then:

## Operators Precedence

The next table present operators from higher precedence (Evaluated first) to lower precedence.
Example:

# Lessons/Control Structures
## Control Structures

In this chapter we are going to learn about the control structures provided by the Ring programming language.

## Branching

* If Statement
Syntax:
Example:
* Switch Statement
Syntax:
Example:

## Looping

* While Loop
Syntax:
Example:
* For Loop
Syntax:
Example:
Example:
Example:
Example:
* For in Loop
Syntax:
Example:

## Using The Step option with For in

We can use the Step option with For in to skip number of items in each iteration
Example:

## Using For in to modify lists

When we use (For in) we get items by reference.
This means that we can read/edit items inside the loop.
Example:

## Do Again Loop

Syntax:
Example:

## Exit Command

Used to go outside one or more of loops.
Syntax:
Example:

## Exit from two loops

The next example presents how to use the exit command to exit from two loops in one jump.
Example:
* Loop Command
Used to jump to the next iteration in the loop.
Syntax:
Example:

## Exit/Loop inside sub functions

While we are inside a loop, we can call a function then use the exit and/or loop command inside that function and the command will work on the outer loop.
Example:

## Short-circuit evaluation

The logical operators and/or follow the `short-circuit evaluation <http://en.wikipedia.org/wiki/Short-circuit_evaluation>`_.
If the first argument of the AND operator is zero, then there is no need to evaluate the second argument and the result will be zero.
If the first argument of the OR operator is one, then there is no need to evaluate the second argument and the result will be one.
Example:
Example:
Example:

## Comments about evaluation

* True, False, nl & NULL are variables defined by the language
* True = 1
* False = 0
* nl = new line
* NULL = empty string = ""
* Everything evaluates to true except 0 (False).
Example:

# Lessons/Getting Input
## Getting Input

We can get input from the keyboard using
* The Give Command
* The GetChar Function
* The Input Function

## Give Command

Syntax:
Example:
Output:

## GetChar Function

We can get one character from the standard input using the GetChar function
Syntax:
Example:

## Input Function

We can get input from the keyboard using the Input function
Syntax:
The function will wait until nCount characters (at least) are read
Example:

# Lessons/Functions
## Functions

In this chapter we are going to learn about the next topics :-
* Define functions
* Call functions
* Declare parameters
* Send parameters
* Main Function
* Variables Scope
* Program structure
* Return Value
* Recursion

## Define Functions

To define new function
Syntax:
.. note:: No keyword is required to end the function definition.
Example:

## Call Functions

To call function without parameters, we type the function name then
.. tip:: We can call the function before the function definition and the function code.
Example:
Example:

## Declare parameters

To declare the function parameters, after the function name type the list of parameters as a group of identifiers separated by comma.
Example:

## Send Parameters

To send parameters to function, type the parameters inside after the function name
Syntax:
Example:

## Main Function

Using the Ring programming language, the Main Function is optional, when it's defined, it will be executed after the end of other statements.
if no other statements comes alone, the main function will be the first `entry point <http://en.wikipedia.org/wiki/Entry_point>`_
Example:

## Variables Scope

The Ring 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:
.. note:: Using the main function before the for loop declare the t variable as a local variable, It's recommended to use the main functions instead of typing the instructions directly to set the scope of the new variables to local.

## Program Structure

The application maybe one or more of files.
to include another source file in the project, just use the load command.
Syntax:
Example:

## Return Value

The function can return a value using the Return command.
Syntax:
.. tip:: the Expression after the return command is optional and we can use the return command to end the function execution without returning any value.
.. note:: if the function doesn't return explicit value, it will return NULL (empty string = "" ).
Example:

## Recursion

The Ring programming language support `Recursion <http://en.wikipedia.org/wiki/Recursion_%28computer_science%29>`_ and the function can call itself using different parameters.
Example:

# Lessons/Lists
## Lists

In this chapter we are going to learn how to deal with lists.

## Create Lists

We can create new lists by defining the list items inside square bracts.
Example:
Also we can create new lists using the : operator
Example:
Also we can create lists using the list function
Syntax:
Example
.. note:: the list index start from 1

## Add Items

To add new items to the list, we can use the Add function.
Syntax:
Example:
Also we can do that using the + operator.
Syntax:
Example:

## Get List Size

We can get the list size using the len function
Syntax:
Example:

## Delete Item From List

To delete an item from the list, we can use the del function
Syntax:
Example:

## Get List Item

To get an item from the list, we uses the next syntax
Example:

## Set List Item

To set the value of an item inside the list, we can use the next syntax
Example:

## Search

To find an item inside the list we can use the find function
Syntax:
Example:
Example:
Also we can use the binarysearch function to search in sorted list.
Syntax:
Example:
Output:

## Sort

We can sort the list using the sort function.
Syntax:
Example:
We can sort list of strings
Example:
We can sort a list based on a specific column.
Example:
Output:

## Reverse

We can reverse a list using the reverse function.
Syntax:
Example:

## Insert Items

To insert an item in the list we can use the insert function.
Syntax:
The inserted item will be after the index
Example:

## Nested Lists

The list may contain other lists
Example:

## Copy Lists

We can copy lists (including nested lists) using the Assignment operator.
Example:

## First-class lists

Lists are `first-class citizens <http://en.wikipedia.org/wiki/First-class_citizen>`_ where we can store lists in variables, pass lists to functions, and return lists from functions.
Example:

## Using Lists during definition

We can use the list items while we are defining the list for the first time.
Example:

## Passing Lists to Functions

Lists are passed to functions by reference, This means that the called function will work on the same list and can modify it.
Example:

## Access List Items by String Index

Instead of using numbers to determine the item index when we get item value or set item value, We can access items using string index if the item is a list contains two items and the first item is a string.
Example:
This type of lists can be defined in a better syntax using the : and = operators.
Example:
.. tip:: using : before identifier (one word) means literal
.. note:: using = inside list definition create a list of two items where the first item is the left side and the second item is the right side.
We can add new items to the list using the string index
Example:

## Passing Parameters Using List

This type of lists is very good for passing parameters to functions Where the order of parameters will not be important (we can change the order).
Also some parameters maybe optional.
Example:

# Lessons/Strings
## Strings

In this chapter we are going to learn about strings creation and manipulation.

## String Literals

Syntax:

## Get String Length

We can get the string length (letters count inside a string) using the len function
Syntax:
Example:

## Convert Letters Case

Syntax:
Example:

## Access String Letters

We can access a letter inside a string by the letter index
Syntax:
Example:
We can use for in to get string letters.
Example:
We can modify the string letters
Example:

## Left Function

We can get a specified number of characters from a string using the Left function.
The starting position is 1.
Syntax:
Example:

## Right Function

We can get a specified number of characters from a string using the Right function.
The starting position is the last character on the right.
Syntax:
Example:

## Trim Function

We can remove all leading and trailing spaces from a string using the Trim function.
Syntax:
Example:

## Copy Function

We can duplicate a string more than one time using the copy function.
Syntax:
Example

## Lines Function

We can count the number of lines inside a string using the Lines function.
Syntax:
Example:

## Substr Function

We can work on sub strings inside a string using the substr function. Using Substr we can
* Find substring
* Get substring from position to end
* Get Number of characters from position
* Transform Substring To Another Substring

## Find substring

Syntax:
Example:

## Get substring from position to end

Syntax:
Example:

## Get Number of Characters From Position

Syntax:
Example:

## Transform Substring To Another Substring

Syntax:
Example:

## strcmp Function

We can compare between two strings using the strcmp function.
Syntax:
Example:
Output:

## str2list and list2str Functions

We can convert string lines to list items using the str2list function. Also we can convert the list to a string using list2str function.
Syntax:
Example:

# Lessons/Date and Time
## Date and Time

In this chapter we are going to learn about the date and time functions.

## Clock Function

Syntax:
Example:

## Time Function

We can get the system time using the Time function.
Example:

## Date Function

We can get the date using the Date function.
Syntax:
Example:

## TimeList Function

We can print the date and the time information using the TimeList function.
Syntax:
The next table presents the list items
Example:
Example:
Example:

## AddDays Function

Syntax:
Example:

## DiffDays Function

Syntax:
Example:

# Lessons/Check Data Type and Conversion
## Check Data Type and Conversion

In this chapter we are going to learn about the functions that can be used for
* Checking Data Type
* Checking Character
* Conversion

## Check Data Type

The next functions can be used to check the data type
* isstring
* isnumber
* islist
* type
* isnull

## IsString Function

Using the IsString function we can know if the value is a string or not
Syntax:
Example:

## IsNumber Function

Using the IsNumber function we can know if the value is a number or not
Syntax:
Example:

## IsList Function

Using the IsList function we can know if the value is a list or not
Syntax:
Example:
pair: Data Type; Type

## Type Function

We can know the type of a value using the Type Function.
Syntax:
Example:

## IsNULL Function

We can check the value to know if it's null or not using the IsNULL function
Syntax:
Example:

## Check Character

The next functions can be used to check character
* isalnum
* isalpha
* iscntrl
* isdigit
* isgraph
* islower
* isprint
* ispunct
* isspace
* isupper
* isxdigit

## IsAlNum Function

We can test a character or a string using the IsAlNum Function
Syntax:
Example:

## IsAlpha Function

We can test a character or a string using the IsAlpha Function
Syntax:
Example:

## IsCntrl Function

We can test a character or a string using the IsCntrl Function
Syntax:
Example:

## IsDigit Function

We can test a character or a string using the IsDigit Function
Syntax:
Example:

## IsGraph Function

We can test a character or a string using the IsGraph Function
Syntax:
Example:

## IsLower Function

We can test a character or a string using the IsLower Function
Syntax:
Example:

## IsPrint Function

We can test a character or a string using the IsPrint Function
Syntax:
Example:

## IsPunct Function

We can test a character or a string using the IsPunct Function
Syntax:
Example:

## IsSpace Function

We can test a character or a string using the IsSpace Function
Syntax:
Example:

## IsUpper Function

We can test a character or a string using the IsUpper Function
Syntax:
Example:

## IsXdigit Function

We can test a character or a string using the IsXdigit Function
Syntax:
Example:

## Conversion

The next functions can be used for conversion
* number
* string
* ascii
* char
* hex
* dec
* str2hex
* hex2str

## Number Function

We can convert strings to numbers using the Number function or the + operator.
Syntax:
Example:

## String Function

We can convert numbers to strings using the String function or the + operator.
Syntax:
Example:

## Ascii Function

We can get the ASCII code for a letter using the Ascii function
Syntax:
Example:

## Char Function

We can convert the ASCII code to character using the Char function.
Syntax:
Example:

## Hex Function

We can convert decimal to hexadecimal using the Hex function.
Syntax:
Example:

## Dec Function

We can convert hexadecimal to decimal using the Dec function
Syntax:
Example:

## Str2hex Function

We can convert string characters to hexadecimal characters using the Str2hex function.
Syntax:
Example:

## Hex2str Function

We can convert hexadecimal characters to string using the Hex2str function
Syntax:
Example:

# Lessons/Mathematical Functions
## Mathematical Functions

In this chapter we are going to learn about the mathematical functions

## List of functions

The Ring programming language comes with the next mathematical functions

## Example

Program Output:

## Random Function

The Random function generate a random number and we can set the maximum value (optional).
Syntax:
Example:
Program Output:

## Unsigned Function

We can use unsigned numbers using the Unsigned function.
Syntax:
Example:
Output:

## Decimals Functions

We can determine the decimals numbers count after the point in float/double numbers using the decimals function.
Syntax:
Example:
Output:

# Lessons/Files
## Files

In this chapter we are going to learn about files functions.
* Read
* Write
* Dir
* Rename
* Remove
* fopen
* fclose
* fflush
* freopen
* tempfile
* tempname
* fseek
* ftell
* rewind
* fgetpos
* fsetpos
* clearerr
* feof
* ferror
* perror
* fgetc
* fgets
* fputc
* fputs
* ungetc
* fread
* fwrite
* fexists

## Read Function

We can read the file content using the Read function
Syntax:
Example:
The read function can read binary files too
Example:

## Write Function

We can write string to file using the Write function
The write function can write binary data to binary files.
Syntax:
Example:

## Dir Function

We can get the folder contents (files & sub folders) using the Dir function.
Syntax:
This function returns a list and each list item is a list of two items
* File/sub folder name
* Type (0 = File , 1 = Folder/Directory)
Example:

## Rename Function

We can rename files using the Rename function
Syntax:
Example:

## Remove Function

We can delete a file using the Remove function
Syntax:
Example:

## Fopen Function

We can open a file using the Fopen function
Syntax:

## Fclose Function

When we open a file using fopen function, we can close it using the Fclose function
Syntax:

## Fflush Function

We can flushes the output buffer of a stream using the Fflush function
Syntax:

## Freopen Function

We can open another file using the same file handle and at the same file close the old file
Syntax:
Example:
/* ** Read : https://en.wikipedia.org/wiki/Device_file#Device_files ** The next code is not portable, we can use iswindows before ** using it and we can write special code for each operating system. */
freopen("CON","w",stdout) # For Microsoft Windows see "Done" + nl # print to stdout again
Output:
# Output to file : myprogoutput.txt welcome 1 2 3 4 5 6 7 8 9 10

## Tempfile Function

The function Tempfile creates a temp. file (binary).
The file will be deleted automatically when the stream is closed
Syntax:

## Tempname Function

We can generate temp. file name using the Tempname function
The generated name will be different from the name of any existing file
Syntax:

## Fseek Function

We can set the file position of the stream using the Fseek function
Syntax:
The next table presents the nWhence values

## Ftell Function

We can know the current file position of a stream using the Ftell function
Syntax:

## Rewind Function

We can set the file position to the beginning of the file using the Rewind function
Syntax:

## Fgetpos Function

We can get handle to the current file position using the Fgetpos function
Syntax:

## Fsetpos Function

We can set the current file position using the Fgetpos function
Syntax:

## Clearerr Function

We can clear the EOF error and the error indicators of a stream using the clearerr function
Syntax:

## Feof Function

We can test the end-of-file indicator using the Feof function
Syntax:

## Ferror Function

We can test the error indicator of a given stream using the Ferror function
Syntax:

## Perror Function

We can print error message to the stderr using the Perror function
Syntax:

## Fgetc Function

We can get the next character from the stream using the Fgetc function
Syntax:

## Fgets Function

We can read new line from the stream using the Fgets function
Syntax:
The function stop when nSize characters are read, new line character is read or EOF.

## Fputc Function

We can write a character to the stream using the Fputc function
Syntax:

## Fputs Function

We can write a string to the stream using the Fputs function
Syntax:

## Ungetc Function

We can push a character to the stream using the Ungetc function
The character will be available for the next read
Syntax:

## Fread Function

We can read data from a stream using the Fread function
Syntax:

## Fwrite Function

We can write data to a stream using the Fwrite function
Syntax:

## Fexists Function

We can check if a file exists using the Fexists function
Syntax:
Example:
Output:

## Example

The next program test some of the file functions

# Lessons/System Functions
## System Functions

In this chapter we are going to learn about the system functions
* System
* Get
* IsMSDOS
* IsWindows
* IsWindows64
* IsUnix
* IsMacOSX
* IsLinux
* IsFreeBSD
* IsAndroid
* Windowsnl
* Get Command Line Arguments
* Get Active Source File Name

## System Function

We can execute system commands using the system function
Syntax:
Example:

## Get Function

We can get environment variables using the Get function
Syntax:
Example:

## IsMSDOS

We can check if the operating system is MSDOS or not using the IsMSDOS function
Syntax:

## IsWindows

We can check if the operating system is Windows or not using the IsWindows function
Syntax:

## IsWindows64

We can check if the operating system is Windows 64bit or not using the IsWindows64 function
Syntax:

## IsUnix

We can check if the operating system is Unix or not using the IsUnix function
Syntax:

## IsMacOSX

We can check if the operating system is Mac OS X or not using the IsMacOSX function
Syntax:

## IsLinux

We can check if the operating system is Linux or not using the IsLinux function
Syntax:

## IsFreeBSD

We can check if the operating system is FreeBSD or not using the IsFreeBSD function
Syntax:

## IsAndroid

We can check if the operating system is Android or not using the IsAndroid function
Syntax:

## Example

Output:

## Windowsnl

We can get the windows new line string using the Windowsnl function.
Syntax:
Example:
if iswindows cStr = substr(cStr,windowsnl,nl) ok
aList = str2list(cStr) # to do - list items processing using "for in" cStr = list2str(aList)
if iswindows cStr = substr(cStr,nl,windowsnl) ok
write("ouput.txt",cStr)

## Get Command Line Arguments

We can get the command line arguments passed to the ring script using the sysargv variable.
The sysargv variable is a list contains the command line parameters.
Example
Output

## Get Active Source File Name

We can get the active source file name (*.ring) using the filename function
Syntax:
Example:
Output:
Example:

# Lessons/Eval and Debugging
## Eval and Debugging

In this chapter we are going to learn about
* Error Handling using Try/Catch/Done
* Eval function
* Raise function
* Assert function

## Try/Catch/Done

Syntax:
The statements in the Try block will be executed, if any error happens then the statements in the catch block will be executed.
Inside the catch block we can use the variable cCatchError to get the error message
Example:
Output:

## Eval Function

We can execute code during the runtime from string using the Eval function
Syntax:
Example:
Output:

## Raise Function

We can raise an exception using the Raise function
Syntax:
The function will display the error message then end the execution of the program.
We can use Try/Catch/Done to avoid exceptions generated by raise function.
Example:
if nMode < 0 or nMode > 5 raise("Error : nMode not in the range 1:4") ok
Output:
Example:
Output:

## Assert Function

We can use the Assert function to test conditions before executing the code
If the test fail the program will be terminated with an error message contains the assert condition.
Syntax:
Example:
Output:

# Lessons/Demo Programs
## Demo Programs

In this chapter we will see simple demo programs
* Language Shell
* Main Menu

## Language Shell

We can create simple interactive programming environment using the next program
Output:

## Main Menu

Example:
Output:

# Lessons/ODBC Functions
## ODBC Functions

This chapter contains the ODBC functions provided by the Ring programming language. Before using the functions load the odbclib.ring library:
* odbc_init
* odbc_drivers
* odbc_datasources
* odbc_close
* odbc_connect
* odbc_disconnect
* odbc_execute
* odbc_colcount
* odbc_fetch
* odbc_getdata
* odbc_tables
* odbc_columns
* odbc_autocommit
* odbc_commit
* odbc_rollback

## odbc_init Function

We can create ODBC Handle using the odbc_init function
Syntax:

## odbc_drivers Function

We can get a list of ODBC drivers using the odbc_drivers function
Syntax:

## odbc_datasources Function

We can get a list of ODBC data sources using the odbc_datasources function
Syntax:

## odbc_close Function

After the end of using ODBC functions we can free resources using ODBC_Close function
Syntax:

## Print List of ODBC Drivers

The next example print a list of ODBC drivers.
Output:

## Print List of ODBC Data Sources

The next example print a list of ODBC data sources.
Output:

## odbc_connect Function

We can connect to the database using the odbc_connect function.
Syntax:

## odbc_disconnect Function

We can close the connection to the database using the odbc_disconnect function.
Syntax:

## Open and Close Connection

The next example connect to the database then close the connection
Output:

## odbc_execute Function

We can execute SQL Statements on the database using the odbc_execute function.
Syntax:

## odbc_colcount Function

We can get columns count in the query result using the odbc_colcount function.
Syntax:

## odbc_fetch Function

We can fetch a row from the query result using the odbc_fetch function.
Syntax:

## odbc_getdata Function

We can get column value from the fetched row using the odbc_getdata function.
Syntax:

## Execute Query and Print Result

The next example execute query then print the query result.

## odbc_tables Function

We can get a list of tables inside the database using the odbc_tables function.
We can access the result of this function as we get any query result.
Syntax:
Example:
Output:

## odbc_columns Function

We can get a list of columns inside the table using the odbc_columns function.
Syntax:
Example:
Output:

## odbc_autocommit Function

We can enable or disable the auto commit feature using the odbc_autocommit function.
Syntax:

## odbc_commit Function

We can commit updates to the database using the odbc_commit function.
Syntax:

## odbc_rollback Function

We can rollback updates to the database using the odbc_rollback function.
Syntax:

## Transactions and Using Commit and Rollback

Example:
for x = 15001 to 20000 odbc_execute(pODBC,"insert into tel values (" + x + ",'fayed')") next
ODBC_ROLLBACK(pODBC) odbc_execute(pODBC,"insert into tel values (" + x + ",'fayed')") odbc_commit(pODBC)
See "Close database..." + nl odbc_disconnect(pODBC) odbc_close(pODBC)
Output:

## Save and Restore images

The next example save an image inside the database
The next example restore the image from the database

# Lessons/MySQL Functions
## MySQL Functions

In this chapter we are going to learn about the MySQL functions provided by the Ring programming language. Before using the functions load the mysqllib.ring library:
* MySQL_Info
* MySQL_Init
* MySQL_Error
* MySQL_Connect
* MySQL_Close
* MySQL_Query
* MySQL_Insert_ID
* MySQL_Result
* MySQL_Next_Result
* MySQL_Columns
* MySQL_Result2
* MySQL_Escape_String
* MySQL_AutoCommit
* MySQL_Commit
* MySQL_Rollback

## MySQL_Info Function

We can get the MySQL Client version using the MySQL_Info function.
Syntax:
Example:
Output:

## MySQL_Init Function

We can start using MySQL Client through the MySQL_Init function.
Syntax:

## MySQL_Error Function

We can get the error message from the MySQL Client using the MySQL_Error function.
Syntax:

## MySQL_Connect Function

We can connect to the MySQL database server using the MySQL_Connect function.
Syntax:

## MySQL_Close Function

We can close the connection to the MySQL database using the MySQL_Close function
Syntax:

## MySQL_Query Function

We can execute SQL queries using the MySQL_Query function
Syntax:

## Create Database

The next example connect to MySQL Server then create new database.
Output:

## Create Table and Insert Data

The next example create new table and insert records
Output:

## MySQL_Insert_ID Function

We can get the inserted row id using the MySQL_Insert_ID function
Syntax:
Example:
see "inserted row id : " + mysql_insert_id(con) + nl see "close database" + nl mysql_close(con)
Output:

## MySQL_Result Function

We can get the query result (data without column names) using the MySQL_Result function.
Syntax:

## MySQL_Next_Result Function

We can move to the next query result using the MySQL_Next_Result function. We use this function when we have multiple SQL statements in the same query.
Syntax:

## Print Query Result

The next example execute a query on the database then print the result.
Output:

## MySQL_Columns Function

We can get a list of columns names using the MySQL_Columns function.
Syntax:
Example:
Output:

## MySQL_Result2 Function

Instead of using MySQL_Result to get the result data without columns names, we can use the MySQL_Result2 to get all of the column names then the query result in one list.
Syntax:
Example:
Output:

## MySQL_Escape_String Function

We can store binary data and special characters in the database after processing using MySQL_Escape_String function
Syntax:

## Save Image inside the database

Example:
Output:

## Restore Image From The Database

Example:
Output:

## MySQL_AutoCommit Function

We can enable or disable the auto commit feature using the MySQL_AutoCommit function.
Syntax:

## MySQL_Commit Function

We can commit updates to the database using the MySQL_Commit function.
Syntax:

## MySQL_Rollback Function

We can rollback updates to the database using the MySQL_Rollback function.
Syntax:

## Transaction Example

The next example presents the usage of MySQL_Autocommit, MySQL_Commit & MySQL_RollBack functions.
Example:
Output:

# Lessons/Security and Internet Functions
## Security and Internet Functions

This chapter contains the security and internet functions provided by the Ring programming language for Hashing, Encryption & Decryption. Before using the functions load the openssllib.ring library:
* MD5
* SHA1
* SHA256
* SHA512
* SHA384
* SHA224
* Encrypt
* Decrypt
* Randbytes
Before using the functions load the internetlib.ring library:
* Download
* SendEmail

## MD5 Function

We can calculate the MD5 hash using the MD5 Function
Syntax:
Example:
Output:

## SHA1 Function

We can calculate the SHA1 hash using the SHA1 Function
Syntax:
Example:
Output:

## SHA256 Function

We can calculate the SHA256 hash using the SHA256 Function
Syntax:
Example:
Output:

## SHA512 Function

We can calculate the SHA512 hash using the SHA512 Function
Syntax:
Example:
Output:

## SHA384 Function

We can calculate the SHA384 hash using the SHA384 Function
Syntax:
Example:
Output:

## SHA224 Function

We can calculate the SHA224 hash using the SHA224 Function
Syntax:
Example:
Output:

## Encrypt Function

We can use the Encrypt function to encrypts the data using the Blowfish algorithm.
Syntax:

## Decrypt Function

We can use the Decrypt function to decrypt the data encrypted using the Encrypt function.
Syntax:

## Encryption and Decryption Example

The next example demonstrates how to use the Encrypt and Decrypt functions.
These functions use the Blowfish algorithm.

## File Hash

The next example demonstrates how to calculate the hash functions for files
Output:

## Randbytes Function

We can generate a string of pseudo-random bytes using the Randbytes function.
Syntax:
Example:

## Download Function

Syntax:
Example:

## SendEmail Function

Syntax:
Example:

# Lessons/Object Oriented Programming (OOP)
## Object Oriented Programming (OOP)

In this chapter we are going to learn how to use the Object-Oriented programming paradigm inside the Ring programming language.
We will learn about
* Classes and Objects
* Access Objects Using Braces
* Composition
* Setter and Getter
* Private Attributes and Methods
* Operator Overloading
* Inheritance
* Dynamic Attributes
* Packages

## Classes and Objects

We can define new classes using the next syntax
Syntax:
And we can create objects using the next syntax
Syntax:
Example:
.. note:: We can use { } to access object data and methods.
.. tip:: we can declare the class attributes directly after the class name.
Output:
We can rewrite the same program in another style
Class Point # define the Point class x y z # the class contains three attributes x, y & z func print # define the print method see x + nl + # print the x attribute y + nl + # print the y attribute z + nl # print the z attribute
Also we can write the same program in another way
.. note:: we can use the dot operator after the object name to access object members.
Also we can write the same program in another way
.. note:: we can set the default values for the class attributes when we declare them.
Also we can write the same program in another way
.. note:: we can call the init method directly using when we create new objects
Also we can write the same program in another way
.. tip:: using Hash for passing method parameters enable us to create optional

## Access Objects Using Braces

We can access the object at any time using braces { }
Inside the braces we can use the object attributes and methods directly
This can be done when we create the object using the New keyword or at any time using the next syntax
Example:
We can use braces to access objects when we call functions or methods
Example:
We can mix between using braces and the dot operator to access the object in the same expression.
Example:

## Composition

The object may contains other objects as attributes.
Using braces to access objects can be nested.
Example:
Output:

## Setter and Getter

We can define methods to be used when we set and get object attributes.
Syntax:
Example:
Output:

## Private Attributes and Methods

We can define private attributes and methods after the keyword private inside the class body
Example:
Output:

## Operator Overloading

We can add the operator method to our class to enable using operators with the class objects.
Syntax:
The function operator takes two paramters, the first represent the operator and the second represent the second parameter after the operator.
Example:
Output:

## Inheritance

We can create class from another class in the class definition using the keyword from.
Syntax:
We can call a method in the parent class from the child class using the super object.
Syntax:
Example:
Output:

## Dynamic Attributes

We can write instructions after the class name to be executed when we create new objects
Example:
.. tip:: in the previous example var1, var2, ..., var10 will be defined as attributes.
.. tip:: The problem with the previous example is that x and cStr will be defined as attributes too!
.. note:: we can write class definitions inside a string then using eval we can execute the string to define the classes

## Packages

We can create a package (a group of classes under a common name) using the next syntax
Example
.. note:: we can use the dot operator as part of the package name
Instead of typing the long name PackageName.ClassName we can use the import command
When we import a package, we can use any class inside this package directly.
Example

## Printing Objects

We can print the object state (attributes and values) using the see command.
Example:
Output:

# Lessons/Declarative Programming using Nested Structures
## Declarative Programming using Nested Structures

In this chapter we are going to learn how to build declarative programming world using nested structures on the top of object oriented.
We will learn about
* Creating Objects inside Lists
* Composition and Returning Objects and Lists by Reference
* Executing code after the end of object access
* Declarative Programming on the top of Object-Oriented

## Creating Objects inside Lists

We can create objects inside lists during list definition. Also we can add objects to the list at any time using the Add function or the + operator.
Example:
Output:

## Composition and Returning Objects and Lists by Reference

When we use composition and have object as one of the class attributes, when we return that object it will be returned by reference.
if the called used the assignment operator, another copy of the object will be created.
The caller can avoid using the assignment operator and use the returned reference directly to access the object.
The same is done also if the attribute is a list (not object).
.. note:: Objects and Lists are treated using the same rules. When you pass them to function they are passed by reference, when you return them from functions they are returned by value except if it's an object attribute where a return by reference will be done.
Example:
Output:
Example(2):
Output:
Example(3):
Output:

## Executing code after the end of object access

We can access an object using { } to use object attributes and methods.
if the object contains a method called BraceEnd, it will be executed before the end of the object access.
Example:
Output:

## Declarative Programming on the top of Object-Oriented

The next features enable us to build and use declarative programming environment using nested structures on the top of object oriented
* using to access the object attributes and methods
* BraceEnd Method
* returning objects by reference
* Setter/Getter Methods (optional)
Example:
Output:

## More beautiful Code

We can get better results and a more beautiful code when we can avoid writing after the method name when the methods doesn't take parameters. This feature is not provided directly by the Ring language because there is a difference between object methods and object attributes. We can get a similar effect on the syntax of the code when we define a getter method for the object attribute. For example instead of defining the point method. we will define the point attribute then the getpoint method that will be executed once you try to get the value of the point attribute. since we write the variable name direcly without we can write point instead of point and the method getpoint will create the object and return the object reference for us.
Example:
Output

# Lessons/Natural Language Programming
## Natural Language Programming

Using the Ring programming language, we can create Natural programming languages based on classes and objects.

## History

In 2010, I developed a new programming language called Supernova (developed using PWCT). This language uses a code that looks similar to Natural Language statements to create simple GUI applications. Now after five years, In the Ring programming language, we can get similar results, but now we have the ability to create/use code similar to Natural language statements in any domain that we like or need.
The Ring programming language comes with the Supernova sprite, but with more generalization and with mix of other languages sprites.

## Example

The next example presents how to create a class that define two instructions
The first instruction is : I want window
The second instruction is : Window title = <expr>
Also keywords that can be ignored like the 'the' keyword
Output:

# Lessons/Functional Programming
## Functional Programming

In previous chapters we learned about Functions and Recursion.
In this chapter we are going to learn about more Functional Programming (FP) concepts like
* Pure Functions
* First-class functions
* Higher-order functions
* Anonymous and nested functions.
* Equality of functions

## Pure Functions

We can create pure functions (functions that doesn't change the state) by the help of the assignment operator to copy variables (Lists & Objects) by value to create new variables instead of working on the original data that are passed to the function by reference.
Example:
Output:

## First-class Functions

Functions inside the Ring programming language are first-class citizens, you can pass functions as parameters, return them as value or store them in variables.
We can pass/return the function by typing the function name as literal like "FunctionName" or :FunctionName for example.
We can pass/return functions using the variable that contains the function name.
We can call function from variables contains the function name using the Call command
Syntax:
Example:
Output:

## Higher-order Functions

Higher-order functions are the functions that takes other functions as parameters.
Example:
Output:

## Anonymous and Nested Functions

Anonymous Functions are functions without names that can be passed as parameters to other functions or stored in variables.
Syntax:
Example:
Output:
Example:
Output:

## Equality of functions

We can test if function = function or not using the '=' or '!=' operators
Example:
Output:

# Lessons/Reflection and Meta-programming
## Reflection and Meta-programming

Since the Ring programming language is a dynamic language, we can get answers about the program code and we can modify our code during the runtime.
In this chapter we will learn about this and the available functions to use.

## locals Function

We can get a list of variables names in the current scope using the locals function.
Syntax:
Example:
Output:

## globals Function

We can get a list of variables names in the global scope using the globals function.
Syntax:
Example:
Output:

## functions Function

We can get a list of functions names written in the Ring language using the functions function.
Syntax:
Example:
Output:

## cfunctions Function

We can get a list of functions names written in the C language using the cfunctions function.
Syntax:
Example:
Output:
.. note:: The complete list is removed from the previous output.

## islocal Function

We can check if a variable is defined in the local scope or not using the islocal function.
Syntax:
Example:
Output:

## isglobal Function

We can check if a variable is defined in the global scope or not using the isglobal function.
Syntax:
Example:
Output:

## isfunction Function

We can check if a Ring function is defined or not using the isfunction function.
Syntax:
Example:
Output:

## iscfunction Function

We can check if a C function is defined or not using the iscfunction function.
Syntax:
Example:
Output:

## packages Function

We can get a list of packages names using the packages function.
Syntax:
Example:
Output:

## ispackage Function

We can check if a package is defined or not using the ispackage function.
Syntax:
Example:
Output:

## classes Function

We can get a list of classes names using the classes function.
Syntax:
Example:
Output:

## isclass Function

We can check if a class is defined or not using the isclass function.
Syntax:
Example:
Output:

## packageclasses Function

We can get a list of classes names inside a package using the packageclasses function.
Syntax:
Example:
Output:

## ispackageclass Function

We can check if a class is defined inside package or not using the ispackageclass function.
Syntax:
Example:
Output:

## classname Function

We can know the class name of an object using the classname function
Syntax:
Example:

## objectid Function

We can know the object id using the objectid function
Syntax:
Example:
Output:
We can check the variable to know if it's an object or not using the isobject function
Syntax:

## attributes Function

We can get the object attributes using the attributes function
Syntax:
Example:
We can get the object methods using the methods function
Syntax:
Example:
Output:

## isattribute Function

We can test if the object contains an attribute or not using the isattribute function
Syntax:
Example:

## isprivateattribute Function

We can test if the object contains a private attribute or not using the isprivateattribute function
Syntax:
Example:
Output:

## ismethod Function

We can test if the object class contains a method or not using the ismethod function
Syntax:
Example:

## isprivatemethod Function

We can test if the object class contains a private method or not using the isprivatemethod function
Syntax:
Example:
Output:

## addattribute Function

We can add an attribute (or a group of attributes) to the object state (not the class) using the addattribute function
Syntax:
Example(1):
Example(2):
Output:

## addmethod Function

We can add a method to the object class using the addmethod function This method can be used with any object from the same class.
Syntax:
Example:
Output:
Instead of using anonymous function to add new method to the class, we can use the function name
Example:
Output:
Since we add the method to the class, any object from that class can use this method
Example:
Output:

## getattribute function

We can get the object attribute value using the getattribute function
Syntax:
Example:
Output:

## setattribute function

We can set the object attribute value using the setattribute function
Syntax:
Example:
Output:

## mergemethods Function

We can share methods between classes without inheritance using the MergeMethods function
This function merge class methods to another class.
Syntax:
Example:
Output:

# Lessons/Extension using the C/C++ languages
## Extension using the C/C++ languages

We can extend the Ring Virtual Machine (RingVM) by adding new functions written in the C programming language or C++.
The RingVM comes with many functions written in C that we can call like any Ring function.
We can extend the language by writing new functions then rebuilding the RingVM again, or we can create shared library (DLL/So) file to extend the RingVM without the need to rebuild it.
The Ring language source code comes with two files to add new modules to the RingVM, ring_ext.h and ring_ext.c

## ring_ext.h

The file ring_ext.h contains constants that we can change to include/exclude modules during the build process.

## ring_ext.c

The file ring_ext.c check constants defined in ring_ext.h before calling the start-up function in each module.
Each module contains a function that register the module functions in the RingVM.

## Module Organization

Each module starts by include the ring header file (ring.h). This files contains the Ring API that we can use to extend the RingVM.
Each module comes with a function to register the module functions in the RingVM The registration is done by using ring_vm_funcregister function.
The ring_vm_funcregister function takes two parameters, the first is the function name that will be used by Ring programs to call the function. The second parameter is the function pointer in the C program.
for example, the ring_vmmath.c module contains the next code to register the module functions
.. tip:: Remember that the function ring_vm_math_loadfunctions will be called by the ring_vm_extension function (in the ring_ext.c file).

## Function Structure

Each module function may contains the next steps
1 - Check Parameters Count
2 - Check Parameters Type
3 - Get Parameters Values
4 - Execute Code/Call Functions
5 - Return Value
The structure is very similar to any function (Input - Process - Output) But here we will use the Ring API for the steps 1,2,3 and 5.

## Check Parameters Count

We can check the parameters count using the RING_API_PARACOUNT macro.
We can compare RING_API_PARACOUNT with any numeric value using == or != operators.
Example:
Example:

## Display Error Message

We can display error messages using the RING_API_ERROR function.
The function will display the error and end the execution of the program.
.. note:: the behaviour of this function can be changed by the Ring code using Try/Catch/Done statements, so in your C code, use Return after this function.
Syntax:
The Ring API comes with some of predefined error messages that we can use

## Check Parameters Type

We can check the parameter type using the next functions
The output of these functions will be 1 (True) or 0 (False).

## Get Parameters Values

We can get paramters values using the next functions

## Return Value

We can return values from our function using the next functions.

## Function Prototype

When we define new function to be used for RingVM extension, we use the next prototype

## Sin Function Implementation

The next code represents the sin function implementation using the Ring API and the sin C function.

## Fopen and Fclose Functions Implementation

The next code represents the fopen function implementation using the Ring API and the fopen C Function.
The function takes two parameters, the first parameter is the file name as string. The second parameter is the mode as string.
In the file ring_vmfile.h we have some constants to use as the pointer type like
The function implementation in ring_vmfile.c
The next code represents the fclose function implementation
From fopen and fclose implementation we learned
1 - how to return C pointer using RING_API_RETCPOINTER function
2 - how to check if the parameter is a pointer using the RING_API_ISPOINTER function
3 - how to get C pointer value using the RING_API_GETCPOINTER function
4 - how to set the C pointer variable (in RingVM) to NULL using the RING_API_SETNULLPOINTER function

## Ring API - List Functions

In this section we will learn about the list functions provided by the Ring API to create new lists and manipulate the list items.

## Ring API - String Functions

In this section we will learn about the string functions provided by the Ring API to create new string and manipulate the string content.

## MySQL_Columns Function Implementation

The next code presents the MySQL_Columns function implementation.
This function returns table columns information.
Lists are of type List, in the previoud function we declared two pointers of type List using List *pList, *pList2;
.. note:: The function uses RING_API_NEWLIST to create new list instead of ring_list_new to create the list in Temp. Memory related to the function scope. This way we can return the list from the function. Also we don't delete the list, if it's stored in a variable by Ring Code it will be saved, if not it will be automatically deleted by RingVM.
The list can contains sub lists, we used the function ring_list_newlist to create a sublist.
The function ring_list_addstring is used to add string items to the list/sublist.
The function ring_list_adddouble is used to add numeric items to the list/sublist.
.. note:: All numeric items in lists returned from RingVM extension functions must be of type double and added to the list using ring_list_adddouble function.
We return the list from the extension function using the RING_API_RETLIST function.

## Dynamic/Shared Libraries (DLL/So) and LoadLib function

Instead of rebuilding the RingVM after writing new functions using C/C++ and the Ring API, we can create a DLL/So file and dynamically use the functions provided by this file in the runtime using the LoadLib function.
Dynamic library example in C
the idea is to create the ringlib_init function, this function will be called by the RingVM when we use the generated DLL file though the LoadLib function.
Inside the ringlib_init function we can register the module function or call a function that do the registration process for all of the module functions.
The next Ring code demonstrates how to use the DLL library during the runtime.
Output:

# Lessons/Embedding Ring Interpreter in C/C++ Programs
## Embedding Ring Interpreter in C/C++ Programs

We can call the Ring interpreter from C/C++ programs using the next functions

## Ring State

The idea is to use the ring_state_init to create new state for the Ring Interpreter then call the ring_state_runcode function to execut Ring code using the same state. When we are done, we call the ring_state_delete to free the memory.
Example:
Output:

## Ring State Functions

The Ring API comes with the next functions to create and delete the state. Also we have functions to create new variables and get variables values.

## Ring State Variables

We can create more than one ring state in the same program and we can create and modify variable values.
To get the variable list we can use the ring_state_findvar function.
To create new variable we can use the ring_state_newvar function.
Example:
Output:

# Lessons/Command Line Options
## Command Line Options

The ring interpreter takes source code file (*.ring) as input to execute, also the interpreter provide other options like

## Printing Tokens

Example:
Command:
Output:

## Printing Rules

Command:
Output:

## Printing Intermediate Code

Command:
Output:

## Printing Final Intermediate Code

Command:
Output:

## CGI Support

Command:

## No Run

Command:

## Printing Instruction Operation Code

Command:
Output:
.. tip:: Output removed from the previous example because it's very large!

## Performance

Command:
Output:

# Lessons/Web Development (CGI Library)
## Web Development (CGI Library)

In this chapter we will learn about developing Web applications using a CGI Library written in the Ring language.

## Ring CGI Hello World Program

The next program is the Hello World program

## Hello World Program using the Web Library

We can use the web library to write CGI Web applications quickly
Example (1) :
Example (2) :
.. tip:: the difference between ex. 1 and ex. 2 is using WebPage function to return the page object instead of creating the object using new statement.

## Web Library Features

The next features are provided by the Web library to quickly create web applications.
* Generate HTML pages using functions
* Generate HTML pages using objects
* HTTP Get
* HTTP Post
* Files Upload
* URL Encode
* Templates
* CRUD MVC Sample
* Users Logic & Registration Sample

## HTTP Get Example

The Page User Interface
Screen Shot:
The Response
Screen Shot:

## HTTP POST Example

The Page User Interface
Screen Shot:
The Response
Screen Shot:

## Upload Files

The Page User Interface
Screen Shot:
The Response
Screen Shot:

## Cookies

The Page User Interface
Screen Shot:
The Response
Screen Shot:

## URL Encode

The Page User Interface
Screen Shot:
Screen Shot:

## Templates

Using Templates we can write Ring code inside HTML files
Syntax:
The HTML Code
The Ring Code
Screen Shot:

## HTML Special Characters

The text function display HTML special characters.
If you want to write html code, use the html function.
Screen Shot:

## Hash Functions

The Page User Interface
Screen Shot:
The Response
Screen Shot:

## Random Image

Screen Shot:

## HTML Lists

The next example print a list contains numbers from 1 to 10
Then print a list from Ring List.
Finally we have a list of buttons and when we press on a button we get a message contains the clicked button number.
To start the list we uses the ulstart function.
To end the list we uses the ulend function.
We uses listart and liend to determine the list item.
Screen Shot:

## HTML Tables

In this example we will learn how to generate HTML tables using the tablestart, tableend, rowstart, rowend ,headerstart, headerend, cellstart and cellend functions.
Screen Shot:

## Gradient

In this example we will learn how to use the StyleGradient function.
The function takes the style number as input (range from 1 to 60).
Screen Shot:

## Generating Pages using Objects

Instead of using functions/methods to generate HTML pages, we can use an object for each element in the page.
This choice means more beautiful code but slower.
The fastest method is to print HTML code directly, then using functions then using templates then using objects (slower).
Screen Shot:

## Using Bootstrap Library using Functions

The next example uses the Bootstrap JavaScript Library when generating the HTML page.
Screen Shot:

## Using Bootstrap Library using Objects

The next example uses the Bootstrap JavaScript Library when generating the HTML page.
Instead of using functions to generate the HTML elements, we will use objects.
Screen Shot:

## CRUD Example using MVC

The next example uses the weblib.ring & datalib.ring.
The datalib.ring contains classes for creating database applications using MVC pattern.
In this example we create an object from the SalaryController class then call the Routing method.
We define the website variable to contains the basic url of the page.
When we create the SalaryModel class from the ModelBase class, the salary table will be opened and the columns data will be defined as attributes in the model class.
The SalaryView class create an object from the SalaryLanguageEnglish class to be used for translation.
The method AddFuncScript is used to call the form for adding/modifying record data.
The method FormViewContent is used to determine the controls in the form when we add or modify a record.
Screen Shot:

## Users registration and Login

We have the users classes (Model, View & Controller) to deal with the users data like username & email.
The next code is stored in ex25_users.ring
In the file ex25.ring we load ex25_users.ring then create an object from UsersController class.
Using the created object, we call the routing method.
Screen Shot:
See the next code for the registration page
Screen Shot:
The Registration response
See the next code for the Login page
Screen Shot:
The response page
The next code for checking if the user needs to login or not

## Database, ModelBase & ControllerBase classes

In this section we will see some code from datalib.ring
The next code presents the Database, ModelBase & ControllerBase classes

## WebLib API

In this section we will see the web library functions, classes and methods.
The Package System.Web contains the next classes

## Application Class

The method DecodeString is used to get HTTP request parameters.
The methods Decode and GetFileName are used for uploading files.
The methods SetCookie, Cookie & GetCookies are used for adding and reading cookies.
The methods StartHTML, ScriptsLibs, Style & Print are used for page structure and JS/CSS support.
The method URLEncode is used to encode a URL to be used in HTML pages.

## Page Class

aPara in the page methods is a list contains attributes and values. Using aPara we can set values for the next attributes

## ScriptFunctions Class

This class contains methods for adding JavaScript code to the generated web page.
The class methods are merged to the Page class, so we can use the next methods with page objects directly.

## StyleFunctions Class

This class contains methods for adding CSS to the generated web page.
Like ScriptFunctions Class, The StyleFunctions class methods are merged to the Page class, so we can use the next methods with page objects directly.

# Lessons/Code Generator for wrapping C/C++ Libraries
## Code Generator for wrapping C/C++ Libraries

In this chapter we will learn how to use the code generator to wrap C/C++ Libraries to use it in our Ring applications.

## Using the tool

The code generator program is parsec.ring that can be executed as any ring code using the ring interpreter.
for example to read a configuration file called test.cf to generate the source code file test.c run parsec.ring as in the next command

## Configuration file

The configuration file (*.cf) is the input file that we pass to the code generator. This file determine the functions prototypes that we need to use from a C/C++ library.
Writing configuration files is simple according to the next rules

## Using the function prototype

* To generate code that wraps a C function, we just write the C function prototype
Example:
The previous example will guide the code generator to generate five functions that wrap the al_create_display, al_destroy_display, al_get_new_display_flags, al_set_new_display_flags and al_get_new_display_option functions.
The generated code will be as in the next example
from the previous example we can see how much of time and effort is saved using the Code Generator.

## Adding code to the generated code

* To generate code directly type it between and
Example :
We use this feature when we need to do something without the help of the code generator. for example including header files and defining constants using Macro.

## Prefix for Functions Names

* To determine a prefix in all of the functions names type it between <funcstart> and </funcstart>
for example when we wrap the Allegro game programming library and we need all of the library functions to start with "al" we type the next code in the configuration file

## Generate function to wrap structures

* To generate functions that wrap structures (create/delete/get structure members)
just type the structures names between <struct> and </struct> also after the structure name you can type the structure members between { } separated by comma.
Example
from the previous example we will generate two function to create/delete the structure ALLEGRO_COLOR Also we will generate two functions to create/delete the structure ALLEGRO_EVENT and four functions to get the structure ALLEGRO_EVENT members (type, keyboard.keycode, mouse.x, mouse.y).

## Register New Functions

We can register functions by typing the function prototype between <register> and </register> We need this feature only when we don't provide the function prototype as input directly where we need to write the code of this function.
Example:
In the previous example we register the al_exit function. This function is not part of the Allegro Library, it's just an extra function that we need to add. Then the code if this function is written inside and . This function call the exit function from the C language library.

## Writing comments in the configuration file

* To type comments just type it between <comment> and </comment>
Example:

## Executing code during code generation

* To ask from the code generator to execute Ring code during reading the configuration file, just
write the code between <runcode> and </runcode>
Example:
The previoud line of code add the string "al_fixed" to the list aNumberTypes, This list contains types that can be considered as numbers when the code generator find it in the function prototype.

## Configuration file for the Allegro Library

The next configuration file enable us to use the Allegro library functions. The configuration file size is less than 1000 lines. when the code generator take this file as input the generated source code file in the C language will be 12000 lines of code!
We can see this configuration file as a complete example about using the code generator Also we can use it to know the functions that can be used from RingAllegro when you use it to create 2D games!
.. note:: we just provided part of the configuration file, for complete copy check the Ring source

## Threads Support

Next, another part of the configutaiton file, it's important because we can learn from it how to add threads to our Ring applications by using a threads library.
The idea is using ring_vm_mutexfunctions and ring_vm_runcodefromthread to execute Ring code.

## Code Generator Rules for Wrapping C++ Classes

* We can define classes between <class> and </class>
* Between <class> and <class> we set attributes like "name, nonew, para, parent, codename, passvmpointer and abstract"
* we set the attributes using the style attributename:value or attributename only if no values are required
* The "name" attribute determine the class name in C++ code and this name will be the default name in the Ring code
* The nonew instruction means that we don't need new/delete methods
* The parent attribute determine the parent class name
* The codename attribute determine another class name in C++ code
* The passvmpoint instruction means passing the Ring VM pointer to the class constructor when we create new objects, this happens when we set the codename attribute to a class the we will define and this class need the Virtual Machine pointer (for example to use it to execute Ring code from C++ code).
* The abstract instruction means that no new method is required for this class "no objects will be created".
* Using <nodllstartup> we can avoid #include "ring.h", We need this to write our startup code.
* Using <libinitfunc> we can change the function name that register the library functions
* Using <ignorecpointertype> we can ignore pointer type check
* Using the aStringTypes list when can defined new types that treated like const char *
* Using the aBeforeReturn list when can define code that is inserted after the variable name when we return that variable from a function
* Using the aNewMethodName list we can define another method name to be used in Ring code when we call the C++ method. this feature is required because some C++ method may be identical to Ring Keywords like "load","next","end" and "done".

## Using configuration file that wrap C++ Library

To run the code generator to generate code for using C++ library in the Ring application, we can do that as we did with using C libraries but here we will generate *.cpp file instead of *.c file. Also we will determine another file to be generated (*.ring). This file will contains classes in Ring code that wraps C++ functions for using C++ classes and objects.

## Configuration file for the Qt Framework

The next configuration file is used to wrap many Qt classes The configuration file is around 3500 lines and generate C++ code around 56000 lines and generate also Ring code around 9000 lines.
.. note:: Most of the content of the previous configuration file is removed from this documentation, for a complete version see the Ring source code distribution.

# Lessons/Graphics and 2D Games programming using RingAllegro
## Graphics and 2D Games programming using RingAllegro

In this chapter we will learn how to use the allegro game programming library in our Ring applications.
We have the file gamelib.ring that load the DLL library that contains wrappers for the Allegro functions
The file gamelib.ring uses the Load instruction to execute the file allegro.rh which is a ring source code file contains constants to be used in our programs. Then using the function LoadLib we can load the DLL library "ring_allegro.dll".
To write portable code we can change the gamelib.ring to check the platform before loading the DLL/So file.

## Drawing, Animation and Input

The next example uses the Allegro library for drawing, moving objects on the screen and getting input from the keyboard and the mouse.
.. note:: In the previous example we used the function callgc which is a Ring function to force calling the Garbage collector inside the While/End loop.
Program Output:
At first the program display a messagebox
Then we see two rectangles are moving on the screen
Then we see an image displayed on the screen
Finally we have one rectangle, and we see it moving all of the time on the screen but we can control it using the Mouse and/or the Keyborad

## Using TrueType Fonts

In this example we will see how to use TrueType Fonts *.ttf in our Games using Allegro
Screen Shot:

## Playing Sound Files

The next example play a sound file

## Scaling and Rotating Images

The next example display and rotate an image
Screen Shot:

## Display Transparent Image

The next example display image with white background on another image
Screen Shot:

## Using Threads

In this example we will learn how to users threads from the Allegro library
Output:

# Lessons/Desktop and Mobile development using RingQt
## Desktop and Mobile development using RingQt

In this chapter we will learn how to use the Qt framework classes
in our Ring applications to create Desktop and Mobile Applications.

## The First GUI Application

In this example we will create an application to ask the user about his/her name. When the user type the name in the textbox then click on "Say Hello" button, the textbox value will be updated by adding "Hello " to the name.
Program Output:
At first we type the name in the textbox
Then we click on the say hello button

## Using Layout

The next example is just an upgrade to the previous application to use the vertical layout.
The application during the runtime!

## Using the QTextEdit Class

In this example we will use the QTextEdit Class
During the runtime we can paste rich text in the qtextedit widget

## Using the QListWidget Class

In this example we will use the QListWidget Class
The application during the runtime

## Using QTreeView and QFileSystemModel

In this example we will learn how to use the QTreeView widget to represent the File System
The application during the runtime

## Using QTreeWidget and QTreeWidgetItem

In this example we will learn about using the QTreeWidget and QTreeWidgetItem classes
The application during the runtime

## Using QComboBox Class

In this example we will learn about using the QComboBox class
The application during the runtime

## Creating Menubar

In this example we will learn about using the QMenuBar class
The application during the runtime

## Creating Toolbar

In this example we will learn about using the QToolBar class
The application during the runtime

## Creating StatusBar

In this example we will learn about using the QStatusBar class
The application during the runtime

## Using QDockWidget

In this example we will learn about using the QDockWidget class
The application during the runtime

## Using QTabWidget

In this example we will learn about using the QTabWidget class
The application during the runtime

## Using QTableView

In this example we will learn about using the QTableView class
The application during the runtime

## Using QProgressBar

In this example we will learn about using the QProgressBar class
The application during the runtime

## Using QSpinBox

In this example we will learn about using the QSpinBox class
The application during the runtime

## Using QSlider

In this example we will learn about using the QSlider class
The application during the runtime

## Using QDateEdit

In this example we will learn about using the QDateEdit class
The application during the runtime

## Using QDial

In this example we will learn about using the QDial class
The application during the runtime

## Using QWebView

In this example we will learn about using the QWebView class
The application during the runtime

## Using QCheckBox

In this example we will learn about using the QCheckBox class
The application during the runtime

## Using QRadioButton and QButtonGroup

In this example we will learn about using the QRadioButton and QButtonGroup classes
The application during the runtime

## Adding Hyperlink to QLabel

In this example we will learn about creating Hyperlink using the QLabel class
The application during the runtime

## QVideoWidget and QMediaPlayer

In this example we will learn about using the QVideoWidget and QMediaPlayer classes to play a group of movies from different positions at the same time
The application during the runtime

## Using QFrame

In this example we will learn about using the QFrame class
The application during the runtime

## Display Image using QLabel

In this example we will learn about displaying an image using the QLabel widget
The application during the runtime

## Menubar and StyleSheet Example

In this example we will learn about creating menubar and setting the window stylesheet
The application during the runtime

## QLineEdit Events and QMessageBox

In this example we will learn about using QLineEdit Events and displaying a Messagebox
The application during the runtime

## Other Widgets Events

Each Qt signal can be used in RingQt, just add Set before the signal name and add event after the signal name to get the method that can be used to determine the event code.
For example the QProgressBar class contains a signal named valueChanged To use it just use the function setValueChangedEvent
Example:
The application during the runtime
Another example for the stateChanged event of the QCheckBox class
The application during the runtime

## Using the QTimer Class

In this example we will learn about using the QTimer class
The application during the runtime

## Using the QFileDialog Class

Example
The application during the runtime

## Drawing using QPainter

In this example we will learn about drawing using the QPainter class
The application during the runtime

## Printing using QPrinter

In this example we will learn how to print to PDF file using QPrinter

## Creating More than one Window

The next example demonstrates how to create more than one window
The application during the runtime

## Playing Sound

Example:

## Color Dialog

Example:
The application during the runtime

## Using qLCDNumber Class

In this example we will learn about using the qLCDNumber class
The application during the runtime

## Movable Label Example

The application during the runtime

## QMessagebox Example

In this section we will learn how to check the output of the Message box
The application during the runtime

## Using QInputDialog Class

In the next example we will learn about using the QInputDialog class
The application during the runtime

## KeyPress and Mouse Move Events

In this example we will learn how to use the Events Filter to know about KeyPress and Mouse Move Events
The application during the runtime

## Moving Objects using the Mouse

In the next example we will learn how to program movable objects where the user can move a label
The application during the runtime

## Inheritance from GUI Classes

Example :
The application during the runtime

## Using QDesktopWidget Class

In the next example we will learn about using the QDesktopWidget class
The application during the runtime

## Simple Client and Server Example

In this section we will learn about creating simple Client and Server Application
The application during the runtime

## Notepad Application

In the next example we will see simple Notepad developed using the RingQt
The application during the runtime
The next screen shot demonstrates the "File" menu
The next window for "search and replace"
The next screen shot demonstrates the application main window
.. Note:: the functions pDebug, pRun and pRunNoConsole in the previous sample are not portable! They are written in this sample for MS-Windows and we can update them for other operating systems.

## The Cards Game

In the next example we will see a simple Cards game developed using RingQt
Each player get 5 cards, the cards are unknown to any one. each time one player click on one card to see it. if the card is identical to another card the play get point for each card. if the card value is "5" the player get points for all visible cards.
The application during the runtime
.. note:: in the previous screen shot the player get the card number '5' but his score is not increased because he opened this card while no other cards are visible!
The next screen shot while running the game using a Mobile (Android)
.. note:: using Qt we can run the same application on other Mobile systems