Squirrel Standard Library 1.0

Alberto Demichelis

This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.

2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original

software.

3. This notice may not be removed or altered from any source distribution.


Table of Contents

1. Introduction
2. The Input/Output library
Squirrel API
Global symbols
File object
C API
Initialization
File object
Script loading and serialization
3. The Blob library
Squirrel API
Global symbols
The blob object
C API
Initialization
Blob object
4. The Math library
Squirrel API
Global symbols
C API
Initialization
5. The System library
Squirrel API
Global symbols
C API
Initialization
6. The String library
Squirrel API
Global symbols
Regexp object
C API
Initialization
Regular Expessions
7. The Aux library
C API
Error handling
Index

Chapter 1. Introduction

The squirrel standard libraries consist in a set of modules implemented in C++. While are not essential for the language, they provide a set of useful services that are commonly used by a wide range of applications(file I/O, regular expressions, etc...), plus they offer a foundation for developing additional libraries.

All libraries are implemented through the squirrel API and the ANSI C runtime library. The modules are organized in the following way:

  • I/O : input and output

  • blob : binary buffers manipilation

  • math : basic mathematical routines

  • system : system access function

  • string : string formatting and manipulation

The libraries can be registered independently,except for the IO library that depends from the bloblib.

Chapter 2. The Input/Output library

the input lib implements basic input/output routines.

Squirrel API

Global symbols

dofile(path);

compiles a squirrel script or loads a precompiled one and executes it. returns the value returned by the script or null if no value is returned.

fopen(filename, mode);

opens or create a file and retuns it as file object

filename is the absolute or realtive path of the file, mode is the access mode. This string is exactly what is used in the standard C function fopen.

loadfile(path);

compiles a squirrel script or loads a precompiled one an returns it as as function.

stderr

File object bound on the os standard error stream

stdin

File object bound on the os standard input stream

stdout

File object bound on the os standard output stream

File object

The file object is bla bla bla

eos();

returns a non null value if the read/write pointer is at the end of the stream.

flush();

flushes the stream.return a value != null if succeded, otherwise returns null

len();

returns the lenght of the stream

readblob(size);

read n bytes from the stream and retuns them as blob

readn(type);

reads a number from the stream according to the type pameter. type can have the following values:

'i'32bits numberreturns an integer
's'16bits signed integerreturns an integer
'w'16bits unsigned integerreturns an integer
'c'8bits signed integerreturns an integer
'b'8bits unsigned integerreturns an integer
'f'32bits floatreturns an float
'd'64bits floatreturns an float

readstr(size, [encoding]);

reads n characters from the stream and returns it as string. if encoding is omitted the function read an 8bit string. encoding can have the following values:

'a'8bits character string
'u'16bits character string

seek(seek, [origin]);

Moves the read/write pointer to a specified location. offset indicates the number of bytes from origin. origin can be 'b' beginning of the stream,'c' current location or 'e' end of the stream. If origin is omitted the parameter is defaulted as 'b'(beginning of the stream).

tell();

returns read/write pointer absolute position

writeblob(blob);

writes a blob in the stream

writen(n, type);

writes a number in the stream formatted according to the type pameter. type can have the following values:

'i'32bits number
's'16bits signed integer
'w'16bits unsigned integer
'c'8bits signed integer
'b'8bits unsigned integer
'f'32bits float
'd'64bits float

writestr(str, [encoding]);

writes a string in the stream str is the string that as to be written, encoding is and optional parameter that can have the following values:

'a'8bits character string
'u'16bits character string

if encoding is omitted the default value is 'a'.

C API

Initialization

sqstd_register_iolib

SQRESULT sqstd_register_iolib(HSQUIRRELVM v);

initialize and register the io library in the given VM.

parameters:
HSQUIRRELVM v

the target VM

return:

an SQRESULT

remarks:

The function aspects a table on top of the stack where to register the global library functions.

File object

sqstd_createfile

SQRESULT sqstd_createfile(HSQUIRRELVM v, SQFILE file, int own);

creates a file object bound to the SQFILE passed as parameter and pushes it in the stack

parameters:
HSQUIRRELVM v

the target VM

SQFILE file

the stream that will be rapresented by the file object

int own

if different than 0 the stream will be automatically closed when the newly create file object is destroyed.

return:

an SQRESULT

