Integration

Integration of TIScript is pretty straightforward. Let's take a look on it step by step. I will use C++ here for the sake of conciseness. C API is also available - just take a look on tiscript.h and comments inside.

Step 1. Creating the engine

side note:
std_stream implementation
/* console io */
class std_stream: public tiscript::stream
{
virtual int  get()
  { return fgetc( stdin ); }
virtual bool put(int v)
  { return fputc( v, stdout ) != EOF; }
};

/* include TIScript C++ API header. */
#include "tiscript.hpp"

/* Create instance of simple stream which will be used by script for its stdio, stdin, stderr */
std_stream cio;

/* Create instance of engine */
tiscript::engine tis(&cio);

At this point we have working instance of the engine in variable tis.

Step 2. Defining native function

Let's define C++ function to be called from script, a.k.a. "native function".

/* alert function - shows standard message box */

struct alert_fcn: tiscript::function
{
virtual tiscript::value operator()( tiscript::value* argv, int argc )
{
if( argc == 1 && argv[0].is_string())
{
 const wchar_t* str = argv[0].get(L"");
 ::MessageBoxW(NULL,str,L"script alert", MB_OK | MB_ICONEXCLAMATION);
}
return tiscript::value(); /* return undefined value here */
}
};

/* add this function into script name space */

tis.add(L"alert", new alert_fcn);

At this point we have initialized scripting engine with our function registered. Next is ...

Step 3. Running scripts

/* creating input stream for reading our script code */
tiscript::file_in_stream in( "c:/test.js" );
if(!in.is_valid())
{
printf( "cannot open %s\n", "c:/test.js" );
return -1;
}
 
/* load and execute script from the in stream. */
if(!tis.load( &in ))
  return -2;
 
/* done */

Step 4. (optional) Calling script functions

Script execution starts immediately on load but you may want to call scripting functions from your C++ code. Never been easier, see:

/* defining array of parameters for script function */

tiscript::value argv[2] =
{
tiscript::value(1),
// int parameter
tiscript::value(L
"hello") // string parameter
};

/* assume that there is MyScriptFunction defined in script, let's call it then: */

tiscript::value r = tis.call(L"MyScriptFunction", argv, 2 /* argc */ );

/* in r we have result returned by MyScriptFunction, report it */
printf( "got from script:%S\n", r.get(L"?") );

Done. We have implemented all typical steps of script engine integration into C++ application.

Full source code of tis.exe - console application using TIScript is in /samples/console/tis.cpp of TIScript SDK.