SGScript documentation - v1.4.1

Table of Contents


SGScript - description

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

ctrl.DReset();
foreach( at, item : speech )
{
    distfromlast = speech.size - at - 1;
    a = 0.9 * pow( 0.7, distfromlast );
    ctrl.DCol( 0.9, a );
    ctrl.DText( item.text,
        x + padding, y + padding + lineheight / 2,
        HALIGN_LEFT, VALIGN_CENTER );
    y += lineheight;
}

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.

It adds dynamic typing and built-in serialization to C. Unlike Lua, it has C-like syntax and proper 0-based indexing and advanced object model, and much more versatile error handling. It has the consistency you'd want after working with PHP, and is considerably more lightweight. It untangles some of the mess JavaScript has introduced, and gives coroutines for a considerable boost in power of expression. And, unlike Python, SGScript won't care as much about formatting.

You can find more about the differences at the "Why SGScript?" page.

The language supports:

The standard library includes:


Why SGScript?

Native serialization

[+] SGScript, Python
[-] JavaScript, Lua, Squirrel

Without any extra work, most of the data can be converted to a byte buffer so that it could be stored in a file or sent over a network and later converted back again. Languages that don't have it will require extra effort to get it and make sure it works with all kinds of custom objects. How much extra effort? Well, try googling for "lua serialize userdata". I didn't find a single way. SGScript - easy: https://github.com/snake5/sgscript/blob/6e9349a5a1ef5210ee440301b889f9afd78291be/ext/sgsxgmath.c#L248

Reference counted memory management support

[+] SGScript, Python, Squirrel
[-] JavaScript, Lua

This is a preferred method to garbage collection since it releases resources as soon as possible, avoiding random stalls throughout the game and thus providing a smooth gameplay experience. There are algorithms that reduce these stalls (incremental/generational garbage collection) but, given enough objects, they will be noticeable again. Source: http://sealedabstract.com/rants/why-mobile-web-apps-are-slow/

Coroutines

[+] SGScript, Lua, Squirrel, Python
[-] JavaScript (only generators are supported)

True cooperative multitasking allows the direction of timed events to be greatly simplified. SGScript goes one step further and also provides helper constructs (thread, subthread, sync, race) to make things as simple as possible for the user.

Custom native objects with complex links

[+] SGScript, Python, JavaScript (partial support)
[-] Lua, Squirrel

These are objects that can be created in C/C++, with special interfaces that support operator overloading, serialization, debug printing, conversions, cloning, type name and iterator retrieval, index and property retrieval. If not used, this feature has no cost, however it helps greatly with defining fast and accessible interfaces by encapsulating native resource management and access. To see what SGScript objects are all about, check the previous GitHub link, there's quite a lot of them.

Native arrays

[+] SGScript, Python, Squirrel, JavaScript (partial support)
[-] Lua

