Advertisement

Passing an object from AngelScript to C++

Started by September 18, 2009 02:29 AM
10 comments, last by WitchLord 15 years, 2 months ago
I got it now! I should have seen earlier that you can register a reference type that can't be initialize by the script. I also misunderstood about executing a script function from the application. You have to prepare it first, then set the arguments to the context, and after that you can execute it, right? I didn't know about this since all the examples in the manual seems to deal with a function that has no return values and no arguments.

So I register that, as well as AddRef and Release behaviour. Then I call the script like this

[/source]

//CPP Side
void GamePlayer::attack(){    PrepareScriptFunction( "PlayerModule", "void attack(GamePlayer @player)");    AngelContext->SetArgObject( 0, this );    ExecuteScriptFunction();}



Also, since I didn't want to let the script handle the memory management for GamePlayer, I didn't put the " if( refcount == 0) delete this; " in the Release method. And at the end of the script function void attack, I set the argument to point to null. Would this be ok or the script will still hold a reference of the GamePlayer?
If you do not handle the reference counting, then you need to be careful that the scripts do not store any references to the object in global variables. You could do that by enumerating the variables. But it will probably be difficult to guarantee that no references are not still being kept around.

In my own engine I solve this by using a simple proxy class, sort of like a smart pointer. The reference that the script works on is to the proxy class rather than the real object, the real object also has a reference to the proxy class. Doing it this way, I can easily destroy the real object if I want without having to worry about any unwanted references still accessing it. This is done by simply updating the proxy class' reference to set it to null, and then have the proxy class know how to handle that (e.g. not do anything when it is no longer pointing to a real object).

It requires a bit more work to write the proxy class, as you need to implement wrappers for all methods you want to expose to the script, but in the end I think it is much easier than having to deal with complicated memory management. I also use these proxy classes from other locations in the game engine, so it is not something done just for the script engine.

Regards,
Andreas

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

This topic is closed to new replies.

Advertisement