Part II - Library Routines

1. Introduction

 
A large number of library routines are provided. Some are built right into the interpreter, ex.exe, exw.exe or exu. Others are written in Euphoria and you must include one of the .e files in euphoria\include to use them. Where this is the case, the appropriate include file is noted in the "Syntax" part of the description. Of course an include file need only be included once in your program. The editor displays in magenta those routines that are built into the interpreter, and require no include file. You can override the definition of these built-in routines by defining your own routine with the same name. You will get a suppressible warning if you do this.

To indicate what kind of object may be passed in and returned, the following prefixes are used:

x - a general object (atom or sequence)
s - a sequence
a - an atom
i - an integer
fn - an integer used as a file number
st - a string sequence, or single-character atom
dt - a datetime sequence
m - a map for key/value pairs

Some routines are only available on one or two of the four platforms. This is noted with "Platform: DOS32" or "Platform: WIN32" or "Platform: Linux" in the description of the routine, and with (DOS32) or (WIN32) or (Linux) in some other places. Things that work on Linux can generally be assumed to work on FreeBSD. The only exception is the mouse routines.

A run-time error message will usually result if an illegal argument value is passed to any of these routines.



2. Application Areas

Type Checking - Test variables for a certain type
Sequence Manipulation - Work with sequences
Searching and Sorting - Search and sort sequences
Math - Simple and advanced math functions
Bitwise Logic Operations - Functions that will treat numbers as a collection of binary bits
File and Device I/O - Input/output on file's and standard in/out/err
Mouse Support - Text based mouse support
Operating System - Functions to work with the operating system
Debugging - Profile and tracing support function
Graphics & Sound - Text and Pixel graphic routines
Machine Level Interface - Allows you to access the machine at a low-level
Dynamic Calls - Allows you to call procedures and functions using a unique integer instead of by name
C Interface - Enables you to call C code written in DLL or so files
Map (hash table) - Manage key/value data types
Date and Time - Get, add, subtract, convert and format date and time values
Multitasking - Create multiple, independent tasks
EDS (Euphoria Database) - Flexible Euphoria-oriented database for storing data



2.1 Type Checking

As well as declaring variables with these types, you can also call them just like ordinary functions, in order to test if a value is a certain type.

integer - test if an object is an integer
atom - test if an object is an atom
sequence - test if an object is a sequence
object - test if an object is an object (always true)
isalnum - test if an atom is an alphanumeric character
isalpha - test if an atom is an alpha character
isascii - test if an atom is an ascii character
iscntrl - test if an atom is a control character
isdigit - test if an atom is a digit
isgraph - test if an atom is a printable character not including space
islower - test if an atom is a lower case character
isprint - test if an atom is a printable character including space
ispunct - test if an atom is a punctuation character
isspace - test if an atom is a space
isupper - test if an atom is an upper case character
isxdigit - test if an atom is a valid hex digit



2.2 Sequence Manipulation

length - return the length of a sequence
repeat - repeat an object n times to form a sequence of length n
reverse - reverse a sequence
append - add a new element to the end of a sequence
prepend - add a new element to the beginning of a sequence
insert - insert one sequence into another
remove - remove an item from a sequence
remove_range - remove a range of items from a sequence
replace - replace a range of items with a new item or sequence
head - return the first n items of st with bounds checking
mid - return from n1 n2 number of items of st with bounds checking
slice - return from n1 to n2 of st with bounds checking
tail - return the last n items of st with bounds checking
split - split a sequence by a sequence
split_adv - advanced split that will allow setting a limit and split type
join - join a sequence by another sequence
trim - remove a set of atoms from the beginning and end of a sequence
trim_head - remove a set of atoms from the beginning of a sequence
trim_tail - remove a set of atoms from the end of a sequence
pad_head - pad the beginning of a sequence with an atom up to x in overall length
pad_tail - pad the end of a sequence with an atom up to x in overall length
chunk - split a sequence into smaller sequences of x size
flatten - remove all nesting from a sequence
vslice - perform a vertical slice on a sequence
lower - convert an atom or sequence to lower case
upper - convert an atom or sequence to upper case



2.3 Searching and Sorting