Native arrays (not to be confused with arrays that contain native data types, that is a subset of these) offer increased performance and memory-friendly storage over arrays made from hash tables. Array stores size as uint32, capacity as uint32 and values (16 bytes + extended data in SGScript) x size. A table would store all the same + keys (16 bytes + extended data) + hash array (size may differ but it's generally another array with size, capacity and a list of hash and index values). When arrays are considered, less (memory usage) is more (capacity).

Map support (all non-string/number keys)

[+] SGScript, Python, JavaScript (requires the support of an extension)
[-] Lua, Squirrel (some types are not supported in both)

The ability to map any variable to any other variable provides extended metadata storage possibilities - it can be stored without modifying the original variable.

m = map();
m[ sprite_obj ] = { high = 5 };

Game math library

[+] SGScript, Python, Lua, JavaScript
[-] Squirrel

A library with vector/matrix objects and functions for games. Not having to rewrite at least the bindings for it saves a lot of time.

Native debugging/profiling facilities

[+] SGScript, Python, JavaScript (support differs between JS engines)
[-] Lua, Squirrel

Introspective debugging and time/memory usage profiling can help resolve various issues found. SGScript supports call stack time, instruction time and call stack memory usage profilers out-of-the-box. At any point, all data can be dumped via the built-in output facilities that can be rerouted to any file or parser.

They are written in C to ensure a practically minimal performance impact while profiling. Significantly less than if the profiler was written in Lua, which is the main solution there. There's also access to some stats in SGScript so it is easy to see, for example, how many new allocations were done each frame.

Advanced native function argument parsing facilities.

[+] SGScript, Python
[-] Lua, Squirrel, JavaScript

Every modern scripting engine should have a function that parses and validates function arguments according to a specification and puts the data in the specified locations. With bigger functions it saves you from writing a lot of boilerplate code.

SGScript:
SGSFN( "fmt_string_parser" );
if( !sgs_LoadArgs( C, "?m|ii", &off, &bufsize ) ) // in case of type mismatch, emits a warning
    return 0; // ... and returns here to continue execution
Lua: (source: http://forums.tigsource.com/index.php?topic=36737.0)
float x  =luaL_checknumber(L,1); // in case of type mismatch, emits a fatal error, cannot continue script execution after this function call
float y  =luaL_checknumber(L,2); // same here
const char* str=luaL_checkstring(L,3); // same here

Non-fatal error messaging facilities without exceptions

[+] SGScript
[-] Python, Lua, Squirrel, JavaScript

This feature allows you to try and continue execution after a failed function call or intercept the error for debugging with the option of continuing later anyway. This is useful when code is published and there's a necessity to avoid going back to bug fixing immediately, before gathering more information about the state of the program.

Why exceptions don't fit the criteria: they force the code to break out of the original execution path, thus severely reducing the usefulness of error suppression with logging.

name = string_cut( other.name ); // warning: missing argument 2; after call, name = null
// name gets printed somewhere as 'null' or is invisible due to some other function not accepting null for a string
// everything else works

Built-in introspective pretty-printing (variable dumps)

[+] SGScript, Python, JavaScript
[-] Lua, Squirrel

This is a very useful feature to have when you need to debug data (i.e. always). Simply passing a variable to some function (for example, printvar) prints some useful information about it - the type, contents, linked resources.

Warning suppression on missing property access

[+] SGScript, Python (requires exception handling code)
[-] Lua, Squirrel, JavaScript (no warnings about it at all)

This feature allows to specify, per-read, whether the property is expected to be there or not.

a = obj.prop; // expected, emits a warning if not found
b = @obj.prop; // might not be there, no error

This also works for many other actions, like function calls and assignments.

Custom native iterators

[+] SGScript, Python
[-] JavaScript, Lua, Squirrel

An extension for custom native objects, it allows to create objects that can be foreach'ed through.

foreach( entry : io_dir( "." ) ) println( entry ); // prints the contents of current directory

Dual access dictionaries

[+] SGScript, Lua, JavaScript, Squirrel
[-] Python

The ability to access simple dictionaries just like any other object visually and syntactically reduces code complexity.

a.b = x; // simple
a["b"] = x; // not so simple

Explicit closures

[+] SGScript
[-] Lua, JavaScript, Squirrel, Python

Explicit closures (specifying which local variables to pass over to the newly defined function) make it easier to read code using closures and prevents closure-related accidents, like having a variable changed unexpectedly.

Multi-index/property-set operation without temporary tables

[+] SGScript
[-] Lua, JavaScript, Squirrel, Python

Simplifying code further without the introduction of sub-optimal memory access patterns. SGScript:

obj.{ // object name written only once, accessed only once
    a = 1, // property write
    b = 2, // property write
    c = 3, // property write
    d = 4, // property write
};

Lua, method 1:

obj.a = 1 // property write
obj.b = 2 // property write
obj.c = 3 // property write
obj.d = 4 // property write
// object name written four times, accessed possibly four times (depending on compiler)

Lua, method 2:

for k, v in pairs({ a = 1, b = 2, c = 3, d = 4 }) do // create table, property write x4, function call, create closure
    obj[ k ] = v // object access x4, property write x4
end

C-like syntax

[+] SGScript, JavaScript, Squirrel
[-] Lua, Python

With the overwhelming majority of code being written in C-like languages (http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html), having a compatible syntax helps when you need to copy code - there's simply less changes to perform.

Indices start at 0

[+] SGScript, JavaScript, Squirrel, Python
[-] Lua

Even though it is argued that 1-based indexing may help someone understand code better (which is actually hard to prove), I have a few arguments to make against it:


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; }

Control flow

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 control flow

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 10 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)-
threadtruecastcastsprintf thread(%p)cast


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
_Rspecial identifier, read-onlyglobal registry access
_Fspecial identifier, read-onlycurrent function retrieval
_Tspecial identifier, read-onlycurrent thread retrieval
nullconstantconstant
trueconstantconstant
falseconstantconstant
varrestricted keywordvariable declaration
globalrestricted keywordvariable declaration
classspecial identifierclass declaration
newrestricted keywordclass instantiation
threadrestricted keywordthread control
subthreadrestricted keywordthread control
syncrestricted keywordthread control
racerestricted keywordthread control
deferrestricted keyworddestruction statement helper
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
printfunction command"print" function
printlnfunction command"println" function
yieldfunction command"yield" function
includefunction command"include" function


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, bitwise, logical, 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
bitwise AND A & B bitwiseno2
bitwise OR A | B bitwiseno2
bitwise XOR A ^ B bitwiseno2
left shift A << B bitwiseno2
right shift A >> B bitwiseno2
bitwise AND-assign A &= B bitwiseyes2
bitwise OR-assign A |= B bitwiseyes2
bitwise XOR-assign A ^= B bitwiseyes2
left shift-assign A <<= B bitwiseyes2
right shift-assign A >>= B bitwiseyes2
bitwise invert ~ A bitwiseno1
logical AND A && B logicalno2
logical OR A || B logicalno2
first-not-null A ?? B logicalno2
logical AND-assign A &&= B logicalyes2
logical OR-assign A ||= B logicalyes2
first-not-null-assign A ??= B logicalyes2
logical invert ! A logicalno1
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
map literal map{[A]=B} specialnoany
assign A = B specialyes1
concatenate A $ B specialno2
concatenate-assign A $= B specialyes2
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
thread-call thread f() specialmaybe<=256
subthread-call subthread f()specialmaybe<=256
new-call new f() specialmaybe<=256

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. Object and its processing function can reside in different locations (like class instance / inherited class) and still be easily accessible.

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;

Control flow 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--;