sqstd_getfile

SQRESULT sqstd_getfile(HSQUIRRELVM v, int idx, SQFILE * file);

retrieve the pointer of a stream handle from an arbitrary position in the stack.

parameters:
HSQUIRRELVM v

the target VM

int idx

and index in the stack

SQFILE * file

A pointer to a SQFILE handle that will store the result

return:

an SQRESULT

Script loading and serialization

sqstd_loadfile

SQRESULT sqstd_loadfile(HSQUIRRELVM v, const SQChar * filename, int printerror);

compiles a squirrel script or loads a precompiled one an pushes it as closure in the stack.

parameters:
HSQUIRRELVM v

the target VM

const SQChar * filename

path of the script that has to be loaded

int printerror

if different than zero the compiler error handler will be called if a error occurs.

return:

an SQRESULT

sqstd_dofile

SQRESULT sqstd_dofile(HSQUIRRELVM v, const SQChar * filename, int retval, int printerror);

Compiles a squirrel script or loads a precompiled one and executes it. Optionally pushes the return value of the executed script in the stack.

parameters:
HSQUIRRELVM v

the target VM

const SQChar * filename

path of the script that has to be loaded

int retval

if different than zero the function will push the return value of the executed script in the stack.

int printerror

if different than zero the compiler error handler will be called if a error occurs.

return:

an SQRESULT

remarks:

the function aspects a table on top of the stack that will be used as 'this' for the execution of the script.

eg.
sq_pushroottable(v); //push the root table(were the globals of the script will are stored)
sqstd_dofile(v, _SC("test.nut"), 0, 1);// also prints syntax errors if any 
				
sqstd_writeclosuretofile

SQRESULT sqstd_writeclosuretofile(HSQUIRRELVM v, const SQChar * filename);

serializes the closure at the top position in the stack as bytecode in the file specified by the paremeter filename. If a file with the same name already exists, it will be overwritten.

parameters:
HSQUIRRELVM v

the target VM

const SQChar * filename

path of the script that has to be loaded

return:

an SQRESULT

Chapter 3. The Blob library

The blob library implements binary data manipulations routines. The library is based on blob objects that rapresent a buffer of arbitrary binary data.

Squirrel API

Global symbols

blob(size);

returns a new blob object of the specified size in bytes

castf2i(f);

casts a float to a int

casti2f(n);

casts a int to a float

swap2(n);

swap the byte order of a number (like it would be a 16bits integer)

swap4(n);

swap the byte order of an integer

swapfloat(f);

swaps the byteorder of a float

The blob object

The blob object is a buffer of arbitrary binary data. The object behaves like a file stream, it has a read/write pointer and it automatically grows if data is written out of his boundary.
A blob can also be accessed byte by byte through the [] operator.

eos();

returns a non null value if the read/write pointer is at the end of the stream.

flush();

flushes the stream.return a value != null if succeded, otherwise returns null

len();

returns the lenght of the stream

readblob(size);

read n bytes from the stream and retuns them as blob

readn(type);

reads a number from the stream according to the type pameter. type can have the following values:

'i'32bits numberreturns an integer
's'16bits signed integerreturns an integer
'w'16bits unsigned integerreturns an integer
'c'8bits signed integerreturns an integer
'b'8bits unsigned integerreturns an integer
'f'32bits floatreturns an float
'd'64bits floatreturns an float

readstr(size, [encoding]);

reads n characters from the stream and returns it as string. if encoding is omitted the function read an 8bit string. encoding can have the following values:

'a'8bits character string
'u'16bits character string

resize(size);

resizes the blob to the specified size

seek(seek, [origin]);

Moves the read/write pointer to a specified location. offset indicates the number of bytes from origin. origin can be 'b' beginning of the stream,'c' current location or 'e' end of the stream. If origin is omitted the parameter is defaulted as 'b'(beginning of the stream).

swap2();

swaps the byte order of the blob content as it would be an array of 16bits integers

swap4();

swaps the byte order of the blob content as it would be an array of 32bits integers

tell();

returns read/write pointer absolute position

writeblob(blob);

writes a blob in the stream

writen(n, type);

writes a number in the stream formatted according to the type pameter. type can have the following values:

'i'32bits number
's'16bits signed integer
'w'16bits unsigned integer
'c'8bits signed integer
'b'8bits unsigned integer
'f'32bits float
'd'64bits float

