3.7. Compiling a scriptΒΆ

You can compile a Squirrel script with the function sq_compile.:

typedef SQInteger (*SQLEXREADFUNC)(SQUserPointer userdata);

SQRESULT sq_compile(HSQUIRRELVM v,SQREADFUNC read,SQUserPointer p,
            const SQChar *sourcename,SQBool raiseerror);

In order to compile a script is necessary for the host application to implement a reader function (SQLEXREADFUNC); this function is used to feed the compiler with the script data. The function is called every time the compiler needs a character; It has to return a character code if succeed or 0 if the source is finished.

If sq_compile succeeds, the compiled script will be pushed as Squirrel function in the stack.

Here an example of a ‘read’ function that read from a file:

SQInteger file_lexfeedASCII(SQUserPointer file)
{
    int ret;
    char c;
    if( ( ret=fread(&c,sizeof(c),1,(FILE *)file )>0) )
        return c;
    return 0;
}

int compile_file(HSQUIRRELVM v,const char *filename)
{
    FILE *f=fopen(filename,"rb");
    if(f)
    {
         sq_compile(v,file_lexfeedASCII,f,filename,1);
         fclose(f);
         return 1;
    }
    return 0;
}

When the compiler fails for a syntax error it will try to call the ‘compiler error handler’; this function must be declared as follow:

typedef void (*SQCOMPILERERROR)(HSQUIRRELVM /*v*/,const SQChar * /*desc*/,const SQChar * /*source*/,
                        SQInteger /*line*/,SQInteger /*column*/);

and can be set with the following API call:

void sq_setcompilererrorhandler(HSQUIRRELVM v,SQCOMPILERERROR f);