SGScript documentation - v0.9.5

Table of Contents


SGScript - description

This is a programming language that is made to be fast, accessible and simple.

include "math";

gradient = [ ".", "o", "O", "#", "O", "o", "." ];

for( y = -7; y <= 7; ++y )
{
    for( x = -7; x <= 7; ++x )
    {
        dst = sqrt( x * x + y * y ) * 0.9;
        if( dst > 6 )
            dst = 6;
        chr = gradient[ dst ];
        print chr $ ' ';
    }
    println();
}

It is similar to many but the exact combination makes it unique in comparison to others. Thus, it might be best to describe it in comparison to others, especially the ones that heavily influenced the development of SGScript.

languagewhat it DOESN'T have in comparison to SGScript
Cdynamic typing, built-in serialization
Luabuilt-in serialization, C-like syntax, proper indexing, arrays, ...
PHPconsistency, lightweight design
JavaScriptenvironmental awareness, determinism, built-in serialization, ...
PythonC-like syntax, lightweight design

With this in mind, technologies get upgraded occasionally, thus be sure to take this comparison with a grain of salt and recheck it and perhaps even report the factual errors along with the version number that marked the introduction of changes.

However, SGScript has all of the things mentioned, and some more, possibly making it one of the most balanced languages ever created.

The language supports:

The standard library includes:


Code samples - SGScript

Statements

print "Text";
println( "!" );
b = rand();

Comments

// this is a comment that ends with the line

/* this type of comment
   can be more than
   one line long
*/

Basic calculations

a = 1, b = 2, c = 5;
d = a + b * c - b / a;
a += 3.14;
c = "eye" $ "sight" // stitch (concatenate) strings together!
d = "Ocean's " $ 11;

Comparison

if( c > 5 )
    print "as expected";
y = x <= 8.8; // result of comparison can be assigned!

Useful shortcuts

a += 1; // short for a = a + 1
a++;    // short for a += 1
a--;
a = if( b > 5, 10, 20 ); // short for if( b > 5 ){ a = 10; } else { a = 20; }

Flow control

if( a > b )
{
    print "something happens only if a is greater than b";
}
else
    print "...and here the opposite is true";

while( a > b )
{
    print "something happens as long as a is greater than b";
    a--; // but not for too long, as we see
}
// or maybe ...
do
{   // first we do
    print a;
}
while( a++ < 10 ); // then we check

More useful shortcuts

for( i = 0; i < 10; i++ )
    print i;
// .. is the short form for ..
i = 0;
while( i < 10 )
{
    print i;
    i++;
}
for(;;) // this is not going to stop...
    print "x";

More flow control

x = 5;
for(;;)
{
    print x;
    x--;
    if( x < 0 )
        break; // this says that we don't want to continue staying in the loop
}
// << this is where "break" leads us, right after the loop

// this goes through a list
foreach( fruit : [ "apple", "orange", "banana" ] )
    println( fruit );

// .. of 2 items ..
list = { "1" = "apple", "2" = "orange", "3" = "banana" };
foreach( number, fruit : list )
    println( number $ ". " $ fruit );

Functions

// cornerstore of reusable code
function square( x )
{
    return x * x;
}
print square( 5 );

function print_quoted( text )
{
    print '"' $ text $ '"';
}
print_quoted( "It works!" );

Objects

a = [ 1, 2, "three" ];
a[2] = 3;
a[1]++;

d = {
    name = "test",
    text = "hello",
};
d.name = "test, edited";
d.text $= ", world!";
println( d.text ); // hello, world!

Interesting stuff

printvar( x ); // tells you all you want to know about "x"

// emits an error with the given message if the first argument is false
assert( x > 5, "x must be greater than 5" );

// returns the type name
typeof( x );

// universal external code loader
include "math", "string", "something";

Code samples - the C API

Primary operations

// create the context
sgs_Context* C = sgs_CreateEngine();

// load the built-in math library
sgs_LoadLib_Math( C );

// load a file
sgs_ExecFile( C, "script.sgs" );

// call a global function with 0 arguments, expecting 0 values returned
sgs_GlobalCall( C, "myFunction", 0, 0 );

// destroy the context
sgs_DestroyEngine( C );

Data in, data out

sgs_Context* C = sgs_CreateEngine();
sgs_LoadLib_Math( C );

// push a variable on the stack
sgs_PushReal( C, 3.14 );

// call a global function with 1 argument, expecting 1 value returned
sgs_GlobalCall( C, "sin", 1, 1 );

// check the returned value
printf( "returned value: %f\n", sgs_GetReal( C, -1 ) );

// clean the stack
sgs_SetStackSize( C, 0 );

Language reference


Variable types

SGScript has 8 primary variable types:

Extended variable types (built on object):


Conversion rules

from \ toboolintrealstringptr
nullfalse00.0"null"NULL
bool-0/10.0/1.0"false"/"true"NULL/0x1
int0 => false, otherwise true---cast
real0.0 => false, otherwise trueround to nearest-sprintf %gcast
stringempty => false, otherwise true*1*1-char*
functrue00.0"function"NULL
cfunctrue00.0"C function"NULL
object *2true00.0"object"data ptr.
ptrNULL => false, otherwise truecastcastsprintf ptr(%p)-


Code structure

Code can contain constants, identifiers, expressions and statements. Statements usually include expressions but expressions can also include statements, specifically - function expressions.


Constants

Available constant formats:

typesubtypeexamples
null-null
bool-true, false
intdecimal1413, -583, 0
intbinary0b0101, 0b11
intoctal0o644, 0o1, 0o77
inthexadecimal0x1f, 0xCA5
realbasic0.14, -25.48
realscientific1.5e-5, 1e+10
stringnormal"text", '1\n2'
stringunescaped*"""text""", '''1\2'''

*) unescaped strings don't parse their contents at all, and the ending markers (""" or ''') cannot be escaped


Identifiers

Identifiers can contain letters (a-z, A-Z), numbers (0-9) or underscores ("_") but they cannot begin with a number.

Special keywords and hardcoded constants:

nametypeusage
thisspecial identifier, read-onlymethod context retrieval
_Gspecial identifier, read/writeglobal environment access
nullconstantconstant
trueconstantconstant
falseconstantconstant
varrestricted keywordvariable declaration
globalrestricted keywordvariable declaration
functionrestricted keywordfunction definition
userestricted keywordfunction definition
ifrestricted keyword"if" statement
elserestricted keyword"if/else" statement
dorestricted keyword"do/while" statement
whilerestricted keyword"while", "do/while" statements
forrestricted keyword"for" statement
foreachrestricted keyword"foreach" statement
breakrestricted keyword"break" statement
continuerestricted keyword"continue" statement
returnrestricted keyword"return" statement


Expressions

Expressions can be categorized in many different ways: type of action, appearance, whether it also assigns the value somewhere or if its purpose has a special meaning.

There are 5 types of action for expressions in SGScript: arithmetic, binary, boolean, comparison and special.

expressionappearancetype of actionassign# in.
add A + B arithmeticno2
subtract A - B arithmeticno2
multiply A * B arithmeticno2
divide A / B arithmeticno2
modulo A % B arithmeticno2
pre-increment ++ A arithmeticself1
pre-decrement -- A arithmeticself1
post-increment A ++ arithmeticself1
post-decrement A -- arithmeticself1
add-assign A += B arithmeticyes2
subtract-assign A -= B arithmeticyes2
multiply-assign A *= B arithmeticyes2
divide-assign A /= B arithmeticyes2
modulo-assign A %= B arithmeticyes2
binary AND A & B binaryno2
binary OR A | B binaryno2
binary XOR A ^ B binaryno2
left shift A << B binaryno2
right shift A >> B binaryno2
binary AND-assign A &= B binaryyes2
binary OR-assign A |= B binaryyes2
binary XOR-assign A ^= B binaryyes2
left shift-assign A <<= B binaryyes2
right shift-assign A >>= B binaryyes2
binary invert ~ A binaryno1
boolean AND A && B booleanno2
boolean OR A || B booleanno2
boolean AND-assign A &&= B booleanyes2
boolean OR-assign A ||= B booleanyes2
boolean invert ! A booleanno1
less than A < B comparisonno2
less than or equal A <= B comparisonno2
greater than A > B comparisonno2
greater than or equal A >= B comparisonno2
equal A == B comparisonno2
not equal A != B comparisonno2
strict equality A === B comparisonno2
strict inequality A !== B comparisonno2
raw comparison A <=> B comparisonno2
error suppression @ A specialno1
declare-local var A specialmaybeany
declare-global global A specialmaybeany
array literal [ A, B, .. ] specialnoany
dict. literal {A=1,B=2,..} specialnoany
assign A = B specialyes1
concatenate A $ B specialno2
concatenate-assign A $= B specialyes2
property A . B specialmaybe2
index A [ B ] specialmaybe2
multi-index-assign A[]<dict.lit>specialyesany
multi-property-assign A.<dict.lit> specialyesany
function call A ([B,..]) specialno<=256
comp. function call O!A ([B,..]) specialno<=256
function definition function A.. specialmaybe0
inline if if(A,B,C) specialno3(2)
subexpression ( A[, ..] ) specialmaybeany

Some notes on the special cases:

compatible function call / inheritance call / global method call ( O!A ([B,..]) )

CFC is created to encourage users to reduce memory usage without sacrificing clarity of code. It is a short-hand, optimized version of the .call method / sys_call function for callables.

Properties:

Example WITHOUT:

function create_object()
{
    object = { x = 0, y = 0 };
    function object.move( x, y ){ this.x = x; this.y = y; @this.move_callback(); }
    function object.tick( delta ){ this.move( this.x + delta, this.y ); }
    return object;
}

Example WITH:

function Object_Move( x, y ){ this.x = x; this.y = y; @this.move_callback(); }
function create_object()
{
    object = { x = 0, y = 0 };
    function object.tick( delta ){ this!Object_Move( this.x + delta, this.y ); }
    return object;
}

Now, by itself it may not mean much, however let's see what happens if the following code is used:

for( i = 0; i < 100; ++i )
    objects.push( create_object() );

Without the usage of a global method, there's a key 'move' in each object that points to the function. In real software there may be no less than 10 such keys in many instances of many objects. And if there are no overrides planned for it, there's no need for it to be there but we can't really move it. Classes are an option that involves a few more allocations and it requires more memory to use them. Using .call/sys_call or replacing this with an argument would sacrifice readability and the option to relocate functions, as well as performance, this being a double call. This is where CFC comes in - syntax allows to clearly state the object and function used, and the required interface for the object to be compatible with said function.


Statements

There are 4 statement types in SGScript:

Container statements

There are two types of container statements: expression statements and block statements.

Format:

Examples:

a = 5;
a = 1, b = 2;

Flow control statements

These statements decide which code gets executed when. They include loops (while, for, foreach, do/while), the if/else construct, break/continue/return.

Formats:

Examples:

if( a )
{
    print( "a is true" );
}
else
    print( "a is not true" );

while( b > 0 ) b--;

Declaration statements

Statements that begin with "var", "global" or "function" declare and set variables.

Examples:

var x = 5, y = 6, z;
global World = null;
function fn(){ INFO( "'fn' was called" ); }

Function call statements

These statements are converted directly to function calls. Currently, 'include' and 'print' functions are available as statements.

Formats:

Examples:

include "io", "string";
print "Count: ", count;

Built-in accessors

There are several built-in accessors for the variable types that are available.

namevariable typeaccessor typedescription
lengthstringpropertyreturns the length of the string, in bytes
char. atstringindexreturns the character from the specified position
callany callablepropertyfunction that allows to specify "this" for the call


Common constructs in SGScript

This section shows some ways of implementing various often-used constructs in SGScript. Some of them (specifically the constructs coming from compiled languages) do not map directly to any set of native features and are considered solutions of lower quality.


Basic classes

global SampleClass = {}; // create a placeholder type dictionary

function SampleClass.SampleMethod( a, b ) // this is the name that will show up in debug output
{
    return a + b + this.c; // usage of "this" turns the function into a method
}

function SampleClass.SampleFunction( a, b )
{
    return a + b;
}

// Function will show up as "<anonymous>" in debug output, so avoid this kind of function declaration if possible
SampleClass.SampleAnonymous = function( a, b )
{
    return a + b + this.c;
}; // <-- the semicolon is required for this notation

// Giving functions a specific name:
function MyCustomFunction( a, b )
{
    return a + b + this.c; // note that it is still possible to use "this"
}
SampleClass.Sample = MyCustomFunction;

SampleClass.StaticVariable = 5;

// class instantiation without custom data
myclass = class( {}, SampleClass );

// class instantiation with custom data
CustomData = { c = 5, d = 6 };
mydataclass = class( CustomData, SampleClass );

// static construction function
function SampleClass.Create( x )
{
    data = { c = x };
    return class( data, SampleClass );
}

// make class interface into a construction function
function SampleClass.__call( x )
{
    return SampleClass.Create( x );
}
SampleClass = class( null, SampleClass );
// Be aware that this method involves some runtime overhead.
// Prefer simply giving the construction function (or the interface variable) a different name:
function createSampleClass( x )
{
    data = { c = x };
    return class( data, SampleClass );
}

// destructor
function SampleClass.__destruct()
{
    this.c = null;
}

// many more special methods are available for 'class' objects

Inheritance

// class A - base class
global A = {};
function A.func()
{
    println( "base" );
}
function A.create()
{
    return class( {}, A );
}

// class B - inherits from A
global B = {};
function B.func()
{
    // needless to say, this is not the preferred way to do software design in SGScript
	this._super._super.func.call( this );
    println( "override" );
}
A.func_A = A.func; // make a duplicate entry that will not be overridden
// it is usually preferred to make the duplicates near the original entries where they're expected to be overridden
function B.func()
{
    B.func_A(); // call that entry instead of the original, obstructed entry 
    println( "override" );
}
function B.create()
{
    return class( {}, class( B, A ) );
}

Game entities

With game entities and objects of similar structure (just about any object) it is easier to simply define it as a key-value data map, without any classes, inheritance or anything of that kind. The nature of a dynamically typed scripting engine implies that almost everything is checked at runtime, making emulation of compiled language constructs pointless.

entity =
{
    x = 10,
    y = 20,
};

function entity.tick( dt )
{
    this.x += dt;
}

Numeric string parsing rules

">>>" means "until any other symbol has been found" (the text is too dense for exact repetition)