writestr(str, [encoding]);

writes a string in the stream str is the string that as to be written, encoding is and optional parameter that can have the following values:

'a'8bits character string
'u'16bits character string

if encoding is omitted the default value is 'a'.

C API

Initialization

sqstd_register_bloblib

SQRESULT sqstd_register_bloblib(HSQUIRRELVM v);

initialize and register the blob library in the given VM.

parameters:
HSQUIRRELVM v

the target VM

return:

an SQRESULT

remarks:

The function aspects a table on top of the stack where to register the global library functions.

Blob object

sqstd_getblob

SQRESULT sqstd_getblob(HSQUIRRELVM v, int idx, SQUserPointer * ptr);

retrieve the pointer of a blob's payload from an arbitrary position in the stack.

parameters:
HSQUIRRELVM v

the target VM

int idx

and index in the stack

SQUserPointer * ptr

A pointer to the userpointer that will point to the blob's payload

return:

an SQRESULT

sqstd_getblobsize

int sqstd_getblobsize(HSQUIRRELVM v, int idx);

retrieve the size of a blob's payload from an arbitrary position in the stack.

parameters:
HSQUIRRELVM v

the target VM

int idx

and index in the stack

return:

the size of the blob at idx position

sqstd_createblob

SQUserPointer sqstd_createblob(HSQUIRRELVM v, int size);

creates a blob with the given payload size and pushes it in the stack.

parameters:
HSQUIRRELVM v

the target VM

int size

the size of the blob payload that has to be created

return:

a pointer to the newly created blob payload

Chapter 4. The Math library

the math lib provides basic mathematic routines. The library mimics the C runtime library implementation.

Squirrel API

Global symbols

abs(x);

returns the absolute value of x as integer

acos(x);

returns the arccosine of x

asin(x);

returns the arcsine of x

atan(x);

returns the arctangent of x

atan2(x, y);

returns the arctangent of y/x.

ceil(x);

returns a float value representing the smallest integer that is greater than or equal to x

cos(x);

returns the cosine of x

exp(x);

returns the exponential value of the float parameter x

fabs(x);

returns the absolute value of x as float

floor(x);

returns a float value representing the largest integer that is less than or equal to x

log(x);

returns the natural logarithm of x

log10(x);

returns the logarithm base-10 of x

pow(x, y);

returns x raised to the power of y.

rand();

returns a pseudorandom integer in the range 0 to RAND_MAX

sin(x);

returns the sine of x

sqrt(x);

returns the square root of x

srand(seed);

sets the starting point for generating a series of pseudorandom integers

tan(x);

returns the tangent of x

PI

The numeric constant pi (3.141592) is the ratio of the circumference of a circle to its diameter

RAND_MAX

the maximum value that can be returned by the rand() function

C API

Initialization

sqstd_register_mathlib

SQRESULT sqstd_register_mathlib(HSQUIRRELVM v);

initialize and register the math library in the given VM.

parameters:
HSQUIRRELVM v

the target VM

return:

an SQRESULT

remarks:

The function aspects a table on top of the stack where to register the global library functions.

Chapter 5. The System library

The system library exposes operating system facilities like environment variables, date time manipulation etc..

Squirrel API

Global symbols

clock();

returns a float representing the number of seconds elapsed since the start of the process

date([time], [format]);

returns a table containing a date/time splitted in the slots:

secSeconds after minute (0 - 59).
minMinutes after hour (0 - 59).
hourHours since midnight (0 - 23).
dayDay of month (1 - 31).
monthMonth (0 - 11; January = 0).
yearYear (current year).
wdayDay of week (0 - 6; Sunday = 0).
ydayDay of year (0 - 365; January 1 = 0).

if time is omitted the current time is used.
if format can be 'l' local time or 'u' UTC time, if omitted is defaulted as 'l'(local time).

getenv(varaname);

Returns a string containing the value of the environment variable varname

remove(path);

deletes the file specified by path

rename(oldname, newname);

renames the file or directory specified by oldname to the name given by newname

system(cmd);

executes the string cmd through the os command interpreter.

time();

returns the number of seconds elapsed since midnight 00:00:00, January 1, 1970.

the result of this function can be formatted through the faunction date

C API

Initialization