compare - compare two objects
equal - test if two objects are identical
find - find an object in a sequence - start searching from element number 1
find_from - find an object in a sequence - start searching from any element number
find_any - find any element in needle in haystack - start searching from element number 1
find_any_from - find any element in needle in haystack - start searching from any element number
find_all - return a sequence of positions where the given atom exists in the given sequence
find_replace - find and replace needle in haystack with the given sequence
match - find a sequence as a slice of another sequence - start searching from element number 1
match_from - find a sequence as a slice of another sequence - start searching from any element number
match_all - return a sequence of positions where the given needle starts in the given haystack
wildcard_match - match a pattern containing ? and * wildcards
wildcard_file - match a file name against a wildcard specification
sort - sort the elements of a sequence into ascending order
custom_sort - sort the elements of a sequence based on a compare function that you supply



2.4 Math

These routines can be applied to individual atoms or to sequences of values. See Part I - Core Language - Operations on Sequences.

sqrt - calculate the square root of an object
set_rand - set the random number generator so it will generate a repeatable series of random numbers
rand - generate random numbers
rand_range - generate a random number within a given range
sin - calculate the sine of an angle
arcsin - calculate the angle with a given sine
cos - calculate the cosine of an angle
arccos - calculate the angle with a given cosine
tan - calculate the tangent of an angle
arctan - calculate the arc tangent of a number
atan2 - calculate the arctangent of y/x
deg2rad - convert angle as degrees to an angle as radians
rad2deg - convert angle as radians to an angle as degrees
log - calculate the natural logarithm
log10 - calculate the base 10 logarithm
floor - round down to the nearest integer
ceil - round up to the nearest integer
round - rounds's elements to the nearest integer
round_to - rounds's elements to the given precision
remainder - calculate the remainder when a number is divided by another
power - calculate a number raised to a power
exp - calculate E to the n'th power
sign - test an objects signness
abs - return the absolute value
average - compute the average item in a sequence
sum - add all items in a sequence
max - find the maximum item in a sequence
min - find the minumum item in a sequence
PI - the mathematical value PI (3.141592653589793238)
E - base of the natural logarithm (2.718281828459045235)



2.5 Bitwise Logical Operations

These routines treat numbers as collections of binary bits, and logical operations are performed on corresponding bits in the binary representation of the numbers. There are no routines for shifting bits left or right, but you can achieve the same effect by multiplying or dividing by powers of 2.

and_bits - perform logical AND on corresponding bits
or_bits - perform logical OR on corresponding bits
xor_bits - perform logical XOR on corresponding bits
not_bits - perform logical NOT on all bits



2.6 File and Device I/O

To do input or output on a file or device you must first open the file or device, then use the routines below to read or write to it, then close the file or device. open() will give you a file number to use as the first argument of the other I/O routines. Certain files/devices are opened for you automatically (as text files):

0 - standard input
1 - standard output
2 - standard error
Unless you redirect them on the command-line, standard input comes from the keyboard, standard output and standard error go to the screen. When you write something to the screen it is written immediately without buffering. If you write to a file, your characters are put into a buffer until there are enough of them to write out efficiently. When you close() or flush() the file or device, any remaining characters are written out. Input from files is also buffered. When your program terminates, any files that are still open will be closed for you automatically.
Note:
If a program (written in Euphoria or any other language) has a file open for writing, and you are forced to reboot your computer for any reason, you should immediately run scandisk to repair any damage to the file system that may have occurred.
open - open a file or device
close - close a file or device
flush - flush out buffered data to a file or device
lock_file - lock a file or device
unlock_file - unlock a file or device
read_file - read an entire file from an open file handle or from a given filename
read_lines - read all lines from an open file handle or from a given filename
write_file - write sequence to a named file or file handle
write_lines - write all lines from a sequence to a named file or file handle
print - print a Euphoria object on one line, with braces and commas {,,} to show the structure
pretty_print - print a Euphoria object in a nice readable form, using multiple lines and appropriate indentation
? x - shorthand for print(1, x)
sprint - return a printed Euphoria object as a string sequence
printf - formatted print to a file or device
sprintf - formatted print returned as a string sequence
puts - output a string sequence to a file or device
getc - read the next character from a file or device
gets - read the next line from a file or device
get_bytes - read the next n bytes from a file or device
prompt_string - prompt the user to enter a string
get_key - check for key pressed by the user, don't wait
wait_key - wait for user to press a key
get - read the representation of any Euphoria object from a file
prompt_number - prompt the user to enter a number
value - read the representation of any Euphoria object from a string
seek - move to any byte position within an open file
where - report the current byte position in an open file
pathinfo - return path information about a filename (dir, filename, extension)
dirname - return the directory name of a fully qualified filename
filename - return the filename of a fully qualified filename
fileext - return the extension of a filename
current_dir - return the name of the current directory
chdir - change to a new current directory
dir - return complete info on all files in a directory
walk_dir - recursively walk through all files in a directory
allow_break - allow control-c/control-Break to terminate your program or not
check_break - check if user has pressed control-c or control-Break
PATHSEP - the platform's path separator
NL - the platform's newline terminator (\n, \r\n)



