Implicit parameter to factory function?

Started by
1 comment, last by Mr Molesley 8 years, 7 months ago

Hi,

I have a class, implemented in C++, that can be instantiated from AngelScript. As per AS documentation, I have a global factory function that doesn't take any parameter.

Now, I want to pass a parameter to the C++ constructor, but I don't want the script writer to have to supply it - the script doesn't know about the parameter. The reason is that I'm using AS to enable users to extend my application, and requiring them to type in this parameter is both redundant and inconvenient for them.

At the moment, I've solved this using a global variable, that I set to a certain value before executing the AS code, and then reset afterwards. The factory function reads the global variable and does "return new MyThing(globalParameter)". However, it would be much cleaner to, somehow, supply a parameter to the factory function - which in turn can supply it to the constructor - "behind the scenes". The global variable method is the only solution I can think of, so I'm asking for help.

I hope this question is reasonably clear. I've rephrased it a couple of times. smile.png If it's not clear, I'll type up some example code.

Thanks in advance!

Advertisement

You could implement the factory function for the object as a functor, and register it with the calling convention asCALL_THISCALL_ASGLOBAL. The functor object can then hold the value that you wish to pass to the object constructor.

class MyFunctor
{
Object *Factory() { return new Object(value); };
int value;
};
 
MyFunctor *factoryFunctor = new MyFunctor;
factoryFunctor->value = 42; // change this whenever you want a different value for the Object constructor
 
engine->RegisterObjectBehaviour("Object", asBEHAVE_FACTORY, "Object @f()", asMETHOD(MyFunctor, Factory), asCALL_THISCALL_ASGLOBAL, factoryFunctor);

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

That's perfect! I had a feeling that something along those lines might be possible, but to be honest I don't completely understand what calling conventions actually are yet, so I couldn't figure it out myself. This will help me both with my project and understanding calling conventions.

Thanks!

This topic is closed to new replies.

Advertisement