I’ve been working on and off on a project to create an in-game console for my flash projects. Initially it had a simple command system, called “Slang”, where a function could be associated with a string and called from the console, and that was all it could do. Eventually I added limited support for parameters, but value passing was extremely brittle and only one function could be called at a time.
I’ve recently released a major rewrite that constitutes Slang v0.5, which adds support for nested function calls, return values and rudimentary conditionals.
Syntax
Slang is a stack-oriented language inspired by Forth and Stackr. Unlike these languages, however, Slang function calls are ordered left to right. Statements, or lines, may be ended with a semicolon, but this is not required unless multiple separate statements are required to exist separately.
Here’s a simple function call, demonstrating the obligatory Hello World program:
print "Hello, world!"
output: Hello, world!
Here’s a slightly more complex example, to demonstrate the order in which functions and parameters are evaluated:
print equals 1 1
output: true
Functions are called as values are added to the stack immediately after them. In the example above, equals consumes two values and returns one, at which point print consumes one (the value returned by equals) and outputs the value.
Conditionals
The built-in “if” function allows conditional execution. If it receives a false value, the currently executing statement (all code up until the next semicolon) is terminated. Boolean values can be inverted with the “not” function.
Here’s an example:
if equals 1 5 print “1 and 5 are never equal”;
if not equals 1 5 print “1 and 5 are, in fact, not equal”
output: 1 and 5 are, in fact, not equal
Custom functions
Adding custom functions to the Slang interpreter is extremely simple. Pass in a name, a function or method closure, an array of parameter types and the object to invoke the method on, and you’re all set. Here’s how the print function was added:
var slang:SlangInterpreter = new SlangInterpreter();
slang.addFunction("print", print, [String], null, "Print a string to the console");
If you want to try it out or poke around in the source, you can do that here. Slang is currently integrated into my AS3 helper library FLAKit, but the interpreter class is dependency-free and should work fine on its own.
Slang is still a long way from finished, and there are a number of bugs that still need to be addressed; for example, using a semicolon inside a string will cause the compiler to think you’ve started a new statement. I think it’s really coming along, though, and I’m really happy with the progress I’ve made on it so far. I’ve been using it in my most recent project, and being able to edit a script file, hot-reload it with FLAKit, and see the changes instantly without restarting the game is really awesome for productivity.