• 13
• 18
• 19
• 27
• 10

# Implicit parameter to factory function?

This topic is 929 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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. If it's not clear, I'll type up some example code.

##### Share on other sites

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);


##### Share on other sites

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!