Basic Interpreter With Shared Variables

I expanded the BASIC script interpreter in to include an example of how you can share variables between your program and the script. For example, you can set a counter in your program, pass that value to the script, and have the script update the value, and then use the new value in your program. Note that since the make file is for Qt, I suggest you compile with g++ *.cpp -o basicscript.

The example ConsoleBasic class now shares two variables with the script, in addition to the CLS command we added in the previous post. An integer variable counter and a string in name$ are now read and modified in the sharedvariable.b sample script.


The program will now show you what the values are before calling the script and after to prove the values were modified. In the code below you can see the counter and name$ being added to the interpreter:

class ConsoleBasic : public SmallBasic
    int m_cls;
    Variable* m_pshared;
    Variable* m_pName;

    ConsoleBasic(const char* pszFilename)
        : SmallBasic(pszFilename),m_cls(0),m_pshared(NULL)
        m_cls = addCommand("cls");

        m_pshared = createNewVariable("counter");

        m_pName = createNewVariable("name$");
        m_pName->setStringValue("Small BASIC Script Engine");

    int counter() {return m_pshared->intValue();}
    const char* name() {return m_pName->stringValue();}

    bool execAddonCommand(const int tok)
        if(tok == m_cls)
        return true;

Which will then be accessible to a script like this:

print "Script starting"

print "Shared variable counter = ";counter
print "Increasing by 10"
counter = counter + 10
print "New value for counter is ";counter

print "Shared variable name$ is ";name$
name$ = "Fred"
print "New value for name$ is ";name$

print "End of script"

The output of basicscript will be as follows. The first and last lines are from the C++ program, while the others are from the script.

$ g++ *.cpp -o basicscript
$ ./basicscript sharedvariable.b 
Shared vars before running script counter [100] name$ [Small BASIC Script Engine]
Script starting
Shared variable counter = 100
Increasing by 10
New value for counter is 110
Shared variable name$ is Small BASIC Script Engine
New value for name$ is Fred
End of script
Shared vars before running script counter [110] name$ [Fred]

Next up: Buffing up ConsoleBasic and make a little something.