defer is a special case since it moves the given statement to the end of the block (however that is reached). This can be useful for resource acquisitions:

rsrc = acquire_resource();
defer release_resource( rsrc );

if( work_with( rsrc ) )
    return; // release_resource is called here

more_work_with( rsrc );
// .. and here

Declaration statements

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

Examples:

var x = 5, y = 6, z;
global World = null;
function fn(){ INFO( "'fn' was called" ); }
class C
{
    var s = 1;
    function f(){ INFO( "'C.f' 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
applySGS/C functionpropertyfunction that allows to specify "this" & arg. array
was_abortedthreadpropertyreturns if thread was aborted
not_startedthreadpropertyreturns if coroutine was not started yet
runningthreadpropertyreturns if thread is currently running
can_resumethreadpropertyreturns if thread is not finished (can be resumed)
end_onthreadpropertyfunction that can specify an event to end the thread
resumethreadpropertyfunction that can resume the thread (see co_resume)
abortthreadpropertyfunction that can abort the thread (see abort)


Classes

Basic class

class SampleClass // create a class
{
    // static member variable (can be read from both class definition and instance)
    global StaticVariable = 5;
    
    // the default construction function
    function __construct( x )
    {
        // instance member variable (can be read only from class instance, not definition)
        this.c = x;
    }
    
    // static construction function
    function Create( x )
    {
        return new SampleClass( x );
    }
    
    function SampleMethod( a, b ) // "SampleClass.SampleMethod" 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 SampleFunction( a, b )
    {
        return a + b;
    }
}

// instances of class
inst1 = new SampleClass( 123 );
inst2 = SampleClass.Create( 456 );

// inspect instance 1, instance 2 and the underlying interface of instance 1
printvar( inst1, inst2, metaobj_get( inst1 ) );

Inheritance

// class A - base class
class A
{
    function func()
    {
        println( "base" );
    }
}

// class B - inherits from A
class B : A
{
    function func()
    {
        this!A.func();
        println( "override" );
    }
}

instA = new A();
instB = new B();

instA.func(); // prints "base"
instB.func(); // prints "base", then "override"

Overloadable operators/interfaces (Metamethods):


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 data types:

Interface function types:


Error codes

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


Variable type codes


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 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, sgs_GetIterator ), advancing ( sgs_IterAdvance ) and data retrieval ( sgs_IterPushData, sgs_IterGetData ).

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, sgs_StackItem( C, -1 ) );
while( sgs_IterAdvance( C, sgs_StackItem( C, -1 ) ) > 0 )
{
    sgs_StackIdx ssz = sgs_StackSize( C );
    
    sgs_IterPushData( C, sgs_StackItem( 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_GetIterator( C, iterable, &iterator );
while( sgs_IterAdvance( C, iterator ) > 0 )
{
    sgs_IterGetData( C, iterator, NULL, &value );
    // .. use value ..
    sgs_Release( C, &value );
    
    sgs_IterGetData( 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.


Metamethods

List of available metamethods:

__getindex

__setindex

__typeof

__clone

__tobool

__tostring

__negate

__add

__sub

__mul

__div

__mod

__compare

__call


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.


Functions


Context management


Memory management


Input / output


Code handling


Introspection / debugging helpers


Execution control


Binding helpers


Object type storage


Variable initialization


Stack primary interface


Sub-item usage


Argument handling


Virtual machine operations


String helpers


Container helpers


Data retrieval & conversion


Iterators


Variable ownership


String generation helper 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_RootContext [function]

sgs_RootContext( sgsContext* C )

Returns the root context of the engine.


sgs_ForkState [function]

sgs_Context* sgs_ForkState( sgs_Context* C, int copystate )

Creates a copy of the execution state.


sgs_ReleaseState [function]

sgs_ReleaseState( sgs_Context* C )

Releases the execution state, possibly destroying the VM.


sgs_PauseState [function]

SGSBOOL sgs_PauseState( sgs_Context* C )

Suspends the execution state, prompting the VM to return control to caller.


sgs_ResumeState*** [functions]

SGSBOOL sgs_ResumeStateRet( sgs_Context* C, int args, int* outrvc )

Resumes the execution state, passing arguments and retrieving the number of returned values.

SGSBOOL sgs_ResumeStateExp( sgs_Context* C, int args, int expect )

Resumes the execution state, passing arguments and retrieving the specified number of returned values.


sgs_ResumeState [function alias]

SGSBOOL sgs_ResumeState( sgs_Context* C )

Resumes the execution state.


sgs_CreateSubthread [function]

void sgs_CreateSubthread( sgs_Context* T, sgs_Context* C, sgs_Variable* out, sgs_StkIdx args, int gotthis )

Creates a thread (managed coroutine) with a starting function.


sgs_ProcessSubthreads [function]

int sgs_ProcessSubthreads( sgs_Context* C, sgs_Real dt )

Advances all subthreads belonging to this state, using the given delta time.


sgs_EventState [function]

SGSBOOL sgs_EventState( sgs_Context* C, sgs_Variable evt, int state )

Sets the event state.


sgs_EndOn [function]

void sgs_EndOn( sgs_Context* C, sgs_Variable ev, int enable )

Associates or detaches the event from thread end set.


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 )

Compiles and executes a string of text, leaving the return values on stack and returning their count.

Error codes:


sgs_EvalBuffer [function]

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

Compiles and executes a buffer of text or bytecode, leaving the return values on stack and returning their count.

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 )

Compiles and executes a file containing script text or bytecode, leaving the return values on stack and returning their count.

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]

void sgs_LoadLib_Fmt( sgs_Context* C )

void sgs_LoadLib_IO( sgs_Context* C )

void sgs_LoadLib_Math( sgs_Context* C )

void sgs_LoadLib_OS( sgs_Context* C )

void sgs_LoadLib_RE( sgs_Context* C )

void sgs_LoadLib_String( sgs_Context* C )

Loads the library into the specified context


sgs_Reg***Consts [function]

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

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

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

Loads the specified list of constants in the context.


sgs_Make*** [functions]

sgs_Variable sgs_MakeNull()

sgs_Variable sgs_MakeBool( sgs_Bool value )

sgs_Variable sgs_MakeInt( sgs_Int value )

sgs_Variable sgs_MakeReal( sgs_Real value )

sgs_Variable sgs_MakeCFunc( sgs_CFunc func )

sgs_Variable sgs_MakePtr( void* ptr )

Returns a variable instance of the specified type.


sgs_Init*** [functions]

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_InitObjectPtr( sgs_Variable* out, sgs_VarObj* obj )

void sgs_InitThreadPtr( sgs_Variable* out, sgs_Context* T )

Initialize a variable to the specified type.


sgs_Create*** [functions]

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

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

Creates a new object.

SGSONE sgs_CreateArray( sgs_Context* C, sgs_Variable* out, sgs_SizeVal numitems )

Creates an array from numitems last items on the stack, pops those items.

SGSONE sgs_CreateDict( sgs_Context* C, sgs_Variable* out, sgs_SizeVal numitems )

Creates a dict from numitems last items on the stack, pops those items.

SGSONE sgs_CreateMap( sgs_Context* C, sgs_Variable* out, sgs_SizeVal numitems )

Creates a map from numitems last items on the stack, pops those items.

SGSONE sgs_CreateEvent( sgs_Context* C, sgs_Variable* out )

Initialize variable to a new event.

SGSONE sgs_CreatePooledEventBuf( sgs_Context* C, sgs_Variable* out, sgs_Variable dict, const char* str, sgs_SizeVal size )

Initialize variable to a new or existing pooled event (by name in buffer).

SGSONE sgs_CreatePooledEvent( sgs_Context* C, sgs_Variable* out, sgs_Variable dict, const char* str )

Initialize variable to a new or existing pooled event (by C-string name).


sgs_Push*** [functions]

SGSONE sgs_PushNull( sgs_Context* C )

SGSONE sgs_PushNulls( sgs_Context* C, int count )

SGSONE sgs_PushBool( sgs_Context* C, sgs_Bool value )

SGSONE sgs_PushInt( sgs_Context* C, sgs_Int value )

SGSONE sgs_PushReal( sgs_Context* C, sgs_Real value )

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

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

SGSONE sgs_PushCFunc( sgs_Context* C, sgs_CFunc func )

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

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

SGSONE sgs_PushPtr( sgs_Context* C, void* ptr )

SGSONE sgs_PushObjectPtr( sgs_Context* C, sgs_VarObj* obj )

SGSONE sgs_PushVariable( sgs_Context* C, sgs_Variable* var )

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

To push objects, use sgs_Create*** functions.

To allocate an uninitialized string buffer, use sgs_PushStringAlloc.


sgs_StoreVariable [function]

void 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.


sgs_Pop [function]

void sgs_Pop( sgs_Context* C, int count )

Pops count variables off the current frame of the stack.


sgs_PopSkip [function]

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

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


sgs_InsertVariable [function]

void 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.


sgs_PushItem [function alias]

void 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.


sgs_GetIndex [function]

SGSBOOL sgs_GetIndex( sgs_Context* C, sgs_Variable obj, sgs_Variable idx, sgs_Variable* out, int isprop )

Retrieve index/property idx from the specified variable obj to the position out, specifying retrieval type via isprop, return if successful.


sgs_SetIndex [function]

SGSBOOL sgs_SetIndex( sgs_Context* C, sgs_Variable obj, sgs_Variable idx, sgs_Variable val, int isprop )

Set index/property idx in the specified variable obj to the value val, specifying type via isprop, return if successful.


sgs_PushIndex [function]

SGSBOOL sgs_PushIndex( sgs_Context* C, sgs_Variable obj, sgs_Variable idx, int isprop )

Retrieve and push index/property idx from the specified variable obj, specifying retrieval type via isprop, return if successful.


sgs_PushProperty [functions]

SGSBOOL sgs_PushProperty( sgs_Context* C, sgs_Variable var, const char* name )

Load and push the property of the variable var in the current stack frame, return if successful.


sgs_SetProperty [functions]

SGSBOOL sgs_SetProperty( sgs_Context* C, sgs_Variable var, const char* name, sgs_Variable val )

Set the property name of variable var to val, return if successful.


sgs_PushNumIndex [function]

SGSBOOL sgs_PushNumIndex( sgs_Context* C, sgs_Variable var, sgs_Int idx )

Load and push the integer index idx of the variable obj, return if successful.


sgs_SetNumIndex [function]

SGSBOOL sgs_SetNumIndex( sgs_Context* C, sgs_Variable var, sgs_Int idx, sgs_Variable val )

Set the index idx of variable var to val, return if successful.


sgs_GetGlobal [function]

SGSBOOL sgs_GetGlobal( sgs_Context* C, sgs_Variable idx, sgs_Variable* out )

Retrieve a global variable by index idx to position out.


sgs_SetGlobal [function]

SGSBOOL sgs_SetGlobal( sgs_Context* C, sgs_Variable idx, sgs_Variable val )

Set global variable idx to val.


sgs_PushGlobalByName [function]

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

Push the global variable name on the stack, return if successful.


sgs_GetGlobalByName [function]

SGSBOOL sgs_GetGlobalByName( sgs_Context* C, const char* name, sgs_Variable* out )

Retrieve the global variable name, return if successful.


sgs_SetGlobalByName [function]

SGSBOOL sgs_SetGlobalByName( sgs_Context* C, const char* name, sgs_Variable val )

Set global variable name to val.


sgs_Registry [function]

sgs_Variable sgs_Registry( sgs_Context* C, int subtype )

Retrieve a table from registry.


sgs_GetEnv [function]

void sgs_GetEnv( sgs_Context* C, sgs_Variable* out )

Retrieve the global environment variable (_G).


sgs_SetEnv [function]

void sgs_SetEnv( sgs_Context* C, sgs_Variable* var )

Set a global environment variable from the variable var.


sgs_PushEnv [function]

void sgs_PushEnv( sgs_Context* C )

Retrieve and push the global environment variable (_G).


sgs_PushPath [function]

SGSBOOL sgs_PushPath( sgs_Context* C, sgs_Variable var, const char* path, ... )

Push the variable specified by starting point var and traversal path path, return if successful.

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


sgs_StorePath [function]

SGSBOOL sgs_StorePath( sgs_Context* C, sgs_Variable var, sgs_Variable val, const char* path, ... )

Set value val to variable specified by starting point var 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.


sgs_Store***Consts [functions]

void sgs_StoreFuncConsts( sgs_Context* C, sgs_Variable var, const sgs_RegFuncConst* list, int size )

void sgs_StoreIntConsts( sgs_Context* C, sgs_Variable var, const sgs_RegIntConst* list, int size )

void sgs_StoreRealConsts( sgs_Context* C, sgs_Variable var, const sgs_RegRealConst* list, int size )

Loads the specified list of constants in the specified variable.


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]

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

SGSBOOL 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.

control commands
parsing commands

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.


sgs_ParseMethod [function]

SGSBOOL sgs_ParseMethod( sgs_Context* C, sgs_ObjInterface* iface, void** ptrout, const char* name );

Implements method parsing.


SGS_PARSE_METHOD [function alias]

SGSBOOL SGS_PARSE_METHOD( sgs_Context* C, sgs_ObjInterface* iface, T*& ptrout, ident objname, ident methodname )

Method parsing macro.


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_ArgCheck_Object [function]

int sgs_ArgCheck_Object( sgs_Context* C, int argid, va_list* args, int flags )

Argument parsing function for parsing any objects.


sgs_ObjectArg [function]

int sgs_ObjectArg( sgs_Context* C )

Returns the additional integer argument to an object interface function call.


sgs_XFCall [functions]

int sgs_XFCall( sgs_Context* C, int args, int gotthis )

Call the function with the arguments on stack, returning variables on stack and their count.


sgs_X(This)Call [function aliases]

int sgs_XCall( sgs_Context* C, int args )

int sgs_XThisCall( sgs_Context* C, int args )

Call the function with the arguments on stack, returning variables on stack and their count.


sgs_FCall [functions]

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

Call the function with the arguments on stack, returning the expected number of variables on stack.

After a successful call, all arguments 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 values, '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.

To check if function call was aborted, see sgs_Cntl / SGS_CNTL_GET_ABORT.

To find out if execution state was suspended in this call, see sgs_Cntl / SGS_CNTL_GET_PAUSED.


sgs_(This)Call [function aliases]

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

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

Call the function with the arguments on stack, returning the expected number of variables on stack.


sgs_GlobalCall [function]

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

Call the global variable name as a function.


sgs_TypeOf [function]

void sgs_TypeOf( sgs_Context* C, sgs_Variable var )

Return the type name string of the specified variable.


sgs_DumpVar [function]

void sgs_DumpVar( sgs_Context* C, sgs_Variable var, int maxdepth )

Convert the variable to a highly informative string that should display its contents, up to maxdepth depth.


sgs_GCExecute [function]

void sgs_GCExecute( sgs_Context* C )

Call the garbage collector on the VM.


sgs_DebugDumpVarExt [functions]

const char* sgs_DebugDumpVarExt( sgs_Context* C, sgs_Variable var, int maxdepth )

Push a string containing variable data and return const char* to it.


sgs_DebugDumpVar [function alias]

const char* sgs_DebugDumpVar( sgs_Context* C, sgs_Variable* var )

Push a variable dump string and return const char* to it.


sgs_DebugPrintVar [function alias]

const char* sgs_DebugPrintVar( sgs_Context* C, sgs_Variable var )

Push a string, converted from variable and return const char* to it.


sgs_PadString [function]

void 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.


sgs_ToPrintSafeString [function]

void 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.


sgs_StringConcat [function]

void sgs_StringConcat( sgs_Context* C, int args )

Concatenate the args number of topmost string variables in the current stack frame.


sgs_CloneItem [function]

void sgs_CloneItem( sgs_Context* C, sgs_Variable var )

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.


sgs_RegSymbol [function]

void sgs_RegSymbol( sgs_Context* C, const char* prefix, const char* name, sgs_Variable var )

Register a persistent item (symbol) by the specified prefix/name.


sgs_GetSymbol [function]

SGSBOOL sgs_GetSymbol( sgs_Context* C, sgs_Variable var, sgs_Variable* out )

Map name to a registered variable or variable to name using the symbol table.


sgs_Serialize(Ext) [functions]

void sgs_Serialize( sgs_Context* C, sgs_Variable var )

Serialize the given variable (convert to a byte stream).

void sgs_SerializeExt( sgs_Context* C, sgs_Variable var, int mode )

Same as above, also allows to specify serialization mode.


sgs_Unserialize(Ext) [functions]

SGSBOOL sgs_Unserialize( sgs_Context* C, sgs_Variable var )

Unserialize the given variable (decode the byte stream).

SGSBOOL sgs_UnserializeExt( sgs_Context* C, sgs_Variable var, int mode )

Same as above, also allows to specify serialization mode.

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


sgs_SerializeObject [function]

void sgs_SerializeObject( sgs_Context* C, sgs_StkIdx args, const char* func )

Specify the unserialization function and argument count to use for the object.


sgs_SerializeObjIndex [function]

void sgs_SerializeObjIndex( sgs_Context* C, sgs_Variable key, sgs_Variable val, int isprop )

Serialize an object's property/index.


sgs_SerializeSGSON [function]

void sgs_SerializeSGSON( sgs_Context* C, sgs_Variable var, const char* tab )

Serialize the given variable into a text format.


sgs_UnserializeSGSON(Ext) [functions]

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

Unserialize the given variable from a byte stream.

void sgs_UnserializeSGSONExt( sgs_Context* C, const char* str, size_t size )

Allows to pass a string buffer to the parsing function.


sgs_Assign [function]

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

Acquire var_from, release var_to, copy var_from to var_to.


sgs_ArithOp [function]

void 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).


sgs_IncDec [function]

void sgs_IncDec( sgs_Context* C, 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).


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]

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