The string is not a number if no numeric characters (0-9) could be parsed. (for example, "+" isn't a number but "0x" is)


C API reference

The interface that it defines is one of the driving forces of SGScript. It is heavily influenced by Lua, while also adding some features of PHP (Zend Engine) and Python.

The most important difference is in error handling and triggers: errors detected in C can easily be non-fatal. Just like with PHP, minor errors are emitted as warnings that also propagate invalid (null) values throughout the system to effectively disable the subsequent calls and notify whoever is interested of the exact trail of errors. Furthermore, this behavior can be modified by using protected calls (pcall function) in SGScript and custom messaging callbacks in C.

The virtual machine supports:


Constants and types

This part of the documentation describes the various types and definitions used in the C API.


Main types

Return types:

Virtual machine / language types:

System types:

Interface types:


Error codes

These are the default meanings for error codes that are honored throughout the API.


Variable types

-- SGS_VT_[NULL|BOOL|INT|REAL|STRING|FUNC|CFUNC|OBJECT|PTR]


Constant registration types


Concepts & systems


Messaging system

Messages are combinations of importance code and a null-terminated string that holds the message itself. The messaging system's purpose generally is to notify about problems and allow handling them to some extent.

The C API has a function for sending messages - sgs_Msg - and two for dealing with the current callback - sgs_SetMsgFunc / sgs_GetMsgFunc.

The sgs_Msg function basically generates the full string from the format string and calls the callback that is currently set. Due to the data association and accessibility, various systems can be implemented on top of it:

Logging

All messages can simply be logged. For the most simple approach, the sgs_StdOutputFunc callback can be used with any FILE* for the data pointer.

A limited amount of exception handling

This system can be used to break out of any point in SGS code up until the last C function. For this, pcall can be used together with a callback that calls sys_abort when necessary.

Debugging

On each warning or error, debugging code can be triggered. It can be an interactive console debugger (as implemented in ext/sgs_idbg), it could also be code that dumps the relevant state and sends it to the developer.

Hidden data collection

Similarly to exception handling, pcall can be used also for gathering messages otherwise skipped by the system. The sub-zero importance range is generally hidden - there's 2^31 values to use to mark special messages - however, sys_replevel or sgs_Cntl with SGS_CNTL_(SET_)MINLEV must be used to enable that range.


Iterator system

Iterators are objects that enable sequential, ordered traversal of object contents, allowing to read up to 2 variables at each position: the key and the value.

The C API has several functions used to deal with iterators. There are essentially three kinds of functions: initialization ( sgs_PushIterator(P), sgs_GetIterator(P) ), advancing ( sgs_IterAdvance(P) ) and data retrieval ( sgs_IterPushData(P), sgs_IterGetData(P) ).

Iterator starts at the pre-first position (-1 in terms of indices), so nothing can be read initially, before the first advance. This allows to implement iterator handling with rather simple code:

initialize;
while( advance > 0 )
{
    retrieve key and/or value;
    ..do something else..;
}
free;

A more real example follows:

// assuming iterable object is at the top of the stack
sgs_PushIterator( C, -1 );
while( sgs_IterAdvance( C, -1 ) > 0 )
{
    sgs_StackIdx ssz = sgs_StackSize( C );
    
    sgs_IterPushData( C, -1, 1, 1 ); // push both key and value
    
    sgs_SetStackSize( C, ssz ); // restore stack to have iterator at -1 again
}
sgs_Pop( C, 1 ); // pop the iterator

Another example using pointers:

sgs_Variable iterator, iterable, key, value;
// .. assuming iterable is initalized here ..
sgs_GetIteratorP( C, &iterable, &iterator );
while( sgs_IterAdvanceP( C, &iterator ) > 0 )
{
    sgs_IterGetDataP( C, &iterator, NULL, &value );
    // .. use value ..
    sgs_Release( C, &value );
    
    sgs_IterGetDataP( C, &iterator, &key, &value );
    // .. use key and value ..
    sgs_Release( C, &key );
    sgs_Release( C, &value );
}
sgs_Release( C, &iterator );
// .. release the iterable or not, depending on how it was initialized ..

Garbage collection system

The garbage collector currently implemented is a basic stop-the-world mark-and-sweep algorithm that goes over all objects and recursively marks them as available.

The marking is done on the variable named redblue, which contains 0 or 1 and in all avaiable objects is synced with the same variable for the context. On each pass, the bit is flipped for all available objects, so all objects that didn't have the bit flipped can be safely removed.

The garbage collector is invoked with sgs_GCExecute in the C API and gc_collect in SGScript.

Sub-objects are marked as available in the GCMARK callback with sgs_GCMark(Array) / sgs_ObjGCMark functions.


Classes

Classes are objects that enable operator/interface overloading and two-layer index retrieval.

Overloadable operators/interfaces:

Two-layer index retrieval is simply trying to read the index from a different source if the first source fails to come up with something. In other languages, metatable and prototype is the name of a table that is the second source. This allows to avoid storing functions and other data that is equal to all instances of some object type.


Closures

Closures are a combination of one callable and some variables. They are meant to simplify interfaces and code around places where it was important for functions to have access to call-invariant (same on every call) data.

Closures can be created from both SGScript and the C API, though both options have their limitations.

Closure stack in the C API is technically very similar to main stack, with one important difference - functions do not accept negative indices.


Functions


Context management


Memory management


Input / output


Code handling


Introspection


Execution control


Binding helpers


Object type storage


Variable initialization


Stack primary interface


Sub-item usage


Argument handling


Virtual machine operations


String helpers


Closure handling


Data retrieval & conversion


Iterators


Variable ownership


String32 optimization interface


Utility functions


ALL functions (A-Z)


sgs_CreateEngine [function alias]

sgs_Context* sgs_CreateEngine()

returns a new scripting engine context


sgs_CreateEngineExt [function]

sgs_Context* sgs_CreateEngineExt( sgs_MemFunc memfunc, void* mfuserdata )

returns a new scripting engine context, attached to the specified allocator


sgs_DestroyEngine [function]

sgs_DestroyEngine( sgs_Context* C )

destroys the passed context and frees all memory associated to it


sgs_ExecString [function alias]

SGSRESULT sgs_ExecString( sgs_Context* C, const char* str )

compiles and executes a string of text

error codes


sgs_ExecBuffer [function alias]

SGSRESULT sgs_ExecBuffer( sgs_Context* C, const char* buf, sgs_SizeVal size )

compiles and executes a buffer of text or bytecode

error codes


sgs_EvalString [function alias]

SGSRESULT sgs_EvalString( sgs_Context* C, const char* str, int* rvc )

compiles and executes a string of text, optionally leaving the return values on stack and returning the number of values via rvc

error codes


sgs_EvalBuffer [function]

SGSRESULT sgs_EvalBuffer( sgs_Context* C, const char* buf, sgs_SizeVal size, int* rvc )

compiles and executes a buffer of text or bytecode, optionally leaving the return values on stack and returning the number of values via rvc

error codes


sgs_ExecFile [function alias]

SGSRESULT sgs_ExecFile( sgs_Context* C, const char* filename )

compiles and executes a file containing script text or bytecode

error codes


sgs_EvalFile [function]

SGSRESULT sgs_EvalFile( sgs_Context* C, const char* filename, int* rvc )

compiles and executes a file containing script text or bytecode, optionally leaving the return values on stack and returning the number of values via rvc

error codes


sgs_Include [function alias]

SGSBOOL sgs_Include( sgs_Context* C, const char* name )

includes an item by the specified name, returning if completed successfully


sgs_IncludeExt [function]

SGSBOOL sgs_IncludeExt( sgs_Context* C, const char* name, const char* searchpath )

includes an item by the specified name, optionally looking in the places specified by the search path, returning if completed successfully


sgs_Compile [function]

SGSRESULT sgs_Compile( sgs_Context* C, const char* buf, size_t size, char** outbuf, size_t* outsize )

compile a buffer of SGScript code, returning the compiled code buffer on success

error codes


sgs_DumpCompiled [function]

SGSRESULT sgs_DumpCompiled( sgs_Context* C, const char* buf, size_t size )

dump compiled bytecode or SGScript code buffer to stdout

error codes


sgs_LoadLib_*** [functions]

SGSRESULT sgs_LoadLib_Fmt( sgs_Context* C )

SGSRESULT sgs_LoadLib_IO( sgs_Context* C )

SGSRESULT sgs_LoadLib_Math( sgs_Context* C )

SGSRESULT sgs_LoadLib_OS( sgs_Context* C )

SGSRESULT sgs_LoadLib_RE( sgs_Context* C )

SGSRESULT sgs_LoadLib_String( sgs_Context* C )

loads the library into the specified context

error codes


sgs_Reg***Consts [function]

SGSRESULT sgs_RegFuncConsts( sgs_Context* C, const sgs_RegFuncConst* list, int size )

SGSRESULT sgs_RegIntConsts( sgs_Context* C, const sgs_RegIntConst* list, int size )

SGSRESULT sgs_RegRealConsts( sgs_Context* C, const sgs_RegRealConst* list, int size )

loads the specified list of constants in the context

error codes


sgs_Init*** [functions]

void sgs_InitNull( sgs_Variable* out )

void sgs_InitBool( sgs_Variable* out, sgs_Bool value )

void sgs_InitInt( sgs_Variable* out, sgs_Int value )

void sgs_InitReal( sgs_Variable* out, sgs_Real value )

void sgs_InitStringBuf( sgs_Context* C, sgs_Variable* out, const char* str, sgs_SizeVal size )

void sgs_InitString( sgs_Context* C, sgs_Variable* out, const char* str )

void sgs_InitCFunction( sgs_Variable* out, sgs_CFunc func )

void sgs_InitObject( sgs_Context* C, sgs_Variable* out, void* data, sgs_ObjInterface* iface )

void* sgs_InitObjectIPA( sgs_Context* C, sgs_Variable* out, sgs_SizeVal added, sgs_ObjInterface* iface )

void sgs_InitPtr( sgs_Variable* out, void* ptr )

void sgs_InitObjectPtr( sgs_Variable* out, sgs_VarObj* obj )


sgs_InitArray [function]

SGSRESULT sgs_InitArray( sgs_Context* C, sgs_Variable* out, sgs_SizeVal numitems )

creates an array at out from numitems last items on the stack, pops those items

error codes


sgs_InitDict [function]

SGSRESULT sgs_InitDict( sgs_Context* C, sgs_Variable* out, sgs_SizeVal numitems )

creates a dict at out from numitems last items on the stack, pops those items

error codes


sgs_InitMap [function]

SGSRESULT sgs_InitMap( sgs_Context* C, sgs_Variable* out, sgs_SizeVal numitems )

creates a map at out from numitems last items on the stack, pops those items

error codes


sgs_Push*** [functions]

void sgs_PushNull( sgs_Context* C )

void sgs_PushBool( sgs_Context* C, sgs_Bool value )

void sgs_PushInt( sgs_Context* C, sgs_Int value )

void sgs_PushReal( sgs_Context* C, sgs_Real value )

void sgs_PushStringBuf( sgs_Context* C, const char* str, sgs_SizeVal size )

void sgs_PushString( sgs_Context* C, const char* str )

void sgs_PushCFunction( sgs_Context* C, sgs_CFunc func )

void sgs_PushObject( sgs_Context* C, void* data, sgs_ObjInterface* iface )

void* sgs_PushObjectIPA( sgs_Context* C, sgs_SizeVal added, sgs_ObjInterface* iface )

void sgs_PushPtr( sgs_Context* C, void* ptr )

void sgs_PushObjectPtr( sgs_Context* C, sgs_VarObj* obj )

SGSRESULT sgs_PushVariable( sgs_Context* C, sgs_Variable* var )

pushes the data on the stack, as a new entry, appended to the end


sgs_StoreVariable [function]

SGSRESULT sgs_StoreVariable( sgs_Context* C, sgs_Variable* var )

copy the topmost item of the current stack frame to the specified place, acquire it and pop it

error codes


sgs_Pop [function]

SGSRESULT sgs_Pop( sgs_Context* C, int count )

pops count variables off the current frame of the stack

error codes


sgs_PopSkip [function]

SGSRESULT sgs_PopSkip( sgs_Context* C, int count, int skip )

pops count variables off the current frame of the stack, skipping the last skip elements

error codes


sgs_InsertVariable [function]

SGSRESULT sgs_InsertVariable( sgs_Context* C, int pos, sgs_Variable* var )

inserts a variable var at a given index pos of the current stack frame, increasing its reference count

error codes


sgs_PushArray [function]

SGSRESULT sgs_PushArray( sgs_Context* C, sgs_SizeVal numitems )

creates an array from numitems last items on the stack, pops those items and pushes the array

error codes


sgs_PushDict [function]

SGSRESULT sgs_PushDict( sgs_Context* C, sgs_SizeVal numitems )

creates a dict from numitems last items on the stack, pops those items and pushes the dict

error codes


sgs_PushMap [function]

SGSRESULT sgs_PushMap( sgs_Context* C, sgs_SizeVal numitems )

creates a map from numitems last items on the stack, pops those items and pushes the map

error codes


sgs_PushItem [function]

SGSRESULT sgs_PushItem( sgs_Context* C, sgs_StkIdx item )

copy an item from the current stack frame and append it to the end of the stack

error codes


sgs_StoreItem [function]

SGSRESULT sgs_StoreItem( sgs_Context* C, sgs_StkIdx item )

copy last item in current stack frame to index item and pop it

error codes


sgs_GetIndex*** [functions]

SGSRESULT sgs_GetIndexPPP( sgs_Context* C, sgs_Variable* obj, sgs_Variable* idx, sgs_Variable* out, int isprop )

SGSRESULT sgs_GetIndexIPP( sgs_Context* C, sgs_StkIdx obj, sgs_Variable* idx, sgs_Variable* out, int isprop )

SGSRESULT sgs_GetIndexPIP( sgs_Context* C, sgs_Variable* obj, sgs_StkIdx idx, sgs_Variable* out, int isprop )

SGSRESULT sgs_GetIndexIIP( sgs_Context* C, sgs_StkIdx obj, sgs_StkIdx idx, sgs_Variable* out, int isprop )

SGSRESULT sgs_GetIndexPPI( sgs_Context* C, sgs_Variable* obj, sgs_Variable* idx, sgs_StkIdx out, int isprop )

SGSRESULT sgs_GetIndexIPI( sgs_Context* C, sgs_StkIdx obj, sgs_Variable* idx, sgs_StkIdx out, int isprop )

SGSRESULT sgs_GetIndexPII( sgs_Context* C, sgs_Variable* obj, sgs_StkIdx idx, sgs_StkIdx out, int isprop )

SGSRESULT sgs_GetIndexIII( sgs_Context* C, sgs_StkIdx obj, sgs_StkIdx idx, sgs_StkIdx out, int isprop )

retrieve index/property idx from the specified variable obj to the position out, specifying retrieval type via isprop

error codes


sgs_SetIndex*** [functions]

SGSRESULT sgs_SetIndexPPP( sgs_Context* C, sgs_Variable* obj, sgs_Variable* idx, sgs_Variable* val, int isprop )

SGSRESULT sgs_SetIndexIPP( sgs_Context* C, sgs_StkIdx obj, sgs_Variable* idx, sgs_Variable* val, int isprop )

SGSRESULT sgs_SetIndexPIP( sgs_Context* C, sgs_Variable* obj, sgs_StkIdx idx, sgs_Variable* val, int isprop )

SGSRESULT sgs_SetIndexIIP( sgs_Context* C, sgs_StkIdx obj, sgs_StkIdx idx, sgs_Variable* val, int isprop )

SGSRESULT sgs_SetIndexPPI( sgs_Context* C, sgs_Variable* obj, sgs_Variable* idx, sgs_StkIdx val, int isprop )

SGSRESULT sgs_SetIndexIPI( sgs_Context* C, sgs_StkIdx obj, sgs_Variable* idx, sgs_StkIdx val, int isprop )

SGSRESULT sgs_SetIndexPII( sgs_Context* C, sgs_Variable* obj, sgs_StkIdx idx, sgs_StkIdx val, int isprop )

SGSRESULT sgs_SetIndexIII( sgs_Context* C, sgs_StkIdx obj, sgs_StkIdx idx, sgs_StkIdx val, int isprop )

set index/property idx in the specified variable obj to the value val, specifying type via isprop

error codes


sgs_PushIndex** [functions]

SGSRESULT sgs_PushIndexPP( sgs_Context* C, sgs_Variable* obj, sgs_Variable* idx, int isprop )

SGSRESULT sgs_PushIndexIP( sgs_Context* C, sgs_StkIdx obj, sgs_Variable* idx, int isprop )

SGSRESULT sgs_PushIndexPI( sgs_Context* C, sgs_Variable* obj, sgs_StkIdx idx, int isprop )

SGSRESULT sgs_PushIndexII( sgs_Context* C, sgs_StkIdx obj, sgs_StkIdx idx, int isprop )

retrieve and push index/property idx from the specified variable obj, specifying retrieval type via isprop

error codes


sgs_StoreIndex** [functions]

SGSRESULT sgs_StoreIndexPP( sgs_Context* C, sgs_Variable* obj, sgs_Variable* idx, int isprop )

SGSRESULT sgs_StoreIndexIP( sgs_Context* C, sgs_StkIdx obj, sgs_Variable* idx, int isprop )

SGSRESULT sgs_StoreIndexPI( sgs_Context* C, sgs_Variable* obj, sgs_StkIdx idx, int isprop )

SGSRESULT sgs_StoreIndexII( sgs_Context* C, sgs_StkIdx obj, sgs_StkIdx idx, int isprop )

set index/property idx in the specified variable obj to the topmost variable in stack, specifying type via isprop, then pop the topmost variable in stack if successful

error codes


sgs_GetGlobalPP [function]

SGSRESULT sgs_GetGlobalPP( SGS_CTX, sgs_Variable* idx, sgs_Variable* out )

retrieve a global variable by index idx to position out

error codes


sgs_SetGlobalPP [function]

SGSRESULT sgs_SetGlobalPP( SGS_CTX, sgs_Variable* idx, sgs_Variable* val )

set a global variable val to index idx

error codes


sgs_PushProperty [function]

SGSRESULT sgs_PushProperty( sgs_Context* C, sgs_StkIdx obj, const char* name )

load and push the property of the item obj in the current stack frame

error codes


sgs_StoreProperty [function]

SGSRESULT sgs_StoreProperty( sgs_Context* C, sgs_StkIdx obj, const char* name )

copy and pop the topmost item of the current stack frame to the property name of variable obj

error codes


sgs_PushNumIndex [function]

SGSRESULT sgs_PushNumIndex( sgs_Context* C, sgs_StkIdx obj, sgs_Int idx )

load and push the integer index idx of the variable obj

error codes:


sgs_StoreNumIndex [function]

SGSRESULT sgs_StoreNumIndex( sgs_Context* C, sgs_StkIdx obj, sgs_Int idx )

copy and pop the topmost item of the current stack to the integer index idx of variable obj

error codes


sgs_PushGlobal [function]

SGSRESULT sgs_PushGlobal( sgs_Context* C, const char* name )

push the global variable name on the stack

error codes


sgs_StoreGlobal [function]

SGSRESULT sgs_StoreGlobal( sgs_Context* C, const char* name )

copy and pop the topmost stack item to the global variable name

error codes


sgs_GetEnv [function]

void sgs_GetEnv( SGS_CTX, sgs_Variable* out )

retrieve the global environment dict variable (_G)


sgs_SetEnv [function]

SGSRESULT sgs_SetEnv( SGS_CTX, sgs_Variable* var )

set a global environment dict variable from the variable var

error codes


sgs_PushEnv [function]

void sgs_PushEnv( SGS_CTX )

retrieve and push the global environment dict variable (_G)


sgs_StoreEnv [function]

SGSRESULT sgs_StoreEnv( SGS_CTX )

set a global environment dict variable from the topmost stack item, then pop it if successful

error codes


sgs_PushPath [function]

SGSRESULT sgs_PushPath( sgs_Context* C, sgs_StkIdx item, const char* path, ... )

push the variable specified by starting point item and traversal path path

The safety of this function is similar to that of the printf family of functions. Be explicit in what types you pass to the variable argument list to avoid errors.

table of accepted letters

letterproperty?variable argumentsvirtual machine access mode / description
oyesSizeValinteger property
pyesC stringstring property
syesSizeVal, bufferspecial string property
inoSizeValinteger index
knoC stringstring index
nnoSizeVal, bufferspecial string index

error codes


sgs_StorePath [function]

SGSRESULT sgs_StorePath( sgs_Context* C, sgs_StkIdx item, const char* path, ... )

copy and pop the topmost item on stack to variable specified by starting point item and traversal path path

The safety of this function is similar to that of the printf family of functions. Be explicit in what types you pass to the variable argument list to avoid errors.

error codes


sgs_ArgErrorExt [function]

int sgs_ArgErrorExt( sgs_Context* C, int argid, int method, const char* expect, const char* expfx )

prints the argument type mismatch error


sgs_ArgError [function]

int sgs_ArgError( sgs_Context* C, int argid, int expect, int is_strict )

prints the argument type mismatch error


sgs_***ArgError [function aliases]

int sgs_FuncArgError( sgs_Context* C, int argid, int expect, int is_strict )

int sgs_MethodArgError( sgs_Context* C, int argid, int expect, int is_strict )

prints the argument type mismatch error


sgs_LoadArgsExt(VA) [function]

SGSMIXED sgs_LoadArgsExt( sgs_Context* C, int from, const char* cmd, ... )

SGSMIXED sgs_LoadArgsExtVA( sgs_Context* C, int from, const char* cmd, va_list* args )

parse the stack items and retrieve their data according to cmd, starting from item from

unlike sgs_LoadArgs, it returns SGSMIXED and must be checked differently ("ret.val. > 0", if same output needed)

control commands
parsing commands

error codes


sgs_LoadArgs [function alias]

SGSBOOL sgs_LoadArgs( sgs_Context* C, const char* cmd, ... )

parse the stack items and retrieve their data according to cmd, starting from item 0

unlike sgs_LoadArgsExt(VA), it returns bool - whether all required arguments have been successfully parsed


sgs_ParseMethod [function]


SGS_PARSE_METHOD [function alias]


sgs_Method [function]

SGSBOOL sgs_Method( sgs_Context* C )

unlock the 'this' variable, return if the function was called as a method (and thus variable was unlocked)


sgs_(Force)HideThis [functions]

SGSBOOL sgs_HideThis( sgs_Context* C )

SGSBOOL sgs_ForceHideThis( sgs_Context* C )

hide the 'this' variable, return if successful


sgs_FCall(P) [functions]

SGSRESULT sgs_FCall( sgs_Context* C, int args, int expect, int gotthis )

call the topmost variable on stack with the arguments before it, returning the expected number of variables on stack

SGSRESULT sgs_FCallP( sgs_Context* C, sgs_Variable* var, int args, int expect, int gotthis )

call the variable with the arguments on stack, returning the expected number of variables on stack

After a successful call, all arguments and the function will be popped off the stack and the expected number of variables will appear in their place. If the underlying callable does not return enough arguments, 'null' variables will be pushed instead. If the number of returned values is bigger than expected, only the first expected return values will stay on the stack.

Stack is returned to the expected state only if the return value implies success (>= 0) or is equal to SGS_EINPROC. Otherwise, it's left exactly as it was before the call.

The return value 1 is returned if function call was aborted.

error codes


sgs_(This)Call(P) [function aliases]

SGSRESULT sgs_Call( sgs_Context* C, int args, int expect )

SGSRESULT sgs_ThisCall( sgs_Context* C, int args, int expect )

call the topmost variable on stack with the arguments before it, returning the expected number of variables on stack

SGSRESULT sgs_Call( sgs_Context* C, sgs_Variable* var, int args, int expect )

SGSRESULT sgs_ThisCall( sgs_Context* C, sgs_Variable* var, int args, int expect )

call the variable with the arguments on stack, returning the expected number of variables on stack


sgs_GlobalCall [function]

SGSRESULT sgs_GlobalCall( sgs_Context* C, const char* name, int args, int expect )

call the global variable name as a function

error codes


sgs_TypeOf [function]

SGSRESULT sgs_TypeOf( sgs_Context* C )

return the type name string of topmost variable in current stack frame

error codes


sgs_DumpVar [function]

SGSRESULT sgs_DumpVar( sgs_Context* C, int maxdepth )

convert the topmost variable of current stack frame to a highly informative string that should display the contents of the variable, up to maxdepth depth

error codes


sgs_GCExecute [function]

SGSRESULT sgs_GCExecute( sgs_Context* C )

call the garbage collector on the VM

error codes


sgs_PadString [function]

SGSRESULT sgs_PadString( sgs_Context* C )

replace the topmost variable of current stack frame with a string variable where two spaces are appended after every newline

error codes


sgs_ToPrintSafeString [function]

SGSRESULT sgs_ToPrintSafeString( sgs_Context* C )

replace the topmost variable of current stack frame with a string where all non-printable (except space), non-ASCII characters converted to a character hex code

error codes


sgs_StringConcat [function]

SGSRESULT sgs_StringConcat( sgs_Context* C, int args )

concatenate the args number of topmost string variables in the current stack frame

error codes


sgs_ClPushNulls [function]

SGSRESULT sgs_ClPushNulls( sgs_Context* C, sgs_StkIdx num )

push num empty closures to the closure stack

error codes


sgs_ClPushItem [function]

SGSRESULT sgs_ClPushItem( sgs_Context* C, sgs_StkIdx item )

push a variable item on stack as a closure to the closure stack

error codes


sgs_ClPop [function]

SGSRESULT sgs_ClPop( sgs_Context* C, sgs_StkIdx num )

pop num closures from the closure stack

error codes


sgs_MakeClosure [function]

SGSRESULT sgs_MakeClosure( sgs_Context* C, sgs_Variable* func, sgs_StkIdx clcount, sgs_Variable* out )

make a callable closure object from the specified callable func and clcount closures on stack, return it at position out

error codes


sgs_ClGetItem [function]

SGSRESULT sgs_ClGetItem( sgs_Context* C, sgs_StkIdx item, sgs_Variable* out )

retrieve the variable from a closure item on stack

error codes


sgs_ClSetItem [function]

SGSRESULT sgs_ClSetItem( sgs_Context* C, sgs_StkIdx item, sgs_Variable* var )

set the variable var to a closure item on stack

error codes


sgs_CloneItem [function]

SGSRESULT sgs_CloneItem( sgs_Context* C, sgs_StkIdx item )

push a copy of the specified stack item

Even though operations with functions and strings succeed, functions and strings are not actually cloned since they are immutable.

error codes


sgs_ObjectAction [function]

SGSMIXED sgs_ObjectAction( sgs_Context* C, sgs_StkIdx item, int action, int arg )

execute an action on the specified stack item

actions

error codes


sgs_Serialize [function]

SGSRESULT sgs_Serialize( sgs_Context* C )

serialize the topmost variable of the current stack frame (convert to a binary recreation instruction stream)

error codes


sgs_SerializeObject [function]

SGSRESULT sgs_SerializeObject( sgs_Context* C, int args, const char* func )

write the serialized code for an object's unserializing function

error codes


sgs_Unserialize [function]

SGSRESULT sgs_Unserialize( sgs_Context* C )

unserialize the topmost string variable of the current stack frame (run the binary recreation instruction stream)

Be mindful of the data sources you use - calls to any global function can be placed in the instruction stream.


sgs_Assign [function]

void sgs_Assign( sgs_Context* C, sgs_Variable* var_to, sgs_Variable* var_from )

release var_to, copy var_from to var_to, acquire the new value


sgs_ArithOp [function]

SGSRESULT sgs_ArithOp( sgs_Context* C, sgs_Variable* out, sgs_Variable* A, sgs_Variable* B, int op )

perform the specified operation on variables A and B, returning the value on out

this function prints errors, exactly like VM would (internally there are the same functions)

error codes


sgs_IncDec [function]

SGSRESULT sgs_IncDec( SGS_CTX, sgs_Variable* out, sgs_Variable* A, int inc )

increment or decrement the specified variable A to the output out

this function prints errors, exactly like VM would (internally there are the same functions)

error codes


sgs_Compare [function]

int sgs_Compare( sgs_Context* C, sgs_Variable* v1, sgs_Variable* v2 )

return the difference between variables, as int -1/0/1


sgs_EqualTypes [function]

SGSBOOL sgs_EqualTypes( sgs_Variable* v1, sgs_Variable* v2 )

return if types of both variables are exactly equal


sgs_Get*** [functions]

sgs_Bool sgs_GetBool( sgs_Context* C, sgs_StkIdx item )

sgs_Int sgs_GetInt( sgs_Context* C, sgs_StkIdx item )

sgs_Real sgs_GetReal( sgs_Context* C, sgs_StkIdx item )

void* sgs_GetPtr( sgs_Context* C, sgs_StkIdx item )

return an item from the current stack frame, converted to the specified type

sgs_Bool sgs_GetBoolP( sgs_Context* C, sgs_Variable* var )

sgs_Int sgs_GetIntP( sgs_Context* C, sgs_Variable* var )

sgs_Real sgs_GetRealP( sgs_Context* C, sgs_Variable* var )

void* sgs_GetPtrP( sgs_Context* C, sgs_Variable* var )

return the value of the specified variable, converted to the specified type


sgs_To*** [functions]

sgs_Bool sgs_ToBool( sgs_Context* C, sgs_StkIdx item )

sgs_Int sgs_ToInt( sgs_Context* C, sgs_StkIdx item )

sgs_Real sgs_ToReal( sgs_Context* C, sgs_StkIdx item )

void* sgs_ToPtr( sgs_Context* C, sgs_StkIdx item )

return an item from the current stack frame, converted in-place to the specified type

sgs_Bool sgs_ToBoolP( sgs_Context* C, sgs_Variable* var )

sgs_Int sgs_ToIntP( sgs_Context* C, sgs_Variable* var )

sgs_Real sgs_ToRealP( sgs_Context* C, sgs_Variable* var )

void* sgs_GetPtrP( sgs_Context* C, sgs_Variable* var )

return the value of the specified variable, converted in-place to the specified type


sgs_ToStringBuf(Fast)(P) [functions]

char* sgs_ToStringBuf( sgs_Context* C, sgs_StkIdx item, sgs_SizeVal* outsize )

char* sgs_ToStringBufFast( sgs_Context* C, sgs_StkIdx item, sgs_SizeVal* outsize )

return an item from the current stack frame, converted in-place to string

char* sgs_ToStringBufP( sgs_Context* C, sgs_Variable* var, sgs_SizeVal* outsize )

char* sgs_ToStringBufFastP( sgs_Context* C, sgs_Variable* var, sgs_SizeVal* outsize )

return the value of the specified variable, converted in-place to string


sgs_ToString(Fast)(P) [function aliases]

char* sgs_ToString( sgs_Context* C, sgs_StkIdx item )

char* sgs_ToStringFast( sgs_Context* C, sgs_StkIdx item )

return an item from the current stack frame, converted in-place to string

char* sgs_ToStringP( sgs_Context* C, sgs_Variable* var )

char* sgs_ToStringFastP( sgs_Context* C, sgs_Variable* var )

return the value of the specified variable, converted in-place to string


sgs_RegisterType [function]

SGSRESULT sgs_RegisterType( sgs_Context* C, const char* name, sgs_ObjInterface* iface )

register a type interface by mapping it to a name

error codes


sgs_UnregisterType [function]

SGSRESULT sgs_UnregisterType( sgs_Context* C, const char* name )

unregister a type interface by its name

error codes


sgs_FindType [function]

sgs_ObjInterface* sgs_FindType( sgs_Context* C, const char* name )

finds the type interface that is mapped to the specified name or returns NULL if that type name cannot be found


sgs_IsObject(P) [functions]

SGSBOOL sgs_IsObject( sgs_Context* C, sgs_StkIdx item, sgs_ObjInterface* iface )

returns whether the specified stack item item is an object with the interface pointer iface

SGSBOOL sgs_IsObjectP( sgs_Context* C, sgs_Variable* var, sgs_ObjInterface* iface )

returns whether the specified variable var is an object with the interface pointer iface


sgs_IsType(P) [function aliases]

SGSBOOL sgs_IsType( sgs_Context* C, sgs_StkIdx item, const char* type )

returns whether the specified stack item item is an object of the specified type

SGSBOOL sgs_IsTypeP( sgs_Context* C, sgs_Variable* var, const char* type )

returns whether the specified variable var is an object of the specified type


sgs_IsCallable(P) [functions]

SGSBOOL sgs_IsCallable( sgs_Context* C, sgs_StkIdx item )

returns whether the specified stack item item is callable

SGSBOOL sgs_IsCallableP( sgs_Context* C, sgs_Variable* var )

returns whether the specified variable var is callable


sgs_IsNumericString [function]

SGSBOOL sgs_IsNumericString( const char* str, sgs_SizeVal size )

checks if the string is convertible to an integer/real


sgs_Parse*** [functions]

SGSBOOL sgs_ParseBool( sgs_Context* C, sgs_StkIdx item, sgs_Bool* out )

SGSBOOL sgs_ParseInt( sgs_Context* C, sgs_StkIdx item, sgs_Int* out )

SGSBOOL sgs_ParseReal( sgs_Context* C, sgs_StkIdx item, sgs_Real* out )

SGSBOOL sgs_ParseString( sgs_Context* C, sgs_StkIdx item, char** out, sgs_SizeVal* size )

SGSBOOL sgs_ParseObjectPtr( sgs_Context* C, sgs_StkIdx item, sgs_ObjInterface* iface, sgs_VarObj** out, int strict )

SGSBOOL sgs_ParsePtr( sgs_Context* C, sgs_StkIdx item, void** out )

attempts to parse the specified item of the current stack frame, returning whether parsing was successful

SGSBOOL sgs_ParseBoolP( sgs_Context* C, sgs_Variable* var, sgs_Bool* out )

SGSBOOL sgs_ParseIntP( sgs_Context* C, sgs_Variable* var, sgs_Int* out )

SGSBOOL sgs_ParseRealP( sgs_Context* C, sgs_Variable* var, sgs_Real* out )

SGSBOOL sgs_ParseStringP( sgs_Context* C, sgs_Variable* var, char** out, sgs_SizeVal* size )

SGSBOOL sgs_ParseObjectPtrP( sgs_Context* C, sgs_Variable* var, sgs_ObjInterface* iface, sgs_VarObj** out, int strict )

SGSBOOL sgs_ParsePtrP( sgs_Context* C, sgs_Variable* var, void** out )

attempts to parse the specified varuabke, returning whether parsing was successful


sgs_Global*** [functions]

sgs_Bool sgs_GlobalBool( SGS_CTX, const char* name )

sgs_Int sgs_GlobalInt( SGS_CTX, const char* name )

sgs_Real sgs_GlobalReal( SGS_CTX, const char* name )

char* sgs_GlobalStringBuf( SGS_CTX, const char* name, sgs_SizeVal* outsize )

char* sgs_GlobalString( SGS_CTX, const char* name )

retrieve a global variable, converted to the specified type

sgs_GlobalString[Buf] pushes the variable on the stack to be able to reliably return the string pointer


sgs_PushIterator(P) [functions]

SGSRESULT sgs_PushIterator( sgs_Context* C, sgs_StkIdx item )

create and push an iterator from the specified item of the current stack frame

SGSRESULT sgs_PushIteratorP( sgs_Context* C, sgs_Variable* var )

create and push an iterator from the specified variable

error codes


sgs_GetIterator(P) [functions]

SGSRESULT sgs_GetIterator( sgs_Context* C, sgs_StkIdx item, sgs_Variable* out )

create an iterator from the specified item of the current stack frame

SGSRESULT sgs_GetIteratorP( sgs_Context* C, sgs_Variable* var, sgs_Variable* out )

create an iterator from the specified variable

error codes


sgs_IterAdvance(P) [functions]

SGSMIXED sgs_IterAdvance( sgs_Context* C, sgs_StkIdx item )

SGSMIXED sgs_IterAdvanceP( sgs_Context* C, sgs_Variable* var )

advance the iterator to the next position, returning if the current position is still in range or an error code on failure

error codes


sgs_IterPushData(P) [functions]

SGSRESULT sgs_IterPushData( sgs_Context* C, sgs_StkIdx item, int key, int value )

SGSRESULT sgs_IterPushDataP( sgs_Context* C, sgs_Variable* var, int key, int value )

load and push data associated with the current position

error codes


sgs_IterGetData(P) [functions]

SGSRESULT sgs_IterGetData( sgs_Context* C, sgs_StkIdx item, sgs_Variable* key, sgs_Variable* value )

SGSRESULT sgs_IterGetDataP( sgs_Context* C, sgs_Variable* var, sgs_Variable* key, sgs_Variable* value )

load data associated with the current position

error codes


sgs_ArraySize(P) [functions]

SGSMIXED sgs_ArraySize( sgs_Context* C, sgs_StkIdx item )

SGSMIXED sgs_ArraySizeP( sgs_Context* C, sgs_Variable* var )

check if the specified stack item or variable is an array and return its size or error code on failure

error codes


sgs_StackSize [function]

sgs_StkIdx sgs_StackSize( sgs_Context* C )

return the size of the current stack frame


sgs_SetStackSize [function]

SGSRESULT sgs_SetStackSize( sgs_Context* C, sgs_StkIdx size )

resizes the current stack frame to fit the specified amount of items


sgs_AbsIndex [function]

sgs_StkIdx sgs_AbsIndex( sgs_Context* C, sgs_StkIdx item )

attempt to convert a negative stack index into a positive one

this function can still return negative values - make sure that valid values are passed to it or check if the returned value is in the range [ 0; stack_frame_size )


sgs_IsValidIndex [function]

SGSBOOL sgs_IsValidIndex( sgs_Context* C, sgs_StkIdx item )

return whether the specified stack index points to an item in the current stack frame


sgs_PeekStackItem [function]

SGSBOOL sgs_PeekStackItem( sgs_Context* C, sgs_StkIdx item, sgs_Variable* out )

write the data of the specified stack variable if the index is valid

this function does not acquire the variable and thus CANNOT be used in functions that modify it, such as sgs_Assign or sgs_To***; to acquire variable on retrieval, see sgs_GetStackItem or sgs_Acquire


sgs_GetStackItem [function]

SGSBOOL sgs_GetStackItem( sgs_Context* C, sgs_StkIdx item, sgs_Variable* out )

write the data of the specified stack variable and increments its reference count if the index is valid


sgs_SetStackItem [function]

SGSRESULT sgs_SetStackItem( sgs_Context* C, sgs_StkIdx item, sgs_Variable* val )

copy the specified variable to the specified position in stack

error codes


sgs_ItemType [function]

uint32_t sgs_ItemType( sgs_Context* C, sgs_StkIdx item )

return the type ID of the specified stack item


sgs_Acquire(Array) [function]

void sgs_Acquire( sgs_Context* C, sgs_Variable* var )

void sgs_AcquireArray( sgs_Context* C, sgs_Variable* var, sgs_SizeVal count )

increment the reference count of the specified variables (if they count references)


sgs_Release(Array) [function]

void sgs_Release( sgs_Context* C, sgs_Variable* var )

void sgs_ReleaseArray( sgs_Context* C, sgs_Variable* var, sgs_SizeVal count )

decrement and possibly deallocate the reference count of the specified variables (if they count references)


sgs_GCMark(Array) [function]

SGSRESULT sgs_GCMark( sgs_Context* C, sgs_Variable* var )

SGSRESULT sgs_GCMarkArray( sgs_Context* C, sgs_Variable* var, sgs_SizeVal count )

mark the specified variables as reachable for the garbage collector


sgs_ObjAcquire [function]

void sgs_ObjAcquire( sgs_Context* C, sgs_VarObj* obj )

increment reference count of the specified object


sgs_ObjRelease [function]

void sgs_ObjRelease( sgs_Context* C, sgs_VarObj* obj )

decrement reference count and possibly delete the specified object


sgs_ObjGCMark [function]

SGSRESULT sgs_ObjGCMark( sgs_Context* C, sgs_VarObj* obj )

mark the specified object as accessible to avoid its destruction by the Garbage collection system


sgs_ObjAssign [function]

void sgs_ObjAssign( sgs_Context* C, sgs_VarObj** dest, sgs_VarObj* src )

assign object pointer, handling acquisition/release properly


sgs_ObjCallDtor [function]

void sgs_ObjCallDtor( sgs_Context* C, sgs_VarObj* obj )

call the DESTRUCT object callback


sgs_GetStringPtr(P) [functions]

char* sgs_GetStringPtr( sgs_Context* C, sgs_StkIdx item )

return the string data pointer of the specified stack item

char* sgs_GetStringPtrP( sgs_Context* C, sgs_Variable* var )

return the string data pointer of the specified variable


sgs_GetStringSize(P) [functions]

sgs_SizeVal sgs_GetStringSize( sgs_Context* C, sgs_StkIdx item )

return the string size of the specified stack item

sgs_SizeVal sgs_GetStringSizeP( sgs_Context* C, sgs_Variable* var )

return the string size of the specified variable


sgs_GetObjectStruct(P) [functions]

sgs_VarObj* sgs_GetObjectStruct( sgs_Context* C, sgs_StkIdx item )

return the object's internal data pointer of the specified stack item

sgs_VarObj* sgs_GetObjectStructP( sgs_Context* C, sgs_Variable* var )

return the object's internal data pointer of the specified variable


sgs_GetObjectData(P) [functions]

void* sgs_GetObjectData( sgs_Context* C, sgs_StkIdx item )

return the object data pointer of the specified stack item

void* sgs_GetObjectDataP( sgs_Context* C, sgs_Variable* var )

return the object data pointer of the specified variable


sgs_GetObjectIface(P) [functions]

sgs_ObjInterface* sgs_GetObjectIface( sgs_Context* C, sgs_StkIdx item )

return the object interface pointer of the specified stack item

sgs_ObjInterface* sgs_GetObjectIfaceP( sgs_Context* C, sgs_Variable* var )

return the object interface pointer of the specified variable


sgs_SetObjectData(P) [functions]

int sgs_SetObjectData( sgs_Context* C, sgs_StkIdx item, void* data )

set the object data pointer of the specified stack item

int sgs_SetObjectDataP( sgs_Context* C, sgs_Variable* var, void* data )

set the object data pointer of the specified variable


sgs_SetObjectIface(P) [functions]

int sgs_SetObjectIface( sgs_Context* C, sgs_StkIdx item, sgs_ObjInterface* iface )

set the object interface pointer of the specified stack item

int sgs_SetObjectIfaceP( sgs_Context* C, sgs_Variable* var, sgs_ObjInterface* iface )

set the object interface pointer of the specified variable


sgs_StdOutputFunc [function]

void sgs_StdOutputFunc( void* userdata, sgs_Context* C, const void* ptr, size_t size )

standard output function assumes userdata to be FILE* type and writes the passed buffer to it


sgs_Get(Err)OutputFunc [function]

void sgs_GetOutputFunc( sgs_Context* C, sgs_OutputFunc* outfunc, void** outuserdata )

void sgs_GetErrOutputFunc( sgs_Context* C, sgs_OutputFunc* outfunc, void** outuserdata )

retrieves the currently set (error) output function


sgs_Set(Err)OutputFunc [function]

void sgs_SetOutputFunc( sgs_Context* C, sgs_OutputFunc func, void* userdata )

void sgs_SetErrOutputFunc( sgs_Context* C, sgs_OutputFunc func, void* userdata )

sets the function used in 'print'/'errprint' function family


sgs_(Err)Write [function]

void sgs_Write( sgs_Context* C, const void* ptr, sgs_SizeVal size )

void sgs_ErrWrite( sgs_Context* C, const void* ptr, sgs_SizeVal size )

passes the specified data to the (error) output function


sgs_(Err)WriteStr [function alias]

void sgs_WriteStr( sgs_Context* C, const char* str )

void sgs_ErrWriteStr( sgs_Context* C, const char* str )

passes the specified string to the (error) output function


sgs_(Err)Writef [function]

void sgs_Writef( sgs_Context* C, const char* what, ... )

passes the arguments through a vsprintf-like function to expand the data and passes it to the specified output function


sgs_StdMsgFunc(_NoAbort) [functions]

void sgs_StdMsgFunc( void* ctx, sgs_Context* C, int type, const char* msg )

void sgs_StdMsgFunc_NoAbort( void* ctx, sgs_Context* C, int type, const char* msg )

writes error info with sgs_WriteErrorInfo to userdata with fprintf, assuming userdata is FILE*


sgs_GetMsgFunc [function]

void sgs_GetMsgFunc( sgs_Context* C, sgs_MsgFunc* outfunc, void** outuserdata )

retrieves the currently set messaging function


sgs_SetMsgFunc [function]

void sgs_SetMsgFunc( sgs_Context* C, sgs_MsgFunc func, void* userdata )

sets the function that handles and prints messages (more commonly, warnings and errors), while still being physically in that context


sgs_Msg [function]

int sgs_Msg( sgs_Context* C, int type, const char* what, ... )

prepares and prints the error specified


sgs_WriteErrorInfo [function]

void sgs_WriteErrorInfo( sgs_Context* C, int flags, sgs_ErrorOutputFunc func, void* ctx, int type, const char* msg )

writes error info using the error output function specified

the error output function type has the following definition:

typedef int (*sgs_ErrorOutputFunc) ( void*, const char*, ... );

sgs_PushErrorInfo [function]

void sgs_PushErrorInfo( sgs_Context* C, int flags, int type, const char* msg )

pushes a string generated from error info


sgs_HasFuncName [function]

int sgs_HasFuncName( sgs_Context* C )

checks if the currently executed function (last stack frame) has a name literal set


sgs_FuncName [function]

void sgs_FuncName( sgs_Context* C, const char* fnliteral )

sets the function name string for the currently executed function (last stack frame)


SGSFN [function alias]

void SGSFN( const char* fnliteral )

sets the function name string, more info at sgs_FuncName


SGSBASEFN [function alias]

void SGSBASEFN( const char* fnliteral )

sets the function name string if it hasn't already been set for the function


sgs_SetHookFunc [function]

void sgs_SetHookFunc( sgs_Context* C, sgs_HookFunc func, void* ctx )

sets the hook function and user data pointer


sgs_GetHookFunc [function]

SGSBOOL sgs_GetHookFunc( sgs_Context* C, sgs_HookFunc* outfunc, void** outctx )

writes the hook function and user data pointer that was set (if any), returns whether anything was written


sgs_DefaultMemFunc [function]

void* sgs_DefaultMemFunc( void* userdata, void* ptr, size_t size )

the default memory allocation function

expected behavior: same as for sgs_Memory

sample implementation (same as in sgscript.h):

if( ptr && size ) return realloc( ptr, size );
else if( size )   return malloc( size );
if( ptr )         free( ptr );
return NULL;

sgs_Memory [function]

void sgs_Memory( sgs_Context* C, void* ptr, size_t size )

allocates and frees memory, as specified in arguments


Memory allocation macros [macros]

Memory allocation macros

these macros allow slightly simplified handling of memory


sgs_CodeString [function]

const char* sgs_CodeString( int type, int val )

returns a string for the enumeration type value val


sgs_Abort [function]

SGSRESULT sgs_Abort( sgs_Context* C )

stops execution of current SGS functions up to the last C function in the stack, excluding the current

error codes


sgs_Stat [function]

ptrdiff_t sgs_Stat( sgs_Context* C, int type )

returns or prints information about state of SGScript VM


sgs_Cntl [function]

int32_t sgs_Cntl( sgs_Context* C, int what, int32_t val )

modifies the state of the VM or returns info about it


sgs_StackFrameInfo [function]

void sgs_StackFrameInfo( sgs_Context* C, sgs_StackFrame* frame, const char** name, const char** file, int* line )

helps to retrieve file name, function name and line number of the specified stack frame


sgs_GetFramePtr [function]

sgs_StackFrame* sgs_GetFramePtr( sgs_Context* C, int end )

returns a call stack frame pointer


sgs_Errno [function alias]

int sgs_Errno( sgs_Context* C, int clear )

copies errno to internal errno value if clear is not 0, otherwise internal errno value is set to 0, returns clear


sgs_SetErrno [function alias]

int sgs_SetErrno( sgs_Context* C, int err )

sets a specific value err to the internal errno variable


sgs_GetLastErrno [function alias]

int sgs_GetLastErrno( sgs_Context* C )

returns the currently set internal errno variable


sgs_PushStringBuf32 [function]

void sgs_PushStringBuf32( sgs_Context* C, sgs_String32* S, const char* str, sgs_SizeVal len )

pushes a temporary string variable from the specified buffer, allocated in the sgs_String32 object


sgs_PushString32 [function]

void sgs_PushString32( sgs_Context* C, sgs_String32* S, const char* str )

pushes a temporary string variable from the specified string, allocated in the sgs_String32 object


sgs_CheckString32 [function]

void sgs_CheckString32( sgs_String32* S )

attempts to trigger a debug breakpoint if the specified temporary string object is not freed from all contexts


sgs_IsFreedString32 [function]

SGSBOOL sgs_IsFreedString32( sgs_String32* S )

returns whether the specified temporary string object is freed from all contexts


Interface implementation


C Functions

A C function has the type int CFunc( sgs_Context* ). It receives the context that called it and must return the number of return values pushed on stack.

Conventions

There are no forced courses of action beyond this point. However, to simplify development, some conventions were established and are used throughout the standard library and are suggested to follow.

General structure
Argument loading
Error handling

A typical function

int sgsfunc_sample( SGS_CTX )
{
    sgs_Int num;
    char* str;
    char* buf;
    sgs_SizeVal bufsize;
    
    if( !sgs_LoadArgs( C, "ism", &num, &str, &buf, &bufsize ) )
        return 0;
    
    if( bufsize == 0 )
        return sgs_Msg( C, SGS_WARNING, "buffer cannot be empty" );
    // sgs_Msg always returns 0
    
    // .. do something with the passed arguments ..
    
    // anything can be returned ..
    // .. but in this case, we want to say ..
    // .. that the action was successful
    sgs_PushBool( C, 1 );
    return 1;
}

Object interface

Every interface function has the type int ObjCallback ( sgs_Context* C, sgs_VarObj* data, ... ). Not every of them has to be implemented (none of them are required) but for all non-pointer objects it helps to have at least one of them.

Interface is a structure that contains of an array and 10 function pointers in the following order: destruct, gcmark, getindex, setindex, convert, serialize, dump, getnext, call, expr. This is how interfaces are usually defined in code:

sgs_ObjInterface object_interface[1] =
{{
    "object_type_name",
    object_destruct, NULL,  /* destruct, gcmark */
    object_getindex, NULL,  /* getindex, setindex */
    NULL, NULL, NULL, NULL, /* convert, serialize, dump, getnext */
    NULL, NULL              /* call, expr */
}};

The interface is defined as an array with size=1 to later be able to use it in code without prepending "&" to the name.

DESTRUCT - destruction callback

When called:
Additional arguments:

None.

Stack frame:

Empty.

Return values:

Non-negative value if successful, negative on error.

Additional notes:

It is important to minimize the possibility of failure here. The system cannot help in any way if memory or ownership states are corrupted.

GETINDEX - index/property retrieval callback

When called:
Additional arguments:
Stack frame:

Empty at beginning. Expected to have at least one item on stack after a successful index/property read. The topmost one is used.

Return values:
Additional notes:

It is safe to use conversion functions on the key variable.

SETINDEX - index/property setting callback

When called:
Additional arguments:
Stack frame:

Empty.

Return values:
Additional notes:

It is safe to use conversion functions on both variables.

CONVERT - conversion callback

When called:

Depending on the argument, it is called by different sources:

Additional arguments:
Stack frame:

Empty at beginning. Expected to have at least one item on stack after a successful conversion. The topmost one is used.

Depending on the argument, it requires different variable types on stack:

Return values:
Additional notes:

SERIALIZE - serialization callback

When called:
Additional arguments:

None.

Stack frame:

Empty.

Return values:
Additional notes:

Callback requires no data but expects that sgs_Serialize / sgs_SerializeObject is successfully called once. In the case of sgs_SerializeObject, the necessary number (equal to argument count, passed to the function) of sgs_Serialize calls must be made before it.

DUMP - debug dump callback

When called:
Additional arguments:
Stack frame:

Empty at beginning. Expected to have at least one item on stack after a successful conversion. The topmost one is used.

Return values:
Additional notes:

GCMARK - garbage collector marking callback

When called:
Additional arguments:

None.

Stack frame:

Empty.

Return values:
Additional notes:

GETNEXT - iterator control callback

When called:
Additional arguments:
Stack frame:

Empty at beginning. Expects at least one (if either flag is set, but not both) or two (if both flags are set) variables on success. Key first, value second.

Return values:
Additional notes:

None.

CALL - the "function call" callback

When called:
Additional arguments:

None.

Stack frame:

Contains all the same things as any C function call would: optional this variable and optional argument list. Expects at least the returned number of items after the call to be used as return values.

Return values:
Additional notes:

None.

EXPR - expression callback

When called:

Additional arguments:
Stack frame:

Empty at beginning. Expects at least one variable on success (the topmost one will be used).

Return values:
Additional notes:

The full list of operators triggering the operations:


Interaction with the environment

Most operations are directed towards the scripting engine, that is - environment makes a function call and scripting engine handles it. For everything else, there are callbacks.

Memory allocation

Output

Execution notifications


Commonly required advanced tasks

Method handling

ObjectDataStruct* data;
if( !SGS_PARSE_METHOD( C, Object_interface_pointer, data, Object_name, Method_name ) )
    return 0;
sgs_FuncName( C, "<object>.<method>" );
if( !sgs_Method( C ) || !sgs_IsObject( C, 0, Object_interface_pointer ) )
    return sgs_ArgErrorExt( C, 0, 1, "<object>", "" );
ObjectDataStruct* data = (ObjectDataStruct*) sgs_GetObjectData( C, 0 );
sgs_HideThis( C );
int method_call = sgs_Method( C );
sgs_FuncName( C, method_call ? "<object>.<method>" : "<object_function>" );
if( !sgs_IsObject( C, 0, Object_interface_pointer ) )
    return sgs_ArgErrorExt( C, 0, method_call, "<object>", "" );
ObjectDataStruct* data = (ObjectDataStruct*) sgs_GetObjectData( C, 0 );
sgs_ForceHideThis( C );

Standard library reference


Core library

This library is loaded on initialization and contains the functions and constants necessary to do primary actions:

Functions:

Objects and their methods:

Constants:

Other:


array [function]

array( ... )

returns an array, containing the arguments

array( "5", 6, 7.0 ) // same as ["5",6,7.0]

dict [function]

dict( [key, value, ...] )

returns a 'dict' (dictionary/hash table) object, containing the even arguments mapped to respective previous arguments

dict( "name", "John", "phone", 1234567890 ); // same as { name = "John", phone = 1234567890 }

map [function]

map( [key, value, ...] )

returns a 'map' (map/hash table) object, containing the even arguments mapped to respective previous arguments

map( "John", "name", 1234567890, "phone" ); // useful for mapping additional data to variables or making sets

class [function]

class( first, second )

returns a class object with first set as the primary data source and second set as the secondary/backup data source

someCommonInterface = { printdata = function(){ print( this.data ); } };
c = class( { data = "5" }, someCommonInterface );
c.data = "6";
c.printdata(); // prints 6

array_filter [function]

array_filter( array[, callable] )

return an array with the items that convert to boolean 'true', optionally preprocessed by a callable

array_filter([ 0, 1, 2, 3 ]); // returns [1,2,3]

array_process [function]

array_process( array, callable )

return an array with the items passed through a callable


dict_filter [function]

dict_filter( dict[, callable] )

return a dict with the items that convert to boolean 'true', optionally preprocessed by a callable

dict_filter({ a = 0, b = 1 }); // returns {b=1}

dict_process [function]

dict_process( dict, callable )

return a dict with the items passed through a callable


dict_size [function]

dict_size( dict )

return the number of entries in the dict object

x = { a = 5, b = 123 };
dict_size( x ); // returns 2

map_size [function]

map_size( dict )

return the number of entries in the map object

x = map( 5, "a", 123, "b" );
map_size( x ); // returns 2

isset [function]

isset( var, key )

returns whether a property key is readable (exists) in variable var

x = { a = 5 };
isset( x, "a" ); // returns 'true'
isset( x, "b" ); // returns 'false'
isset( print, "call" ); // returns 'true' -- works with built-in special properties too

unset [function]

unset( dict|map var, (string) key )

removes an entry named key from the dictionary var


clone [function]

clone( var )

creates a one-reference copy of the variable var or returns null and emits a warning on failure

x = { a = 5 };
y = clone( x );
z = x;
x.a = 6;
print( y.a ); // prints "5"
print( z.a ); // prints "6"

get_keys [function]

get_keys( iterable var )

returns an array of keys found in the iterable object var or returns null and emits a warning on failure

get_keys( [5,7,0] ); // returns [0,1,2]
get_keys( {b=5,a=2} ); // returns ["b","a"]

get_values [function]

get_values( iterable var )

returns an array of values found in the iterable object var or returns null and emits a warning on failure

get_values( [5,7,0] ); // returns [5,7,0]
get_values( {b=5,a=2} ); // returns [5,2]

get_concat [function]

get_concat( iterable var, iterable var1, ... )

returns an array of values found in all iterable objects passed to the function or returns null and emits a warning on failure

get_concat( [1,2], {a="5",b=8} ); // returns [1,2,"5",8]

get_merged [function]

get_merged( iterable var, iterable var1, ... )

returns a dict of all key-value pairs found in all iterable objects passed to the function or returns null and emits a warning on failure

get_merged( [1,2], [3], {a="4"} ); // return {0=3,1=2,a="4"}

get_merged_map [function]

get_merged_map( iterable var, iterable var1, ... )

returns a map of all key-value pairs found in all iterable objects passed to the function or returns null and emits a warning on failure

get_merged_map( [1,2], map(5,6), {a="4"} ); // return {0=3,1=2,int(5)=6,a="4"}

get_iterator [function]

get_iterator( iterable var )

returns an iterator from the passed object, if it has one

get_iterator( [ 5 ] ); // returns array iterator for the specified array

iter_advance [function]

iter_advance( iterator var )

advances an iterator to the next position, returning if there is any more data to read

it = get_iterator( [ 5 ] ); // retrieves iterator from array [5]
iter_advance( it ); // returns true, indicating that the current position is still a valid one

iter_getdata [function]

iter_getdata( iterator var, bool pushkey = false, bool pushvalue = true )

returns key/value data from iterator

it = get_iterator( [ 5 ] ); // retrieves iterator from array [5]
iter_advance( it ); // returns true, indicating that the current position is still a valid one
(key,value) = iter_getdata( it, true ); // returns 0, 5  -- key, value

tobool [function]

tobool( var )

returns a boolean, generated from variable var using the Conversion rules

tobool( 5 ); // returns 'true'
tobool( "" ); // returns 'false'

toint [function]

toint( var )

returns an integer, generated from variable var using the Conversion rules

toint( 5.4 ); // returns 5
toint( "0xff" ); // returns 255

toreal [function]

toreal( var )

returns a real value, generated from variable var using the Conversion rules

toreal( 5 ); // returns 5.0
toreal( "3e+2" ); // returns 300.0
toreal( "0xff" ); // returns 255.0

tostring [function]

tostring( var )

returns a string value, generated from variable var using the Conversion rules

tostring( 5 ); // returns "5"
tostring( { "a" = "b" } ); // returns "{a=b}"

toptr [function]

toptr( var )

returns a pointer value, generated from variable var using the Conversion rules

toptr( 5 ); // returns 5
toptr( "3e+2" ); // returns address of the string
toptr( [] ); // returns address of array data

parseint [function]

parseint( var )

returns an integer, generated from variable var using the Conversion rules or returns null on failure

parseint( 5.4 ); // returns 5
parseint( "0xff" ); // returns 255
parseint( parseint ); // returns null

parsereal [function]

parsereal( var )

returns a real value, generated from variable var using the Conversion rules or returns null on failure

parsereal( 5 ); // returns 5.0
parsereal( "3e+2" ); // returns 300.0
parsereal( "0xff" ); // returns 255.0
parsereal( parsereal ); // returns null

typeof [function]

typeof( var )

returns the type name of variable var, as string

typeof( 5 ); // returns "real"
typeof( [] ); // returns "array"

typeid [function]

typeid( var )

returns the first 4 bits of the variable var type flags, as int

typeid( 5 ) == VT_INT; // returns 'true'
typeid( [] ); // returns 7 / VT_OBJECT

typeptr [function]

typeptr( var )

returns type interface pointer from object variables or null pointer from other variables

typeptr( 5 ); // returns ptr(0)
typeptr( [] ); // returns ptr(...), NOT ptr(0)

typeptr_by_name [function]

typeptr_by_name( string name )

returns type interface pointer by its name or null pointer if name is not assigned to a pointer

typeptr_by_name( "array" ); // returns ptr(...)
typeptr_by_name( "array" ) == typeptr( [] ); // returns 'true'

is_numeric [function]

is_numeric( var )

returns whether the variable var is numeric - one of bool/int/real or a numeric string

is_numeric( 12.124 ); // returns true
is_numeric( "what" ); // returns false

is_callable [function]

is_callable( var )

returns whether the variable var is callable - a function (func/cfunc) or an object with OP_CALL defined

is_callable( print ); // returns 'true'
is_callable( function(){} ); // returns 'true'
is_callable( 5 ); // returns 'false'

is_array [function]

is_array( var )

returns if variable is an array

is_array( print ); // returns 'false'
is_array( [] ); // returns 'true'

is_dict [function]

is_dict( var )

returns if variable is a dict

is_dict( 5 ); // returns 'false'
is_dict( [] ); // returns 'false'
is_dict( {} ); // returns 'true'

is_map [function]

is_map( var )

returns if variable is a map

is_map( "map" ); // returns 'false'
is_map( {} ); // returns 'false'
is_map( map() ); // returns 'true'

is_iterable [function]

is_iterable( var )

returns if variable is iterable

is_iterable( print ); // returns 'false'
is_iterable( [] ); // returns 'true'
is_iterable( {} ); // returns 'true'

print, println, printlns, errprint, errprintln, errprintlns [functions]

print( ... ), println( ... ), printlns( ... ),

errprint( ... ), errprintln( ... ), errprintlns( ... ),

passes all arguments, converted to strings, to the (error) output callback

print( 5, "x" ); // prints "5x"
println( 5, "x" ); // prints "5x\n"
printlns( 5, "x" ); // prints "5\nx\n"
errprint( 5, "x" ); // prints "5x" to error output stream
errprintln( 5, "x" ); // prints "5x\n" to error output stream
errprintlns( 5, "x" ); // prints "5\nx\n" to error output stream

printvar_ext [function]

printvar_ext( var, int maxdepth = 5 )

passes a dump of the variable (informative string version) to the output callback, allowing to optionally specify the maximum depth of the dump (how deep it is allowed to look for sub-variables)

printvar_ext( 5 ); // prints "real (5)"
printvar_ext( "wat" ); // prints "string [3] "wat""
printvar_ext( [{a=[{}]}], 2 ); /* prints:
object (003C5F90) [0] array (1)
[
  object (003C60A8) [1] dict (1)
  {
    ...
  }
]
*/

printvar [function]

printvar( var, ... )

same as a list of printvar(var); calls for each argument


read_stdin [function]

read_stdin( bool all = false )

reads from the standard input

print "Name: "; name = read_stdin(); // waits for user input
process( read_stdin(true) ); // loads all piped input

ftime [function]

ftime()

returns a value that is increased by a total of 1 each second (time), as real

start = ftime();
do_something_big();
println( "That took " $ ftime() - start $ " seconds." );

rand [function]

rand()

returns a random 'int' value in the range [0;RAND_MAX] - from 0, inclusive, to RAND_MAX, inclusive


randf [function]

randf()

returns a random 'real' value in the range [0;1] - from 0, inclusive, to 1, inclusive


srand [function]

srand( int seed )

specify a different seed value for the built-in pseudo-random number generator

srand( 5 ); // restart the generator with the value specified
srand( ftime() ); // restart the generator depending on the second the code was executed

hash_fnv [function]

hash_fnv( string buf, bool as_hexstring = false )

generate a hash, using the FNV-1a algorithm


hash_crc32 [function]

hash_crc32( string buf, bool as_hexstring = false )

generate a hash/checksum, using the CRC32 algorithm


va_get_args [function]

va_get_args()

return an array containing all arguments passed to the calling function


va_get_arg [function]

va_get_arg()

returns one of the arguments passed to calling function


va_arg_count [function]

va_arg_count()

return the number of arguments passed to the calling function


sys_call [function]

sys_call( func, this[, args..] )

calls the specified function with the specified this value and argument list

if argument count is only known at runtime, see sys_apply


sys_apply [function]

sys_apply( func, this, args )

calls the specified function with the specified this value and argument array

if argument count is known at compile time, prefer sys_call to this function


pcall [function]

pcall( callable func[, callable errh ])

calls the callable func, hiding internal errors from the caller or optionally passing them to callable errh

include "string";

function handler( type, msg )
{
    if( string_find( msg, "not found" ) !== null )
        sys_msg( type, "nooooooooooo" );
}

function handler2( type, msg )
{
    if( string_find( msg, "not found" ) !== null )
        return SGS_ERROR;
}

pcall(function(){ print x; }); // nothing
pcall(function(){ print x; }, handler ); // renamed warning
pcall(function(){ print x; }, handler2 ); // changed type to error

assert [function]

assert( var condition[, string message] )

if condition evaluates to 'false', emits an error "assertion failed" or if message is defined, "assertion failed: <message>"

assert( text, "text was not defined" );

eval [function]

eval( string code )

returns the result of evaluating the passed code string as SGScript code

eval("print 5;"); // prints 5

eval_file [function]

eval_file( string filename )

returns the result of evaluating the file pointed to by filename as SGScript code

eval_file("myfile.sgs"); // ???

compile_sgs [function]

compile_sgs( string code )

returns the generated bytecode or null + error info

compile_sgs( io_file_read( "myfile.sgs" ) ); // ???

include_library [function]

include_library( string lib[, bool override ] )

loads the global variables of the specific library lib in the state, returns success, as bool, emits a warning on failure

printvar( sin ); // warning, null
include_library( "math" );
printvar( sin ); // C function

include_file [function]

include_file( string file[, bool override ] )

executes the file pointed to by file, returns success, as bool, emits a warning on failure

include_file( "something.sgs" ); // loads something
include_file( "something.sgs" ); // does not load it again
include_file( "something.sgs", true ); // loads it again

include_shared [function]

include_shared( string file[, bool override ] )

runs the shared library pointed to by file, returns success, as bool, emits a warning on failure

include_shared( "sgsjson.dll" ); // load the JSON library DLL on Windows

include [function]

include( string file[, bool override ] )

tries to load a library or a file according to the include path


import_cfunc [function]

import_cfunc( string file, string funcname )

retrieves the funcname function of the shared library file, returns success, as bool, emits a warning on failure

Do not call 'sgscript_main' using this function! That function has different return value semantics so at best, something will work, a warning could be emitted and the worst case is that something will crash.

import_cfunc( "mydll.dll", "someSGScriptFunc" )();

sys_curfile [function]

sys_curfile()

returns the path of the file (as passed on load) that contains the currently executed code or null if the file cannot be determined (eval, C functions)

// a.sgs
print( sys_curfile() ); // prints "a.sgs"
// b.sgs
include "a.sgs";

sys_curfiledir [function]

sys_curfiledir()

returns the directory path of the file (as passed on load) that contains the currently executed code or null if the file cannot be determined (eval, C functions)

// ext/a.sgs
print( sys_curfiledir() ); // prints "ext"
// a.sgs
print( sys_curfiledir() ); // prints "."
// b.sgs
include "ext/a.sgs", "a.sgs";

sys_backtrace [function]

sys_backtrace( bool as_string = false )

returns the call stack function/line/file list, either as array of dicts, or as a string, formatted exactly like in error messages (via sgs_PushErrorInfo)

errprint( sys_backtrace( true ) ); // print backtrace to stderr
println( sys_backtrace().last.func ); // print name of current function

sys_msg [function]

sys_msg( int code, string message )

passes a message to the internal messaging system (one that's commonly used to report errors and warnings)

Different codes can be handled differently by the system. By default, SGS_ERROR code will stop execution and return to C code as soon as possible.


INFO [function]

INFO( string message )

passes a message to the internal messaging system


WARNING [function]

WARNING( string message )

passes a message to the internal messaging system


ERROR [function]

ERROR( string message )

passes a message to the internal messaging system

By default, SGS_ERROR code (the one this function uses internally) will stop execution and return to C code as soon as possible.


sys_abort [function]

sys_abort()

stops execution and returns to C code as soon as possible

sys_abort();
print( 5 ); // this line is not reached

app_abort [function]

app_abort()

calls the abort() function of the C standard library (crashes the application)


app_exit [function]

app_exit( code = 0 )

calls the exit() function of the C standard library (exits the application)


sys_replevel [function]

sys_replevel([ level ])

returns the current reported error level and optionally sets a new one

The effects of this function are not reverted automatically at any moment (unless implemented manually with hooks).

old_level = sys_replevel( SGS_ERROR ); // report only errors or worse
magic = calculate_magic(); // any warnings are never processed at this point
sys_replevel( old_level ); // restore the old reported level

sys_stat [function]

sys_stat( code )

prints info about virtual machine state, everything is implementation-defined

sys_stat( 11 ); // dumps all globals

errno [function]

errno( as_string = false )

returns the last relevant error number for the C standard library, as an integer or a string if as_string is set

data = io_file_read( "doesnotexist" ); // file that does not exist
print errno(); // prints 2
print errno(true); // prints "No such file or directory" on Windows

errno_string [function]

errno_string( int code )

returns the error string for the given code

print errno_string(2); // prints "No such file or directory" on Windows

errno_value [function]

errno_value( string key )

returns the number for the error key (for "ENOENT" it would return 2)

data = io_file_read( "doesnotexist" );
if( errno() == error_string("ENOENT") )
    println( "file does not exist" );

dumpvar_ext [function]

dumpvar_ext( var, int depth = 5 )

similar to printvar_ext() but returns the dump instead of printing it

sys_error( SGS_INFO, "Extended variable info:\n" $ dumpvar(data) );

dumpvar [function]

dumpvar( ... )

similar to printvar() but returns the dumps, concatenated, instead of printing them


gc_collect [function]

gc_collect()

runs the garbage collector on the virtual machine, waiting until it has finished

a = [];
a.push(a); // creates a circular dependency
a = null; // a is not actually freed
gc_collect(); // a is freed now

serialize [function]

serialize( var )

converts the variable to a byte buffer (string), containing the serialized data that can be recreated with unserialize() or returns null and emits a warning on failure

data = serialize({ name = "A", info = "B" });
print data; // prints random-looking, yet deterministic garbage
print unserialize(data); // prints {name=A,info=B}

unserialize [function]

unserialize( string data[, array|dict funcs ])

recreates a variable from the buffer with serialized data or returns null and emits a warning on failure

data = serialize({ name = "A", info = "B" });
print data; // prints random-looking, yet deterministic garbage
print unserialize(data); // prints {name=A,info=B}

SGS_*** [constants]

SGS_INFO, SGS_WARNING, SGS_ERROR

defined to the values of the C macros, respectively 100, 200 and 300


VT_*** [constants]

VT_NULL, VT_BOOL, VT_INT, VT_REAL, VT_STRING, VT_FUNC, VT_CFUNC, VT_OBJECT, VT_PTR

these constants are defined to the values of the C macros (with the prefix "SGS_VT_" in C) and can be compared with the values returned in typeid()


RAND_MAX [constant]

RAND_MAX

the maximum number that can be returned by rand()


_G [superglobal]

A hard-coded global value that points to the global dictionary. Can be used to access non-identifier globals and change the global dictionary.

_G["$diff"] = 5; // no way to access this via usual globals
_G = {}; // global value dictionary is changed, previous functions are lost unless stored somewhere

array [object]


array.push [method]

array.push( ... )

appends the variables passed to the end of array in the same order, returns the array for chaining

a = [ 5 ];
a.push( 6, 7 ).push( 8 ); // a = [5,6,7,8]

array.pop [method]

array.pop()

removes one item from the end of array or emits a warning if there are no items in the array, returns the removed item

a = [ 5 ];
a.pop(); // array is empty now
a.pop(); // warning: "array is empty, cannot pop"

array.shift [method]

array.shift()

removes one item from the beginning of array or emits a warning if there are no items in the array, returns the removed item

a = [ 5, 6 ];
a.shift(); // a = [6], returned 5

array.unshift [method]

array.unshift( ... )

prepends the variables passed to the beginning of array in the same order, returns the array for chaining

a = [ 5 ];
a.unshift( 6, 7 ); // a = [6,7,5] now

array.insert [method]

array.insert( int pos, ... )

inserts the variables passed (all arguments after first) to the position specified in the array or emits a warning on failure (index out of bounds), returns the array for chaining

a = [ 5, 7 ];
a.insert( 1, 6 ); // inserts 6 at position 1 (before item with index 1)
a.insert( -1, 8 ); // appends to the end of array, a = [5,6,7,8] now

array.erase [method]

array.erase( int[, int] )

erases item or a range of items from the array, depending on the arguments passed or emits a warning on failure, returns the array for chaining

a = [ 5, 6, 7, 8 ];
a.erase( 1, 2 ); // erases all items between position 1 and 2, including; gives a = [5,8]
a.erase( 0 ); // a = [8]

array.part [method]

array.part( int from[, int max ] )

returns a new array starting from index from, with the max. size max

a = [ 5, 6, 7, 8 ];
a.part( 1, 2 ); // returns [6,7]
a.part( -5, 2 ); // returns [5]
a.part( 3 ); // returns [8]

array.clear [method]

array.clear()

erases all items from the array, returns the array for chaining

a = [ 1, "asd", 8 ];
a.clear(); // a = []

array.reverse [method]

array.reverse()

reverses the order of items in the original array, returns the original array for chaining

a = [ 1, 2, 3 ];
b = a;
a.reverse(); // a = [3,2,1]
print( b ); // prints [3,2,1]

array.resize [method]

array.resize( int size )

changes the size of the array, returns the array for chaining

a = [ 5, 6, 7 ];
a.resize( 5 ); // a = [5,6,7,null,null]
a.resize( 2 ); // a = [5,6]

array.reserve [method]

array.reserve( int capacity )

reserves the space for the requested number of elements in the array, returns the array for chaining

a = [ 5, 6, 7 ];
a.capacity( 1 ); // nothing happens
a.capacity( 5 ); // a.capacity = 5 and two variable additions can now happen without reallocations

array.sort [method]

array.sort([ bool reverse ])

sorts the array using the sgs_Compare C API function for comparisons, returns the array for chaining

a = [ 6, 8, 7, 5 ];
a.sort(); // a = [5,6,7,8]

array.sort_custom [method]

array.sort_custom( callable[, bool reverse ] )

sorts the array using the callable for comparisons, returns the array for chaining

This function is considerably slower than array.sort or array.sort_mapped so prefer those if performance matters.

a = [ 6, 8, 7, 5 ];
// this code will sort numbers into odd/even ones and in ascending order
a.sort_custom( function(a,b){return a-b+(b%2-a%2)*1000; } ); // a = [5,7,6,8]

array.sort_mapped [method]

array.sort_mapped( array map[, bool reverse ] );

sorts the array by sorting the passed array and applying the index map to the first one, returns the array for chaining

a = [ 5, 6, 7, 8 ];
b = [ 3, 1, 4, 2 ];
a.sort_mapped( b ); // a = [6,8,5,7]

array.find [method]

array.find( var item[, bool strict[, int from ]] )

attempts to find item in array, starting from 0 or the index passed with from, if it exists, using basic or strict equality comparisons (depending on strict), returning the index or 'null' if item was not found

a = [ 5, 6, 7, 8 ];
a.find( "7" ); // returns 2
a.find( "7", true ); // returns null

array.remove [method]

array.remove( var item[, bool strict[, bool all[, int from ]]] )

attepts to find and remove first or all item variables in array (depending on all), according to the rules specified in array.find(), returning the number of removed items

a = [ 5, 2, 6, 7, 8, 2 ];
a.remove( "7" ); // returns 1; a = [5,2,6,8,2]
a.remove( "6", true ); // returns 0; a remains unchanged
a.remove( 2, false, true ); // returns 2; a = [5,6,8]

array.unique [method]

array.unique( bool strconv = false )

returns an array without duplicates, where a duplicate is a strictly equal variable or a string conversion match

a = [ 5, 3, 2, 3, 2, "3" ];
a.unique(); // returns [5,3,2,"3"]
a.unique( true ); // returns [5,3,2]

array.random [method]

array.random( int num )

return num randomly chosen items from the array


array.shuffle [method]

array.shuffle()

change the order of items in the array


dict [object]


map [object]


class [object]


ALL SGScript core functions (A-Z)


Formatting library ("fmt")

This library includes functions and objects for parsing binary and text buffers.

Functions:

Objects and their methods:


fmt_pack [function]

fmt_pack( string fmt, ... )

packs the given arguments using the format fmt and returns the byte buffer or returns null and emits a warning on failure

printvar( fmt_pack( "3cf", 0, 1, 2, 3 ) ); // prints 'string [7] "\x00\x01\x02\x00\x00@@"'

fmt_unpack [function]

fmt_unpack( string fmt, string data )

unpacks the byte buffer data using the format fmt, returns unpacked items (possibly in an array)

print fmt_unpack( "3ld", fmt_pack( "3ld", 0, 1, 2, 3 ) ); // prints [0,1,2,3]

fmt_pack_count [function]

fmt_pack_count( string fmt )

calculates the number of items to be expected in an unpacked array / required to make a successful fmt_pack call

print fmt_pack_count( "3ld" ); // prints 4

fmt_pack_size [function]

fmt_pack_size( string fmt )

calculates the number of bytes generated by a successful fmt_pack call / required to successfully unpack data using the given format

print fmt_pack_size( "3ld" ); // prints 20

fmt_base64_encode [function]

fmt_base64_encode( string data )

encodes data to produce base64 text data

print fmt_base64_encode( "hello world" ); // prints "aGVsbG8gd29ybGQ="

fmt_base64_decode [function]

fmt_base64_decode( string b64text )

decodes base64 text data

fmt_base64_decode( fmt_base64_encode( "hello world" ) ) == "hello world" // returns true

fmt_text [function]

fmt_text( [int prealloc,] string text, ... )

parses all format specifiers in text and returns the result

see string_format if you need position (argument index) specifications in the format string

print fmt_text( "{d} -> {x}", 1337, 1337 ); // prints "1337 -> 539"
print fmt_text( "null: {d}, {s}, {c}", null, null, null ); // prints "null: #error#, #error#, null" and emits two warnings for item 1 and item 2
print fmt_text( "pi: {f10.10r} {g10r} {E10r}", M_PI, M_PI, M_PI ); // "pi: 3.1415926536 3.14159    3.141593E+000"

fmt_parser [function]

fmt_parser( callable[, buffersize ] )

creates a fmt_parser object, connected to the callable

f = io_file( "test.txt", FILE_READ );
// usually it is easier to use @fmt_file_parser instead of the next line of code
p = fmt_parser( function( num ) use( file ){ if( file.eof() ) return null; return file.read( num ); } );

fmt_string_parser [function]

fmt_string_parser( string, offset = 0[, buffersize ] )

creates a fmt_parser object, connected to a string reader object, initialized to the given offset and buffer size

p = fmt_string_parser( "this is a test" );
p.readcc( "a-z" ); // returns "this"

fmt_file_parser [function]

fmt_file_parser( file[, buffersize ] )

creates a fmt_parser object, connected to a file reader object, initialized to the given buffer size

p = fmt_file_parser( io_file( "something.txt", FILE_READ ) );
p.readcc( "a-z" ); // returns something

fmt_charcc [function]

fmt_charcc( string char, string class )

checks if the first character of string char is included in the character class class

fmt_charcc( ".", "a-zA-Z0-9" ); // returns false
fmt_charcc( "x", "a-zA-Z0-9" ); // returns true

fmt_parser [object]


fmt_parser.read [method]

fmt_parser.read( int num )

reads at most num bytes from stream and returns them as string

stream = fmt_string_parser( "action" );
stream.read( 5 ); // returns "actio"

fmt_parser.getchar [method]

fmt_parser.getchar( bool peek = false, bool as_int = false )

returns a character from stream

stream = fmt_string_parser( "action" );
stream.read( true ); // returns "a"
stream.read( true, true ); // returns 97
stream.read(); // returns "a"
stream.read(); // returns "c"

fmt_parser.readcc [method]

fmt_parser.readcc( string class, int num = 2^31-1 (0x7fffffff) )

reads and returns at most num bytes that match the character class class

stream = fmt_string_parser( "what is this" );
stream.readcc( "a-z" ); // returns "what"
stream.readcc( "^a-z" ); // returns " "

fmt_parser.skipcc [method]

fmt_parser.skipcc( string class, int num = 2^31-1 (0x7fffffff) )

skips at most num bytes that match the character class class and returns the number of bytes skipped

stream = fmt_string_parser( "what is this" );
stream.skipcc( "a-z" ); // returns 4
stream.skipcc( "^a-z" ); // returns 1

fmt_parser.read_real [method]

fmt_parser.read_real( bool as_real = true )

returns characters read with the character class "-+0-9.eE", optionally returned as a real value


fmt_parser.read_int [method]

fmt_parser.read_int( bool as_int = true )

returns characters read with the character class "-+0-9A-Fa-fxob", optionally returned as an int value


fmt_parser.read_binary_int [method]

fmt_parser.read_binary_int( bool as_int = true )

returns characters read with the character class "0-1", optionally returned as an int value


fmt_parser.read_octal_int [method]

fmt_parser.read_octal_int( bool as_int = true )

returns characters read with the character class "0-7", optionally returned as an int value


fmt_parser.read_decimal_int [method]

fmt_parser.read_decimal_int( bool as_int = true )

returns characters read with the character class "-+0-9", optionally returned as an int value


fmt_parser.read_hex_int [method]

fmt_parser.read_hex_int( bool as_int = true )

returns characters read with the character class "0-9a-fA-F", optionally returned as an int value


fmt_parser.check [method]

fmt_parser.check( string str, bool ci = false, bool partial = false )

returns whether the specified string was found at the current position


ALL SGScript formatting functions (A-Z)


I/O library ("io")

This library contains the functions necessary to work with the file system (files and directories).

Functions:

Objects and their methods:

Constants:


io_setcwd [function]

io_setcwd( string cwd )

sets the current working directory, returns bool/sets errno


io_getcwd [function]

io_getcwd()

returns the current working directory or null, if for some reason an error occured


io_getexecpath [function]

io_getexecpath()

returns the path of the executable file the script is executed in


io_rename [function]

io_rename( string path, string newpath )

attempts to rename the file, returns bool/sets errno


io_file_exists [function]

io_file_exists( string file )

checks if file exists and is accessible by the process at the moment, returns true on success, false otherwise


io_dir_exists [function]

io_dir_exists( string dir )

checks if directory exists and is accessible by the process at the moment, returns true on success, false otherwise


io_stat [function]

io_stat( string fsitem )

returns info about the file system item fsitem, as dict


io_dir_create [function]

io_dir_create( string path, int mode = 0o777 )

attempts to create a directory at the specified path, with the specified access mode mode, returns bool/sets errno


io_dir_delete [function]

io_dir_delete( string path )

attempts to delete a directory at the specified path, returns bool/sets errno


io_file_delete [function]

io_file_delete( string path )

attempts to delete a file at the specified path, returns bool/sets errno


io_file_write [function]

io_file_write( string path, string data )

writes the byte buffer data to the file pointed to by path, returns bool/sets errno


io_file_read [function]

io_file_read( string path )

reads the byte buffer from file at path, returns buffer as string or null/sets errno


io_file [object]


io_file.open [method]

io_file.open( string name, int mode )

closes the previously open file if any, opens the file name for operation mode mode, returns bool/sets errno

f = io_file();
f.open( "file" ); // returns true or false, sets errno accordingly

io_file.close [method]

io_file.close()

closes the previously open file, if any, returns whether the file was open or not

f = io_file( "file.txt" );
f.close(); // returns true if the file existed
f.close(); // returns false

io_file.read [method]

io_file.read( int num )

reads and returns at most num bytes from file, sets errno


io_file.write [method]

io_file.write( string data )

writes the byte buffer data to the file, sets errno


io_file.seek [method]

io_file.seek( int off, int mode )

sets the offset in file, returns bool/sets errno


io_file.flush [method]

io_file.flush()

flushes a buffered file, returns bool


io_file.setbuf [method]

io_file.setbuf( int size )

sets the size of file buffer (0 to disable buffering), returns bool


io_file [function]

io_file([ string name, int mode ])

creates and returns a file, optionally allowing to open it on creation


io_dir (directory_iterator) [object]


io_dir [function]

io_dir( string dir )

creates a directory iterator for the directory dir, sets errno, returns null and emits a warning on failure


FILE_*** [constants]

FILE_READ, FILE_WRITE

mode constants for io_file.open / io_file [function]


SEEK_*** [constants]

SEEK_SET, SEEK_CUR, SEEK_END

mode constants for io_file.seek


FST_*** [constants]

FST_UNKNOWN, FST_FILE, FST_DIR

file system item type constants for io_stat


ALL SGScript I/O functions (A-Z)


Math library ("math")

This library contains the basic math functions for processing real values.

Functions:

Constants:


abs [function]

abs( x )

returns the absolute value of x, as real

abs( 2.2 ); // real (2.2)
abs( -3.1 ); // real (3.1)

floor [function]

floor( x )

returns the largest integer that is not bigger than x, as real

floor( 3.4 ); // real (3)
floor( 3.8 ); // real (3)
floor( 4.2 ); // real (4)
floor( -3.1 ); // real (-4)

ceil [function]

ceil( x )

returns the smallest integer that is not smaller than x, as real

ceil( 3.4 ); // real (4)
ceil( 3.8 ); // real (4)
ceil( 4.2 ); // real (5)
ceil( -3.1 ); // real (-3)

round [function]

round( x )

returns the closest integer to x, as real

round( 3.4 ); // real (3)
round( 3.8 ); // real (4)
round( 4.2 ); // real (4)
round( -3.1 ); // real (-3)

pow [function]

pow( x, y )

returns x raised to the power y, as real

pow( 2, 5 ); // real (32)
pow( 9, 0.5 ); // real (3)
pow( -1, 0.5 ); // null; Warning: pow(): mathematical error

sqrt [function]

sqrt( x )

returns the square root of x, as real

sqrt( 16 ); // real (4)
sqrt( -1 ); // null; Warning: sqrt(): mathematical error

log [function]

log( x, y )

returns the base-`y` logarithm of x, as real

log( 9, 3 ); // real (2)
log( -1, 3 ); // .. or ..
log( 3, 0 ); // .. or ..
log( 3, 1 ); // null; Warning: log(): mathematical error

sin [function]

sin( x )

returns the sine of angle x in radians, as real

sin( 0 ); // real (0)
sin( M_PI / 2 ); // real (1)
sin( M_PI / 4 ); // real (0.707107)

cos [function]

cos( x )

returns the cosine of angle x in radians, as real

sin( 0 ); // real (1)
sin( M_PI ); // real (-1)
sin( M_PI / 4 ); // real (0.707107)

tan [function]

tan( x )

returns the tangent of angle x in radians, as real

tan( 0 ); // real (0)
tan( 1 ); // real (1.55741)
tan( M_PI / 4 ); // real (1)

asin [function]

asin( x )

returns the arcsine of x (angle in radians), as real

asin( -1 ); // real (-1.5708)
asin( 0 ); // real (0)
asin( 2 ); // null; Warning: asin(): mathematical error

acos [function]

acos( x )

returns the arccosine of x (angle in radians), as real

acos( -1 ); // real (3.14159)
acos( 0 ); // real (1.5708)
acos( 2 ); // null; Warning: acos(): mathematical error

atan [function]

atan( x )

returns the arctangent of x (angle in radians), as real

atan( 0 ); // real (0)
atan( 1 ); // real (0.785398)
atan( 9999999 ); // real (1.5708)

atan2 [function]

atan2( y, x )

returns the extended arctangent of y/x (angle in radians), as real

Due to the common requirement to use this function to determine the angle between two somewhat random points (usually from a simulation), it will not emit a warning when both arguments are 0 - it will return 0 instead.

atan2( 0, 1 ); // real (0)
atan2( 1, 0 ); // real (1.5708)
atan2( -1, -1 ); // real (-2.35619)
atan2( 0, 0 ); // real (0)

deg2rad [function]

deg2rad( x )

returns angle, converted from degrees to radians, as real

deg2rad( 0 ); // real (0)
deg2rad( 180 ); // real (3.14159)
deg2rad( -90 ); // real (-1.5708)

rad2deg [function]

rad2deg( x )

returns angle, converted from radians to degrees, as real

rad2deg( 0 ); // real (0)
rad2deg( M_PI ); // real (180)
rad2deg( -M_PI / 2 ); // real (-90)

M_*** [constants]

M_PI

the ratio of circumference of a circle to its diameter (pi)

M_E

the natural logarithmic base (e)


ALL SGScript math functions (A-Z)


OS library ("os")

Functions:

Constants:


os_gettype [function]

os_gettype()

returns the name of the closest known match for the operating system type, defined at library compile time


os_command [function]

os_command( string cmd )

passes a command to the OS command processor, returns the integer return value

this function can be extremely unsafe in multithreaded/incontrollable environments due to the completely undefined outcome of the call


os_getenv [function]

os_getenv( string var )

returns the value for the environment variable var or null, if there is no such value


os_putenv [function]

os_putenv( string cmd )

sets the value for the environment variable specified in command cmd, returns success as bool


os_time [function]

os_time( real tz = <local> )

returns the time in seconds, as integer, optionally from a different time zone tz


os_get_timezone [function]

os_get_timezone( bool as_string = false )

returns the time zone set in the operating system, optionally as string in the format "(+/-)HH:MM"


os_date_string [function]

os_date_string( string fmt, int time = os_time() )

returns the date/time string in the format fmt, optionally for a different time time


os_parse_time [function]

os_parse_time( int time = os_time() )

returns time split into parts, as dict


os_make_time [function]

os_make_time( int sec, int min = 0, int hour = 0, int mday = 0, int mon = 0, int year = 0 )

returns time as UNIX timestamp, generated from the arguments, using them as hints (under-/overflows may have some unexpected behavior)


os_get_locale [function]

os_get_locale( int which )

returns the currently set locale for the specified category


os_set_locale [function]

os_set_locale( int which, string locale )

sets the locale for the specified category, returning whether the call was successful


os_get_locale_format [function]

os_get_locale_format()

retrieve the formatting info of the currently set locale as a dict


os_locale_strcmp [function]

os_locale_strcmp( string a, string b )

compare two strings using locale to return correct sign for inequalities (good for language-correct sorting)


LC_*** [constants]

These constants specify the categories for which locale can be changed.


ALL SGScript OS functions (A-Z)


Regular expression library ("re")

This library includes regular expression match & replace functions.

Functions:

Constants:


re_match [function]

re_match( string str, string pattern, int flags = 0, int offset = 0 )

check for matches in string str for pattern, returning whether a match was found or details of the first match, as specified in flags


re_match_all [function]

re_match_all( string str, string pattern, int flags = 0, int offset = 0 )

check for matches in string str for pattern, returning the number of matches or details of all matches, as specified in flags


re_replace [function]

re_replace( string str, string pattern, string replacement )

find and replace all occurrences of pattern in string str with the replacement string


RE_RETURN_*** [constants]

These constants are used in re_match / re_match_all to specify the format of the return value.

If none of these are specified (flags = 0), only the success state is returned (true/false/match count).


ALL SGScript RegExp functions (A-Z)


String library ("string")

This library contains the string handling functions. In all functions, except the utf-8 ones, it is assumed that strings are byte buffers where each byte is one character. If correct indices are applied, many of them will work with multibyte strings.

Objects:

Functions:

Constants:


string_utf8_iterator [object]


string_cut [function]

string_cut( string str, int from[, int to[, int flags]] )

returns a part of string str, from and to being positions of the first and last character returned, respectively

string_cut( "01234567", 3, 5 ); // string [3] "345"

string_part [function]

string_part( string str, int from[, int len[, int flags]] )

returns a part of string str, starting at from, at most len characters

string_part( "01234567", 3, 3 ); // string [3] "345"

string_reverse [function]

string_reverse( string str )

returns str with all the bytes in reversed order

This function will not work correctly with multibyte-encoded strings.

string_reverse( "noitca" ); // string [6] "action"

string_pad [function]

string_pad( string str, int tgtsize, string padstr = " ", int flags = STRING_PAD_RIGHT )

return the string str, padded from template padstr up to the size tgtsize according to flags

string_pad( "padded", 10 ); // string [10] "padded    "
string_pad( "center", 10, "_", STRING_PAD_LEFT | STRING_PAD_RIGHT ); // string [10] "__center__"

string_repeat [function]

string_repeat( string str, int count )

return the string str, appended to itself `count`-1 times or an empty string if count is equal to 0

string_repeat( "na", 6 ); // string [12] "nananananana"
string_repeat( "none", 0 ); // string [0] ""

string_count [function]

string_count( string str, string substr, bool overlap = false )

returns the number of substrings substr found in string str

string_count( "abababa", "aba" ); // int 2
string_count( "abababa", "aba", true ); // int 3

string_find [function]

string_find( string str, string substr, int offset = 0 )

returns the position of first found substring substr in string str, starting at offset

string_find( "what hat", "hat" ); // int 1
string_find( "what", "hat", 2 ); // null

string_find_rev [function]

string_find_rev( string str, string substr, int offset = 0 )

returns the position of last found substring substr in string str, starting at offset

string_find_rev( "what hat", "hat" ); // int 5
string_find_rev( "what", "hat", 2 ); // int 1

string_replace [function]

string_replace( string str, string from, string to )

string_replace( string str, array from, string to )

string_replace( string str, array from, array to )

replaces parts of string str, specified in from, to the respective values passed in to

string_replace( "loaded %num files", "%num", 5 ); // string [14] "loaded 5 files"
string_replace( "abcd", ["a","b","c","d"], [1,2,3,4] ); // string [4] "1234"
string_replace( "1234", ["1","2","3","4"], ["x","y"] ); // string [4] "xyxy"

string_translate [function]

string_translate( string str, iterable repmap )

replaces parts of string str, specified in the keys of repmap, to the matching values of the same iterable

string_translate( "found %a files and %b folders", {"%a" = 5, "%b" = 17} ); // string [28] "found 5 files and 17 folders"

string_trim [function]

string_trim( string str, string chars = " \t\r\n", int flags = STRING_TRIM_LEFT | STRING_TRIM_RIGHT )

removes the specified characters from the specified sides of the string

string_trim( "  space  " ); // string [5] "space"
string_trim( "..something!..", ".!", STRING_TRIM_RIGHT ); // string [11] "..something"

string_toupper [function]

string_toupper( string str )

converts all ASCII lowercase letter characters of the string to uppercase

string_toupper( "Test" ); // string [4] "TEST"

string_tolower [function]

string_tolower( string str )

converts all ASCII uppercase letter characters of the string to lowercase

string_toupper( "Test" ); // string [4] "test"

string_compare [function]

string_compare( string str1, string str2, int max = 0, int from = 0 )

compares the two strings or the specified portions of them

string_compare( "what", "whaT" ); // int 1
string_compare( "what", "whaT", 3 ); // int 0
string_compare( "file.txt", ".txt", 0, -4 ); // int 0

string_implode [function]

string_implode( array items, string sep )

concatenates the string representations of array items values, putting a string sep between each two

string_implode( ["one","two","three"], ", " ); // string [15] "one, two, three"

string_explode [function]

string_explode( string str, string sep )

splits the string str into an array of substrings, separated by string sep

string_explode( "www.example.com", "." ); // ["www","example","com"]
string_explode( "x", "-" ); // ["x"]
string_explode( "/some//data", "/" ); // ["","some","","data"]

string_charcode [function]

string_charcode( string str, int offset = 0 )

returns the byte value / ASCII character code of the specified byte in the string

string_charcode( "Test" ); // int 84
string_charcode( "Test", 3 ); // int 116

string_frombytes [function]

string_frombytes( int byteval )

string_frombytes( array bytes )

returns a string, created from either one byte value (overload #1) or an array of byte values (overload #2)

string_frombytes( 53 ); // string [1] "5"
string_frombytes([ 84, 101, 115, 116 ]); // string [4] "Test"

string_utf8_decode [function]

string_utf8_decode( string ustr )

returns an array of Unicode code points, decoded from the UTF-8 string ustr

string_utf8_decode( "pie" ); // [112,105,101]
string_utf8_decode( "код" ); // [1082,1086,1076]
string_utf8_decode( "標準" ); // [27161,28310]

string_utf8_encode [function]

string_utf8_encode( array cplist )

returns a UTF-8 string, composed from the Unicode code point list cplist

string_utf8_encode([ int cp0[, int cp1, ... ]])

returns a UTF-8 string, composed from the Unicode code point list passed in argument list

Without proper terminal software UTF-8 strings will not be displayed correctly (as is the case on Windows).

string_utf8_encode( [112,105,101] ); // string [3] "pie"
string_utf8_decode( [1082,1086,1076] ); // string [6] "код"
string_utf8_decode( [27161,28310] ); // string [6] "標準"

string_utf8_offset [function]

string_utf8_offset( string ustr, int charnum[, int byteoff ])

returns byte offset of character in UTF-8 string, optionally skipping the specified number of bytes

string_utf8_offset( "標準", 2 ); // returns 6

string_utf8_length [function]

string_utf8_length( string ustr, int byteoff = 0[, int numbytes[, int flags ]])

returns length of UTF-8 string or the specified part of it

string_utf8_length( "標準", 3 ); // returns 1

string_utf8_iterator [function]

string_utf8_iterator( string ustr, int byteoff = 0 )

creates a UTF-8 code point iterator object

it = string_utf8_iterator( "標準" ); // returns string_utf8_iterator object
iter_advance( it ); // go to position 0
iter_getdata( it ); // returns 27161

string_format [function]

string_format( [int prealloc,] string text, ... )

parses all format specifiers in text and returns the result

see fmt_text if you don't need the position (argument index) specifications

print string_format( "{1:d} -> {1:x}", 1337 ); // prints "1337 -> 539"

ALL SGScript string functions (A-Z)


Included tools

Executables

Extensions


Virtual Machine (sgsvm)

This is the default standalone environment for SGScript, useful for running scripts in a portable way.

Command line syntax

sgsvm [files|options]
sgsvm [options] -p|--program <srcname>[, <arguments>]

Options

Example usage

Additional info


Compiler (sgsc)

This is the standalone script compiler and instruction listing generator for SGScript.

Command line syntax

sgsc [file|options]

Additional info

Example usage


Executable generator for Windows (sgsexe)

Utility to combine a single script with the virtual machine. After compilation, the executable passes all input arguments as-is as argc and argv to the script.

Command line syntax

sgsexe <output-file> <script-file>

Language test application (sgstest)

The application runs all test scripts in ./tests directory. File handling rules are as follows:

The sort order broken down:

The application sgstest must be run from root, like so: bin/sgstest. It generates two log files: ./tests-errors.log and ./tests-output.log.


API test application (sgsapitest)

This application tests the core programming interface. It generates two log files: ./apitests-errors.log and ./apitests-output.log.


C++ binding compiler test application (sgscppbctest)

This application tests the C++ programming interface that utilizes the binding compiler.


Lightweight C++ binding test application (sgscppbindtest)

This application tests the C++ programming interface that utilizes the lightweight binding extension.


Multithreading safety test application (mttest)

This application tests the SGScript engine's ability to work with more than one thread (different instances for each) at the same time.


Profiler

This is an engine profiler hook extension. It supports three processing modes.

Modes

Functions

Usage example

sgs_Prof profiler; // keep this allocated while it is linked to engine
// initialize and attach the profiler
sgs_ProfInit( contextPtr, &profiler, [SGS_PROF_FUNCTIME|SGS_PROF_OPTIME|SGS_PROF_MEMUSAGE] );
// ...do things with the engine...
sgs_ProfDump( &profiler ); // dump the data (done through @sgs_Write* functions)
// free the profiler - must be done before freeing the engine
sgs_ProfClose( &profiler );

Interactive debugger

This is an engine debugging hook extension. It provides the opportunity to interactively introspect the engine state on each message (info/warning/error).

Functions

Usage example

sgs_IDbg debugger; // keep this allocated while it is linked to engine
// initialize and attach the debugger
sgs_InitIDbg( contextPtr, &debugger );
// ...do things with the engine...
// free the debugger
sgs_CloseIDbg( contextPtr, &debugger );

Additional info


Serialization in SGScript

In SGScript, serialization is conversion to a binary stream of a specific format. Serialization in the language API is done by calling the "serialize" function and deserialization is done with "unserialize". The C API has similar functions: sgs_Serialize / sgs_SerializeObject and sgs_Unserialize, respectively.

check the "Possible gotchas" part of this page if it is intended to trust the end user with access to serialized data

The format

Serialization

Deserialization

Possible gotchas


Secure sandbox environment

To ensure safety of the underlying environment, there are functions that need to be protected or disabled.

Critical (access to file system, possibility of taking control of the machine):

Information control (access to data about the system

Sandbox example

restrict = function( name )
{
    println( "==\n= The use of '" $ name $ "' is restricted!\n==" );
};
closure = function( clbl, data )
{
    return function() use( clbl, data )
    {
        args = va_get_args();
        args.unshift( data );
        sys_apply( clbl, this, args );
    };
};
safe_include_lib = function( data, libname )
{
    libname = tostring( libname );
    if( ["string","math","re","fmt","os"].find( libname ) === null )
    {
        println( "info: cannot include files and system access libraries here" );
        return;
    }
    data( libname );
    if( libname == "os" )
    {
        unset( _G, "os_command" );
        unset( _G, "os_getenv" );
        unset( _G, "os_putenv" );
    }
};
safe_include = function( libname )
{
    return include_library( libname );
};
global include_library = closure( safe_include_lib, include_library );
global include = safe_include;
global include_shared = closure( restrict, "include_shared" );
global import_cfunc = closure( restrict, "import_cfunc" );
global include_file = closure( restrict, "include_file" );
global eval_file = closure( restrict, "eval_file" );

include "string", "math", "re", "fmt", "os";