2.7 Mouse Support (DOS32 and Linux)

Note: On Windows XP, if you want the DOS mouse to work in a (non-full-screen) window, you must disable QuickEdit mode in the Properties for the DOS Window.
get_mouse - return mouse "events" (clicks, movements)
mouse_events - select mouse events to watch for
mouse_pointer - display or hide the mouse pointer



2.8 Operating System

time - number of seconds since a fixed point in the past
tick_rate - set the number of clock ticks per second (DOS32)
date - current year, month, day, hour, minute, second etc.
command_line - command-line used to run this program
getenv - get value of an environment variable
system - execute an operating system command line
system_exec - execute a program and get its exit code
abort - terminate execution
sleep - suspend execution for a period of time
platform - find out which operating system are we running on



2.9 Debugging

trace - dynamically turns tracing on or off
profile - dynamically turns profiling on or off



2.10 Graphics & Sound

The following routines let you display information on the screen. In DOS, the PC screen can be placed into one of many graphics modes. See the top of include\graphics.e for a description of the modes. There are two basic types of graphics mode available. Text modes divide the screen up into lines, where each line has a certain number of characters. Pixel-graphics modes divide the screen up into many rows of dots, or "pixels". Each pixel can be a different color. In text modes you can display text only, with the choice of a foreground and a background color for each character. In pixel-graphics modes you can display lines, circles, dots, and also text. Any pixels that would be off the screen are safely clipped out of the image.

For DOS32 we've included a routine for making sounds on your PC speaker. To make more sophisticated sounds, get the Sound Blaster library developed by Jacques Deschenes. It's available on the Euphoria Web page.

The following routines work in all text and pixel-graphics modes:

clear_screen - clear the screen
position - set cursor line and column
get_position - return cursor line and column
graphics_mode - select a new pixel-graphics or text mode (DOS32)
video_config - return parameters of current mode
scroll - scroll text up or down
wrap - control line wrap at right edge of screen
text_color - set foreground text color
bk_color - set background color
palette - change color for one color number (DOS32)
all_palette - change color for all color numbers (DOS32)
get_all_palette - get the palette values for all colors (DOS32)
read_bitmap - read a bitmap (.bmp) file and return a palette and a 2-d sequence of pixels
save_bitmap - create a bitmap (.bmp) file, given a palette and a 2-d sequence of pixels
get_active_page - return the page currently being written to (DOS32)
set_active_page - change the page currently being written to (DOS32)
get_display_page - return the page currently being displayed (DOS32)
set_display_page - change the page currently being displayed (DOS32)
sound - make a sound on the PC speaker (DOS32)

The following routines work in text modes only:

cursor - select cursor shape
text_rows - set number of lines on text screen
get_screen_char - get one character from the screen
put_screen_char - put one or more characters on the screen
save_text_image - save a rectangular region from a text screen
display_text_image - display an image on the text screen

The following routines work in pixel-graphics modes only (DOS32):