Register a type interface by mapping it to a name.


sgs_UnregisterType [function]

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

Unregister a type interface by its name.


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_PushInterface [function]

SGSONE sgs_PushInterface( sgs_Context* C, sgs_CFunc igfn )

Push a cached/generated object.


sgs_InitInterface [function]

void sgs_InitInterface( sgs_Context* C, sgs_Variable* var, sgs_CFunc igfn )

Initialize a variable to a cached/generated object.


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_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_ParseStringP( sgs_Context* C, sgs_Variable* var, char** out, sgs_SizeVal* size )

Attempts to parse the specified variable, returning whether parsing was successful.


sgs_Global*** [functions]

sgs_Bool sgs_GlobalBool( sgs_Context* C, const char* name )

sgs_Int sgs_GlobalInt( sgs_Context* C, const char* name )

sgs_Real sgs_GlobalReal( sgs_Context* C, const char* name )

char* sgs_GlobalStringBuf( sgs_Context* C, const char* name, sgs_SizeVal* outsize )

char* sgs_GlobalString( sgs_Context* C, 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 [functions]

SGSBOOL sgs_PushIterator( sgs_Context* C, sgs_Variable var )

Create and push an iterator from the specified variable, return if successful.


sgs_GetIterator [functions]

SGSBOOL sgs_GetIterator( sgs_Context* C, sgs_Variable var, sgs_Variable* out )

Create an iterator from the specified variable, return if successful.


sgs_IterAdvance [functions]

SGSBOOL sgs_IterAdvance( sgs_Context* C, sgs_Variable var )

Advance the iterator to the next position, returning if the current position is still in range.


sgs_IterPushData [functions]

void sgs_IterPushData( sgs_Context* C, sgs_Variable var, int key, int value )

Load and push data associated with the current position.


sgs_IterGetData [functions]

void sgs_IterGetData( sgs_Context* C, sgs_Variable var, sgs_Variable* key, sgs_Variable* value )

Load data associated with the current position.


sgs_IsArray [function]

SGSBOOL sgs_IsArray( sgs_Variable var )

Return if variable is of array type.


sgs_IsDict [function]

SGSBOOL sgs_IsDict( sgs_Variable var )

Return if variable is of dict type.


sgs_IsMap [function]

SGSBOOL sgs_IsMap( sgs_Variable var )

Return if variable is of map type.


sgs_ArraySize [functions]

sgs_SizeVal sgs_ArraySize( sgs_Variable var )

Check if the specified stack item or variable is an array and return its size or -1 if variable is not an array.


sgs_ArrayPush [function]

void sgs_ArrayPush( sgs_Context* C, sgs_Variable var, sgs_StkIdx count )

Push the last count variables on stack to the end of the array var, then pop them from the stack.


sgs_ArrayPop [function]

void sgs_ArrayPop( sgs_Context* C, sgs_Variable var, sgs_StkIdx count, SGSBOOL ret )

Pop the last count variables off the end of the array var, optionally return them.


sgs_ArrayErase [function]

void sgs_ArrayErase( sgs_Context* C, sgs_Variable var, sgs_StkIdx at, sgs_StkIdx count )

Remove the specified variable range [`at`,`at`+`count`) from array var.


sgs_ArrayFind [function]

sgs_SizeVal sgs_ArrayFind( sgs_Context* C, sgs_Variable var, sgs_Variable what )

Return the first position of item what in array var or -1 if item was not found.


sgs_ArrayRemove [function]

sgs_SizeVal sgs_ArrayRemove( sgs_Context* C, sgs_Variable var, sgs_Variable what, SGSBOOL all )

Remove first/all occurrence(s) of what in array var.


sgs_Unset [function]

SGSBOOL sgs_Unset( sgs_Context* C, sgs_Variable var, sgs_Variable key )

Unset the specified index of the given dict/map variable, return if successful.


sgs_StackSize [function]

sgs_StkIdx sgs_StackSize( sgs_Context* C )

Return the size of the current stack frame.


sgs_SetStackSize [function]

void sgs_SetStackSize( sgs_Context* C, sgs_StkIdx size )

Resizes the current stack frame to fit the specified amount of items.


sgs_SetDeltaSize [function]

void sgs_SetDeltaSize( sgs_Context* C, sgs_StkIdx diff )

Resizes the current stack frame to the [size+diff] size.


sgs_AdjustStack [function]

SGSRESULT sgs_AdjustStack( sgs_Context* C, int expected, int ret )

Resizes the current stack frame by expected - ret, returns ret

Used with sgs_Eval** functions to create their sgs_Exec** counterparts.


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_OptStackItem [function]

sgs_Variable sgs_OptStackItem( sgs_Context* C, sgs_StkIdx item )

Returns a non-owned copy of a variable on stack or null if the index is invalid.


sgs_StackItem [function]

sgs_Variable sgs_StackItem( sgs_Context* C, sgs_StkIdx item )

Returns a non-owned copy of a variable on stack.

Avoid using this function with functions that can alter the stack and remove the source item.

This function does not acquire the variable and thus can't be used in functions that modify it without previously taking ownership of 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]

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

Copy the specified variable to the specified position in stack.


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]

