Squirrel Scripting Language         How to set up a very simple application and use Squirrel for scripting

In this forum post morez posted the following helpful bit on the Squirrel Scripting Language...


Hi guys,
In this topic I would like to explain how to set up a very simple application and use Squirrel for scripting (instead of Lua for example :-D )
Squirrel is very nice high level imperative/OO programming language with syntax similar to C/C++ developed by Alberto Demichelis. I'm going to use SQPlus, developed by John Schultz, to bind Squirrel to C++.
This code example has been inspired by the LuaBind example in wiki page.

What do you need?

Note that I'm using Microsoft Visual Studio .NET 2003 (7.1).
You need Ogre (SDK or source) Squirrel and SQPlus of course :-). SQPlus contains the last stable version of Squirrel. So, download it and compile.

Create the Project

I used the wizard to create a simple Standard Ogre Application. I called it SquirrelOgre.

Let's Include some stuff

Note that this simple example is made in debug mode. So in C++ general (Project properties) add:

  • path/to/Squirrel/sqplus
  • path/to/Squirrel/include

In Linker general add:

  • path/to/Squirrel/lib

In Linker dependencies add:

  • squirrelD.lib
  • sqstdlibD.lib
  • sqplusD.lib

If you are running *nix

gcc will need the following options:

  • -Ipath/to/Squirrel/sqplus
  • -Ipath/to/Squirrel/include
  • -Lpath/to/Squirrel/lib
  • -lsquirrel
  • -lsqstdlib
  • -lsqplus

Let's code

This is main.cpp. We do not change this file, I'll do everything in the header file. This is not a clear style code programming lesson :-)

