Working with SqPlus to support swapping between VM:s during execution, I've encountered a couple of problems. The goal is to create SQVM objects and keep them around for as long as needed, and to get this to happen as automatically as possible.
Since SQVM differs a bit from ordinary Squirrel objects in create / destroy semantics it's been some trial and error. Also, taking both ref-counted and GC:ed execution into account adds some concerns.
Question 1.
To support VM swapping I used reference tracking on the VMs (sq_addref and sq_release). A sqplus class SquirrelVMSys holds a reference on the VM and there can
be several such instances. So, we cannot simply call sq_close() because
only ref count mechanism / GC knows when to delete object now.
And when the SQVM is not referenced anymore, it is correctly destroyed. But... not its SQSharedState (which holds all allocated objects it seems). I got a leak there, and and had to manually delete the SQSharedState.
Ideally, the shared state would be ref counted (GC:ed) and once the last VM using it goes out of scope, the shared state should be destroyed. (it also seems to me that VM:s created using sq_newthread(...) may outlive the original VM (since references can be kept in other places than first VM stack)).
Any suggestion for good workaround here? (Currently I maintain an array of created SQSharedState and destroy them at app shutdown).
Question 2.
When trying this out, I found that in ref count and GC:ed mode, the state of the new VM, after calling sq_open(...), is different. In ref counted mode, we have a ref count of 1. In GC:ed mode, there is no ref to the object at this time. It was easy enough to fix through something like this:
SQVM *v = sq_open( 1024 );
static SquirrelObject ref;
ref = v; // Now have additional ref on VM
DropVMRefIfRefCounted( v ); // Decrease ref _only_ if ref counted Squirrel
// Now have one ref in both GC and ref counted.
The fix is simple enough, but nice if not needed.
Regards
// ATS.