void sgs_GCMark( sgs_Context* C, sgs_Variable* var )

void 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]

void 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_ObjSetMetaObj [function]

void sgs_ObjSetMetaObj( sgs_Context* C, sgs_VarObj* obj, sgs_VarObj* metaobj )

Set metaobj as the meta-object of object obj.


sgs_ObjGetMetaObj [function]

sgs_VarObj* sgs_ObjGetMetaObj( sgs_VarObj* obj )

Retrieve meta-object of an object.


sgs_ObjSetMetaMethodEnable [function]

void sgs_ObjSetMetaMethodEnable( sgs_VarObj* obj, SGSBOOL enable )

Enable or disable metamethod support for an object.


sgs_ObjGetMetaMethodEnable [function]

SGSBOOL sgs_ObjGetMetaMethodEnable( sgs_VarObj* obj )

Check if metamethod support is enabled for an object.


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]

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

Set the object data pointer of the specified stack item.

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

Set the object data pointer of the specified variable.


sgs_SetObjectIface(P) [functions]

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

Set the object interface pointer of the specified stack item.

void 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, ... )

void sgs_ErrWritef( 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_GetScriptFSFunc [function]

SGSBOOL sgs_GetScriptFSFunc( sgs_Context* C, sgs_ScriptFSFunc* outf, void** outc )

Retrieves the currently set virtual file system function.


sgs_SetScriptFSFunc [function]

void sgs_SetScriptFSFunc( sgs_Context* C, sgs_ScriptFSFunc func, void* ctx ).

Sets the virtual file system function.


sgs_StdScriptFSFunc [function]

SGSRESULT sgs_StdScriptFSFunc( void* ctx, sgs_Context* C, int op, sgs_ScriptFSData* data )

Implements virtual file system using real file system.


sgs_Msg [function]

SGSZERO 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]