sqstd_register_systemlib

SQRESULT sqstd_register_systemlib(HSQUIRRELVM v);

initialize and register the system library in the given VM.

parameters:
HSQUIRRELVM v

the target VM

return:

an SQRESULT

remarks:

The function aspects a table on top of the stack where to register the global library functions.

Chapter 6. The String library

the string lib implements string formatting and regular expression matching routines.

Squirrel API

Global symbols

format(formatstr, ...);

Returns a string formatted according formatstr and the optional parameters following it. The format string follows the same rules as the printf family of standard C functions( the "*" is not supported).

eg.
sq> print(format("%s %d 0x%02X\n","this is a test :",123,10));
this is a test : 123 0x0A

					

regexp(pattern);

compiles a regular expression pattern and returns it as a new regexp object.

\ Quote the next metacharacter
^ Match the beginning of the string
. Match any character
$ Match the end of the string
| Alternation
(subexp) Grouping (creates a capture)
(?:subexp) No Capture Grouping (no capture)
[] Character class

GREEDY CLOSURES. 

* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times

ESCAPE CHARACTERS. 

\t tab (HT, TAB)
\n newline (LF, NL)
\r return (CR)
\f form feed (FF)

PREDEFINED CLASSES. 

\l lowercase next char
\u uppercase next char
\a letters
\A non letters
\w alphanumeric [_0-9a-zA-Z]
\W non alphanumeric [^_0-9a-zA-Z]
\s space
\S non space
\d digits
\D non nondigits
\x exadecimal digits
\X non exadecimal digits
\c control charactrs
\C non control charactrs
\p punctation
\P non punctation
\b word boundary
\B non word boundary

Regexp object

The regexp object rapresent a precompiled regular experssion pattern. The object is created trough the function regexp().

capture(str, [start]);

returns an array of tables containing two indexs("begin" and "end")of the first match of the regular expression in the string str. An array entry is created for each captured sub expressions. If no match occurs returns null. The search starts from the index start of the string, if start is omitted the search starts from the beginning of the string.

the first element of the returned array(index 0) always contains the complete match.

 
local ex = regexp(@"(\d+) ([a-zA-Z]+)(\p)");
local string = "stuff 123 Test;";
local res = ex.capture(string);
foreach(i,val in res)
{
	print(format("match number[%02d] %s\n",
			i,string.slice(val.begin,val.end))); //prints "Test"
}

...
will print
match number[00] 123 Test;
match number[01] 123
match number[02] Test
match number[03] ;
				
				

match(str);

returns a value different than null if the regular expression matches the string str, otherwise returns null.

search(str, [start]);

returns a table containing two indexs("begin" and "end") of the first match of the regular expression in the string str, otherwise if no match occurs returns null. The search starts from the index start of the string, if start is omitted the search starts from the beginning of the string.

 
local ex = regexp("[a-zA-Z]+");
local string = "123 Test;";
local res = ex.search(string);
print(string.slice(res.begin,res.end)); //prints "Test"
				
				

C API

Initialization

sqstd_register_stringlib

SQRESULT sqstd_register_stringlib(HSQUIRRELVM v);

initialize and register the string library in the given VM.

parameters:
HSQUIRRELVM v

the target VM

return:

an SQRESULT

remarks:

The function aspects a table on top of the stack where to register the global library functions.

Regular Expessions

sqstd_rex_compile

SQRex * sqstd_rex_compile(const SQChar * pattern, const SQChar ** error);

compiles an expression and returns a pointer to the compiled version. in case of failure returns NULL.The returned object has to be deleted through the function sqstd_rex_free().

parameters:
const SQChar * pattern

a pointer to a zero terminated string containing the pattern that has to be compiled.

const SQChar ** error

a pointer to a string pointer that will be set with an error string in case of failure.

return:

a pointer to the compiled pattern

sqstd_rex_free

void sqstd_rex_free(SQRex * exp);

deletes a expression structure created with sqstd_rex_compile()

parameters:
SQRex * exp

the expression structure that has to be deleted

sqstd_rex_match

SQRexBool sqstd_rex_match(SQRex * exp, const SQChar * text);

returns SQRex_True if the string specified in the parameter text is an exact match of the expression, otherwise returns SQRex_False.

parameters:
SQRex * exp

the compiled expression

const SQChar * text