pixel - set color of a pixel or set of pixels
get_pixel - read color of a pixel or set of pixels
draw_line - connect a series of graphics points with a line
polygon - draw an n-sided figure
ellipse - draw an ellipse or circle
save_screen - save the screen to a bitmap (.bmp) file
save_image - save a rectangular region from a pixel-graphics screen
display_image - display an image on the pixel-graphics screen



2.11 Machine Level Interface

We've grouped here a number of routines that you can use to access your machine at a low-level. With this low-level machine interface you can read and write to memory. You can also set up your own 386+ machine language routines and call them.

Some of the routines listed below are unsafe, in the sense that Euphoria can't protect you if you use them incorrectly. You could crash your program or even your system. Under DOS32, if you reference a bad memory address it will often be safely caught by the CauseWay DOS extender, and you'll get an error message on the screen plus a dump of machine-level information in the file cw.err. Under WIN32, the operating system will usually pop up a termination box giving a diagnostic message plus register information. Under Linux you'll typically get a segmentation violation.

Note:
To assist programmers in debugging code involving these unsafe routines, we have supplied safe.e, an alternative to machine.e. If you copy euphoria\include\safe.e into the directory containing your program, and you rename safe.e as machine.e in that directory, your program will run using safer (but slower) versions of these low-level routines. safe.e can catch many errors, such as poking into a bad memory location. See the comments at the top of safe.e for instructions on how to use it and how to configure it optimally for your program.

These machine-level-interface routines are important because they allow Euphoria programmers to access low-level features of the hardware and operating system. For some applications this is essential.

Machine code routines can be written by hand, or taken from the disassembled output of a compiler for C or some other language. Pete Eberlein has written a "mini-assembler" for use with Euphoria. See the Archive. Remember that your machine code will be running in 32-bit protected mode. See demo\callmach.ex for an example.

peek - read one or more bytes from memory
peeks - read one or more signed bytes from memory
peek2s - read 2-byte signed values from memory
peek2u - read 2-byte unsigned values from memory
peek4s - read 4-byte signed values from memory
peek4u - read 4-byte unsigned values from memory
peek_string - read a sequence of text from a null terminated string from memory
poke - write one or more bytes to memory
poke2 - write 2-bye values into memory
poke4 - write 4-byte values into memory
mem_copy - copy a block of memory
mem_set - set a block of memory to a value
call - call a machine language routine
dos_interrupt - call a DOS software interrupt routine (DOS32)
allocate - allocate a block of memory
free - deallocate a block of memory
allocate_low - allocate a block of low memory (address less than 1Mb) (DOS32)
free_low - free a block allocated with allocate_low (DOS32)
allocate_string - allocate a string of characters with 0 terminator
register_block - register an externally-allocated block of memory
unregister_block - unregister an externally-allocated block of memory
get_vector - return address of interrupt handler (DOS32)
set_vector - set address of interrupt handler (DOS32)
lock_memory - ensure that a region of memory will never be swapped out (DOS32)
int_to_bytes - convert an integer to 4 bytes
bytes_to_int - convert 4 bytes to an integer
int_to_bits - convert an integer to a sequence of bits
bits_to_int - convert a sequence of bits to an integer
atom_to_float64 - convert an atom, to a sequence of 8 bytes in IEEE 64-bit floating-point format
atom_to_float32 - convert an atom, to a sequence of 4 bytes in IEEE 32-bit floating-point format
float64_to_atom - convert a sequence of 8 bytes in IEEE 64-bit floating-point format, to an atom
float32_to_atom - convert a sequence of 4 bytes in IEEE 32-bit floating-point format, to an atom
use_vesa - force the use of the VESA graphics standard (DOS32)
crash - cause a crash with a given message
crash_file - specify the file for writing error diagnostics if Euphoria detects an error in your program.
crash_message - specify a message to be printed if Euphoria detects an error in your program
crash_routine - specify a routine to be called if Euphoria detects an error in your program
machine_func - specialized internal operations with a return value
machine_proc - specialized internal operations with no return value



2.12 Dynamic Calls

These routines let you call Euphoria procedures and functions using a unique integer known as a routine identifier, rather than by specifying the name of the routine.

routine_id - get a unique identifying number for a Euphoria routine
call_proc - call a Euphoria procedure using a routine id
call_func - call a Euphoria function using a routine id