SGSBOOL sgs_Abort( sgs_Context* C )

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


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, sgs_StackFrame* from, int bwd )

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_PushBool( C, sgs_Errno( C, rename( a, b ) == 0 ) )

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_PushStringAlloc [function]

char* sgs_PushStringAlloc( sgs_Context* C, sgs_SizeVal size )

Push an uninitialized string buffer, returns pointer to buffer.

Created string is a valid resource in terms of acquisition/release but not hashed and internalized yet, thus it cannot be used in indexing/comparison functions until it's finalized, see sgs_FinalizeStringAlloc(P).


sgs_InitStringAlloc [function]

char* sgs_InitStringAlloc( sgs_Context* C, sgs_Variable* var, sgs_SizeVal size )

Set an uninitialized string buffer to a variable, returns pointer to buffer.

Created string is a valid resource in terms of acquisition/release but not hashed and internalized yet, thus it cannot be used in indexing/comparison functions until it's finalized, see sgs_FinalizeStringAlloc(P).


sgs_FinalizeStringAlloc(P) [functions]

void sgs_FinalizeStringAlloc( sgs_Context* C, sgs_StkIdx item )

void sgs_FinalizeStringAllocP( sgs_Context* C, sgs_Variable* var )

Finalize (prepare for usage) an uninitialized string buffer.


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:
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:
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 built-in methods:

