C++ Calling functions from text?

Started by
5 comments, last by The Communist Duck 13 years, 3 months ago
Hey all, i've been wondering for a while if you could call a function from text for example; say you have a XML file that stores the information about an item in game and it would have a variable called "function" and you could set that too "foo" would it be possible to then be able to read that variable in game and call the function "foo"?
Advertisement
Not in C++ without specifying/interpreting the mapping yourself. There's no mechanism to do it automatically, or reflection that would allow you to generate/find the function.
It can be done, but C++ has no built in methods to do so. You need to manually parse the text data for the names "function" and "foo" and then manually decide how the function should be called (or use a third party tool or tools that will do some of this work for you). The relevant topics are called lexical analysis (or just lexing) and parsing.
You could probably do something like have a stl map of function pointers, where the key to each is a string.

then you can just go

functionslist[ string_from_xml ]( );
[size="1"]
If you don't want to do all the work yourself, there's the Lua scripting language, which will work as both code and configuration.
you should look into C/C++ script librarries. ie Angelscript, Lua etc. I use Angelscript. It's easy, fast and has support for class binding.
This is definitely supported in Python.

But you can always have an std::map of function pointers and strings.

This topic is closed to new replies.

Advertisement