2.13 Calling C Functions (WIN32 and Linux)

See platform.doc for a description of WIN32 and Linux programming in Euphoria.

open_dll - open a Windows dynamic link library (.dll file) or Linux shared library (.so file)
define_c_proc - define a C function that is VOID (no value returned), or whose value your program will ignore
define_c_func - define a C function that returns a value that your program will use
define_c_var - get the memory address of a C variable.
c_proc - call a C function, ignoring any return value
c_func - call a C function and get the return value
call_back - get a 32-bit machine address for a Euphoria routine for use as a call-back address
message_box - pop up a small window to get a Yes/No/Cancel response from the user
free_console - delete the console text window
instance - get the instance handle for the current program



2.14 Map

An object that maintains mapping from keys to values. No duplicate keys are allowed, so each key can only map to one value. When including map.e, a new type is available, map. It will be used throughout the documentation.

new - create a new map
has - does the map contain a certain key?
get - get the value of the specified key from the map
put - put a new entry into the map
remove - remove an entry from the map
size - get the number of entries in the map
keys - return all keys as a sequence
values - return all values as a sequence



2.15 Datetime

new - Create a new datetime value
now - Create a new datetime value populated with the current date and time
format - Format a date according to a format string
from_date - Create a new datetime value a date() value
dow - Return the day of week for a give datetime value
doy - Return the Julian day of year for a give datetime value
to_unix - Convert a datetime value to the unix numeric format (seconds since EPOCH)
from_unix - Create a new datetime value from the unix numeric format (seconds since EPOCH)
add - Add an interval to a datetime value
subtract - Subtract an intervalue from a datetime value
diff - Caluclate the seconds different between two dates

Constants to aid in accessing datetime value contents and working with the add and subtract functions:

YEAR - Constant for accessing the Year of a datetime value
MONTH - Constant for accessing the Month of a datetime value
DAY - Constant for accessing the Day of a datetime value
HOUR - Constant for accessing the Hour of a datetime value
MINUTE - Constant for accessing the Minute of a datetime value
SECOND - Constant for accessing the Second of a datetime value
SECONDS - Interval key for adding seconds to a datetime value
MINUTES - Interval key for adding minutes to a datetime value
HOURS - Interval key for adding hours to a datetime value
DAYS - Interval key for adding days to a datetime value
WEEKS - Interval key for adding weeks to a datetime value
MONTHS - Interval key for adding months to a datetime value
YEARS - Interval key for adding years to a datetime value



2.16 Multitasking

This collection of routines lets you create multiple, independent tasks. Each task has its own current statement being executed, its own subroutine call stack, and its own set of private variables. The local and global variables of a program are shared amongst all tasks. When a task calls task_yield(), it is suspended, and the Euphoria scheduler decides which task to execute next.

The Language War demo program, lw.ex, makes heavy use of tasks to create a simulated battle involving numerous independently moving ships, torpedos, phasors etc. See also the taskwire.exw Windows demo program, and the news.exu demo for Linux and FreeBSD.

task_clock_start - restart the scheduler's clock
task_clock_stop - stop the scheduler's clock
task_create - create a new task
task_list - get a list of all tasks
task_schedule - schedule a task for execution
task_self - return the task id of the current task
task_status - the current status (active, suspended, terminated) of a task
task_suspend - Suspend a task.
task_yield - Yield control, so the scheduler can pick a new task to run.

2.17 EDS Database Routines

db_create - create a new database
db_open - open an existing database
db_select - select a database to be the current one
db_close - close a database
db_create_table - create a new table within a database
db_select_table - select a table to be the current one
db_rename_table - rename a table
db_delete_table - delete a table
db_table_list - get a list of all the table names in a database
db_table_size - get the number of records in the current table
db_find_key - quickly find the record with a certain key value
db_record_key - get the key portion of a record
db_record_data - get the data portion of a record
db_insert - insert a new record into the current table
db_delete_record - delete a record from the current table
db_replace_data - replace the data portion of a record
db_compress - compress a database
db_dump - print the contents of a database
db_fatal_id - handle fatal database errors