Constants:

Other:


array [function]

array( ... )

returns an array, containing the arguments

array( "5", 6, 7.0 ) // same as ["5",6,7.0]
function array.join( separator )
{
    return string_implode( this, separator );
}

array_sized [function]

array_sized( size )

returns an array, containing size null values


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( object obj, object metaobj )

sets metaobj as meta-object for obj and enables metamethods for obj, returns obj

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}

map_filter [function]

map_filter( map[, callable] )

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

map_filter(map{ a = 0, b = 1 }); // returns [map]{b=1}

map_process [function]

map_process( obj, callable )

pass all items through a callable, return same object


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'

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_ext(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


metaobj_set [function]

metaobj_set( object obj, object metaobj )

sets the meta-object of an object


metaobj_get [function]

metaobj_get( object obj )

retrieves the meta-object of an object


metamethods_enable [function]

metamethods_enable( object obj, bool enable )

enables or disables metamethod support for an object


metamethods_test [function]

metamethods_test( object obj )

retrieves metamethod support state


mm_getindex_router [function]

mm_getindex_router( key )

__getindex to __get_*** router


mm_setindex_router [function]

mm_setindex_router( key, value )

__setindex to __set_*** router


event [function]

event( bool signaled = false )

Creates an event.


pooled_event [function]

pooled_event( object, string name, bool signaled = false )

Create a pooled event (named event, in table)


end_on [function]

end_on( this thread, object event, bool enable = true )

Set or unset an event object that can stop a thread.

An "event" is any object that implements the "convert to bool" behavior. True means 'signaled', false - inactive. When the event is signaled, the thread will be aborted as soon as possible.


co_create [function]

co_create( callable )

Creates a coroutine with the specified callable.


co_resume [function]

co_resume( coroutine[, args..] )

Starts or resumes the coroutine.


thread_create [function]

thread_create( fn, this[, args..] )

Starts a managed topmost coroutine (thread).


subthread_create [function]

subthread_create( fn, this[, args..] )

Starts a managed sub-coroutine (subthread).


process_threads [function]

process_threads( dt[, ctx ] )

Advance the managed subthreads once, using the specified delta time.


yield [function]

yield([ args.. ])

Suspends the current state, returning to caller.


abort [function]

abort([ contexts... ])

Stops execution and returns to C code as soon as possible.

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

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 using the compatible function call syntax (thisvar!func( arg1, ... )) 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" );

sym_register [function]

sym_register( string name, var )

Register a persistent item (symbol) by the specified name.

myfunc = function(){};
sym_register( "myfunc", myfunc );

sym_get [function]

sym_get( var )

Map name to a registered variable or variable to name using the symbol table.

print sym_get( assert ); // prints "assert"
print sym_get( "assert" ); // prints "C function"

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

find_include_file [function]

find_include_file( string file )

Find the include file according to SGS_PATH.


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_curprocfile [function]

sys_curprocfile()

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


sys_curprocdir [function]

sys_curprocdir()

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


multiply_path_ext_lists [function]

multiply_path_ext_lists( string prefixes, string joiner = "/"[, string suffixes ])

combines prefixes (paths) and suffixes (extensions) through the joiner string to create an array of paths


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.


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_msg( 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, int mode = 2 )

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, int mode = 2 )

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}

