File: compiling_a_script.rst

package info (click to toggle)
squirrel3 3.1-8.3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,380 kB
  • sloc: cpp: 12,722; ansic: 917; makefile: 316; python: 40
file content (58 lines) | stat: -rw-r--r-- 1,866 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
.. embedding_compiling_a_script:

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

.. :note::
    In order to execute the script, the function generated by *sq_compile()* has
    to be called through *sq_call()*

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