the string that has to be tested

return:

SQRex_True if successful otherwise SQRex_False

sqstd_rex_search

SQRexBool sqstd_rex_search(SQRex * exp, const SQChar * text, const SQChar ** out_begin, const SQChar ** out_end);

searches the first match of the expressin in the string specified in the parameter text. if the match is found returns SQRex_True and the sets out_begin to the beginning of the match and out_end at the end of the match; otherwise returns SQRex_False.

parameters:
SQRex * exp

the compiled expression

const SQChar * text

the string that has to be tested

const SQChar ** out_begin

a pointer to a string pointer that will be set with the beginning of the match

const SQChar ** out_end

a pointer to a string pointer that will be set with the end of the match

return:

SQRex_True if successful otherwise SQRex_False

sqstd_rex_searchrange

SQRexBool sqstd_rex_searchrange(SQRex * exp, const SQChar * text_begin, const SQChar * text_end, const SQChar ** out_begin, const SQChar ** out_end);

searches the first match of the expressin in the string delimited by the parameter text_begin and text_end. if the match is found returns SQRex_True and the sets out_begin to the beginning of the match and out_end at the end of the match; otherwise returns SQRex_False.

parameters:
SQRex * exp

the compiled expression

const SQChar * text_begin

a pointer to the beginnning of the string that has to be tested

const SQChar * text_end

a pointer to the end of the string that has to be tested

const SQChar ** out_begin

a pointer to a string pointer that will be set with the beginning of the match

const SQChar ** out_end

a pointer to a string pointer that will be set with the end of the match

return:

an SQRESULT

sqstd_rex_getsubexpcount

int sqstd_rex_getsubexpcount(SQRex * exp);

returns the number of sub expressions matched by the expression

parameters:
SQRex * exp

the compiled expression

return:

the number of sub expressions matched by the expression

sqstd_rex_getsubexp

int sqstd_rex_getsubexp(SQRex * exp, int n, SQRexMatch * subexp);

retrieve the begin and and pointer to the length of the sub expression indexed by n. The result is passed trhough the struct SQRexMatch.

parameters:
SQRex * exp

the compiled expression

int n

the index of the submatch(0 is the complete match)

SQRexMatch * subexp

a pointer to structure that will store the result

return:

the function returns SQRex_True if n is valid index otherwise SQRex_False.

Chapter 7. The Aux library

Table of Contents

C API
Error handling

The aux library implements default handlers for compiler and runtime errors and a stack dumping.

C API

Error handling

sqstd_seterrorhandlers

void sqstd_seterrorhandlers(HSQUIRRELVM v);

initialize compiler and runtime error handlers, the handlers use the print function set through(sq_setprintfunc) to output the error.

parameters:
HSQUIRRELVM v

the target VM

sqstd_printcallstack

void sqstd_printcallstack(HSQUIRRELVM v);

print the call stack and stack contents.the function uses the print function set through(sq_setprintfunc) to output the stack dump.

parameters:
HSQUIRRELVM v

the target VM

Index

S

search, Regexp object
seek, File object, The blob object
sin, Global symbols
sqrt, Global symbols
sqstd_createblob, Blob object
sqstd_createfile, File object
sqstd_dofile, Script loading and serialization
sqstd_getblob, Blob object
sqstd_getblobsize, Blob object
sqstd_getfile, File object
sqstd_loadfile, Script loading and serialization
sqstd_printcallstack, Error handling
sqstd_register_bloblib, Initialization
sqstd_register_iolib, Initialization
sqstd_register_mathlib, Initialization
sqstd_register_stringlib, Initialization
sqstd_register_systemlib, Initialization
sqstd_rex_compile, Regular Expessions
sqstd_rex_free, Regular Expessions
sqstd_rex_getsubexp, Regular Expessions
sqstd_rex_getsubexpcount, Regular Expessions
sqstd_rex_match, Regular Expessions
sqstd_rex_search, Regular Expessions
sqstd_rex_searchrange, Regular Expessions
sqstd_seterrorhandlers, Error handling
sqstd_writeclosuretofile, Script loading and serialization
srand, Global symbols
stderr, Global symbols
stdin, Global symbols
stdout, Global symbols
swap2, Global symbols, The blob object
swap4, Global symbols, The blob object
swapfloat, Global symbols
system, Global symbols