sgson_encode [function]

sgson_encode( var[, string tab ])

Encodes the given variable in the SGSON format.


sgson_decode [function]

sgson_decode( string data )

Decodes the SGSON text into a variable


SGS_*** [constants]

SGS_INFO, SGS_WARNING, SGS_ERROR, SGS_APIERR

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


VT_*** [constants]

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

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

_R [superglobal]

A hard-coded global value that points to the registry. Can be used to access the symbol table (_R["$sym"]) or include list (_R["$inc"]).


_F [superglobal]

The currently executed function.

function f(){ printvar( _F ); }
f(); // prints info about function 'f'

_T [superglobal]

The currently executed thread (context/coroutine).

function f(){ printvar( _T ); }
f(); // prints info about current context
thread f(); // prints info about this newly created thread

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]


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_custom_encode [function]

fmt_custom_encode( string text, string class, string prefix, int format, int mindigits = 0, string postfix = "" )

encodes a custom format (selected character codes to numeric version)

Every character (byte) from text that matches class is converted to the following format:

format must be one of:

Use case example - encode a string for C/C++ source code output:

// character class:
// - '^' - invert class (exclude the following characters/ranges)
// - <space>, '!' - characters to exclude (first printable characters, before quote)
// - '#-~' - character range to exclude (other printable characters, after quote)
// the extra set of quotes around hex code prevent hyperactive parsers from thinking ..
// .. that the following characters might be a part of the hex code
fmt_custom_encode( 'some text', "^ !#-~", '""\\x', FMT_NUMBER_HEX, 2, '""' )

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.


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(Ext) / 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 (modes 1 and 2)

The format (mode 3)

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)