#include "SquirrelOgre.h"
 #define WIN32_LEAN_AND_MEAN
 #include "windows.h"
 #ifdef __cplusplus
    extern "C" {
       int main(int argc, char *argv[])
          // Create application object
          SquirrelOgre app;
          try {
          } catch( Ogre::Exception& e ) {
             MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
             std::cerr << "An exception has occured: " <<
                e.getFullDescription().c_str() << std::endl;
          return 0;
 #ifdef __cplusplus

Ok so let's see how to make our header file SquirrelOgre.h

#ifndef __SquirrelOgre_h_
 #define __SquirrelOgre_h_
 #include "sqplus.h" // Include the SQPlus header
 #include "ExampleApplication.h"
 #include <stdarg.h> // needed for redirecting squirrel output
 using namespace SqPlus; // SqPlus namespace

Simple and clear.

// ====================================================================
 // Define a custom constructor for Vector 3
 // ====================================================================
 int constructVector3(int x, int y, int z, HSQUIRRELVM v) {
   return PostConstruct<Vector3>(v, new Vector3(x, y, z), ReleaseClassPtr<Vector3>::release);
 SQ_DECLARE_RELEASE(Vector3) // This is required when using a custom constructor

Here we have declared a custom constructor for the Ogre::Vector3 class.

// ====================================================================
 // Actor class this is a cut & paste from LuaBind wiki tutorial ;)
 // ====================================================================
 class Actor
    Actor() {}
    Actor( std::string sName, SceneManager *pSceneMgr, Vector3 v3Position, Vector3 v3Scale )
       mName = sName;
       mSceneMgr = pSceneMgr;
       std::stringstream ss;
       ss << mName << "_ControlNode";
       mControlNode = pSceneMgr->getRootSceneNode()->createChildSceneNode( ss.str(), v3Position );
       ss << mName << "_Entity";
       mEntity = pSceneMgr->createEntity( ss.str(), "ogrehead.mesh" );
       mControlNode->attachObject( mEntity );
       mControlNode->setScale( v3Scale );
     void setMaterialName( const SQChar* sMaterialName )
       mEntity->setMaterialName( sMaterialName );
    void setScale( Vector3* v3Scale )
       mControlNode->setScale( *v3Scale );
    void setPosition( Vector3* v3Position )
        mControlNode->setPosition( *v3Position );
    void setMesh( const SQChar* sMeshResourceName )
       if( mEntity )
          mControlNode->detachObject( mEntity->getName() );
          mSceneMgr->removeEntity( mEntity );
          mEntity = 0;
       mEntity = mSceneMgr->createEntity(  mName, sMeshResourceName );
       mControlNode->attachObject( mEntity );
    std::string mName;
    SceneNode *mControlNode;
    Entity *mEntity;
    SceneManager *mSceneMgr;
 // Declare both Actor and Vector3 class

Here we have declared the Actor class and called the macro DECLARE_INSTANCE_TYPE for both Actor and Ogre::Vector3 classes. Note that the Actor class methods parameters are passed by reference in setScale and setPosition methods and I've used const SQChar* instead of std::string in setMaterialName and setMesh.

class SquirrelOgre : public ExampleApplication
 virtual void createScene(void)
     SquirrelVM::Init(); // Start the virtual machine
     sq_setprintfunc(SquirrelVM::GetVMPtr(), SquirrelOgre::printFunc); // Redirect the VM output, print func is declared below
     // The following reads the test.nut script using Ogres Resource manager:
     DataStreamPtr pStream = ResourceGroupManager::getSingleton().openResource( "Test.nut", "General"); // open the script file   
     String filestream = pStream->getAsString();
     SquirrelObject testSquirrel = SquirrelVM::CompileBuffer(filestream.c_str()); // Compile the script
     // This is if you instead want to open the test.nut file in the current directory and avoid the Ogre resource manager:
     // SquirrelObject testSquirrel = SquirrelVM::CompileScript("Test.nut"); 
         SquirrelVM::RunScript(testSquirrel); // run the script
     catch(SquirrelError & e)
         // catch exceptions and print them out through the custom print function
            (SquirrelVM::GetVMPtr(),_T("Error: %s, %s\n"),e.desc);
     // Bind the Vector3 class
         staticFunc(constructVector3,_T("constructor")). // here's our custom cunstructor
     // Bind the Actor class
     // Create an Actor object
     Actor *pActor = new Actor( "TestActor", mSceneMgr, Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) );
     // Call initActor function and pass object by reference
     // Shutdown the VM when finish
     // Delete Actor object
     delete pActor;
     // Set ambient light
     mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5));
     // Create a light
     Light* l = mSceneMgr->createLight("MainLight");

I've put everything in the createScene method. First of all we create the Virtual Machine. Then we compile and run the script "Test.nut". The Test.nut file is in a directory where the ResourceGroupManager can read it, or the same directory of the exe file. It depends on which method you use to read it. After that we bind the classes Actor and Vector3. Note how the constructor is bind.
Finally we create an Actor object and the initActor (define in Test.nut) function is called. Note that pActor is passed by reference.

(NOTE: You probably should have a constructor and destructor in the SquirrelOgre class.)

static void printFunc(HSQUIRRELVM v,const SQChar * s,...)
      std::string tempStr = "";
      static SQChar temp[2048];
      va_list vl;
      scvsprintf( temp,s,vl);
 };        //ends the class
 #endif    //ends #ifndef

This function must be a member of the same class as create scene above (SquirrelOgre)
This function requires the stdarg.h header, which allows you to do the magic required to make a function behave like printf, that is taking many arguements relating to the prototype you also send ( something like "Days %d: Name: %s" with additional integer and string arguements).

Now all the output from the VM, including exceptions and the ::print() function, is written to squirrel.log through the Ogre log manager.

Finally let's see Test.nut

// ==========================================================
 // Test.nut
 // ==========================================================
 function initActor( pActor ) {
    pActor.setScale( Vector3(3, 3, 3) );
    pActor.setPosition( Vector3( 0, 0, 0 ) );
    pActor.setMaterialName( "Examples/BumpyMetal" );

Ok that's all. I hope it could be useful for someone. ;)

The Squirrel home page

The SQPlus home page

The thread that started it all, with lots of useful info