Some notes on Squirrel

Posted on 03 Feb 2013

Squirrel is an embeddable language with an API very similar to Lua’s (stack based). Squirrel has a lot of nice language features that you can see on their site. Here are some notes on certain parts of squirrel that I’ve come across so far.

A more complete definition for _inherited

The _inherited metamethod which is called when a class extends the class that implements it. It’s defined as such (with this being the new class):

function _inherited(attributes) { ... }

For starters, the attributes parameter is from the deriving class not the base class (the one that implements _inherited). I know I said “definition”, but here’s some behaviour traits as well. The new class that gets the name this has no attributes. If you planned on using attributes to track things like class name you have to use static variables. I’m actually pretty confused on this one as SQClass (squirrel internal class) does copy attributes from the base class before _inherited is called, you just cannot get at them

The this variable - While it does allow you to mess with the members of the class before it gets squished together with the deriving class, it has a limitation. You cannot just pull the rug out from under the deriving class and throw it a completely different class as shown below.

class Base
{
	constructor(s)
	{
		print("Hi from Base, got string: " + s + "\n");
	}

	function something_important()
	{
		//TODO: launch missile
	}

	function _inherited(attributes)
	{
		this = SomeOtherClass; // fails silently - cause it didn't actually fail.
	}
}

class Derived extends Base
{
	constructor()
	{
		base.constructor("Derived");
	}
}

Sure I could have just said this was inside local scope, but everything is better with examples. This means you need to manually copy everything.

Tables and metamethods

If you want to do something like override _newslot or something in a table, you need to stick your fancy implementation of _newslot into a delegate and set it for the table. This is obvious but I overlooked it when I forgot that there’s a difference between classes and tables.

local t = { //table we won't to override _newslot on
_newslot = function(k, v) // Won't work as tables don't do metamethods like this
	{
		this.rawset(k, v); 
	}
}

//This will work
local delegate = {_newslot = function(k, v) { this.rawset(k, v); }}

local t = {}
t.setdelegate(delegate)

Pretty much like lua with it’s metatables.

Other Stuff

comments powered by Disqus