Sign in to follow this  

Implicit parameter to factory function?

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

If you intended to correct an error in the post then please contact us.

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

 

Thanks in advance!

Share this post


Link to post
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 this post


Link to post
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!

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this