I’m creating a 2D RPG game engine in C++ with Allegro. I’ve reached the point in which i need to implement a scripting system. So, my poblem is this one:
I have a struct called Event. Inside this struct there is a function pointer, which points to the function that i want to execute when the event is fired. So, here’s an example:
struct Event {
//...
void (*func)(Player*, void*);
//...
}
Now, to create an event i have this function:
Event* Events::register_event_source(int x, int y, std::string name, Player* player, void (*func)(Player*, void*));
So, to use it i just need to create a function with this signature:
void test_event(Player* p, void* data)
{
//Do something cool here
}
and then register an event source, giving the address to that function:
//...
Player* player = new Player(0, 0);
//...
Event* evt = Events::register_event_source(10, 10, "test event", player, &test_event);
//Eventually set some data for the event
evt->set_data(new std::string("Just some test data"));
In this way, when the player goes over the assigned spot (in this case x = 10, y = 10) the event will fire, executing any code in the test_event function.
Now, my question is: is it possible to do, or at least to get close to, this process at runtime?? …i would need to create the function (in this case “test_event”) at runtime, but i did some research, and i think what i understood is that it is not really possible to create functions at runtime.
So, which approach should i go for?? …I know it is an abstract question…but i really don’t know how to approach this problem.
Thanks in advice for any help! and sorry for my bad explaining abilities…English is not my language!
If I understand correctly what you are trying to express, you are writing a scripting engine that interprets some logics built at run-time into a string, and this should determine what to do on
Playeranddata. If so, I can imagine you should have a function likeor something equivalent that interprets and execute the logics described in
codeonpanddata.Then, you can use
std::bindandstd::functionto encapsulate a call to your scripting engine:And pass
fxnin input to yourregister_event_source()function.Btw, you might be interested in using Boost.Signals/Boost.Signals2 for realizing event registration/handling.
If you are not using C++11, you can use
boost::bindandboost::functioninstead ofstd::bindandstd::function.