compiling_a_script.rst 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. .. embedding_compiling_a_script:
  2. ==================
  3. Compiling a script
  4. ==================
  5. You can compile a Squirrel script with the function *sq_compile*.::
  6. typedef SQInteger (*SQLEXREADFUNC)(SQUserPointer userdata);
  7. SQRESULT sq_compile(HSQUIRRELVM v,SQREADFUNC read,SQUserPointer p,
  8. const SQChar *sourcename,SQBool raiseerror);
  9. In order to compile a script is necessary for the host application to implement a reader
  10. function (SQLEXREADFUNC); this function is used to feed the compiler with the script
  11. data.
  12. The function is called every time the compiler needs a character; It has to return a
  13. character code if succeed or 0 if the source is finished.
  14. If sq_compile succeeds, the compiled script will be pushed as Squirrel function in the
  15. stack.
  16. .. :note::
  17. In order to execute the script, the function generated by *sq_compile()* has
  18. to be called through *sq_call()*
  19. Here an example of a 'read' function that read from a file: ::
  20. SQInteger file_lexfeedASCII(SQUserPointer file)
  21. {
  22. int ret;
  23. char c;
  24. if( ( ret=fread(&c,sizeof(c),1,(FILE *)file )>0) )
  25. return c;
  26. return 0;
  27. }
  28. int compile_file(HSQUIRRELVM v,const char *filename)
  29. {
  30. FILE *f=fopen(filename,"rb");
  31. if(f)
  32. {
  33. sq_compile(v,file_lexfeedASCII,f,filename,1);
  34. fclose(f);
  35. return 1;
  36. }
  37. return 0;
  38. }
  39. When the compiler fails for a syntax error it will try to call the 'compiler error handler';
  40. this function must be declared as follow: ::
  41. typedef void (*SQCOMPILERERROR)(HSQUIRRELVM /*v*/,const SQChar * /*desc*/,const SQChar * /*source*/,
  42. SQInteger /*line*/,SQInteger /*column*/);
  43. and can be set with the following API call::
  44. void sq_setcompilererrorhandler(HSQUIRRELVM v,SQCOMPILERERROR f);