LUA itself is a scripting language. The advantage of using Lua or other scripting languages with your C/C++ programs is you can write your application control logic in C++ and for things like AI for instance as a script. Once you compile your main program, you can change the behavior of your AI without having to recompile. That's just the most popular example for using scripts, but you can use them for anything you'd like. Another example would be to use them as a configuration utility. Since the lua api does all the file parsing for you, you can setup a file with all your settings then just use the api to read them in.
Using the api however has been more than a little confusing to me. You interact with the Lua api through it's pseudo stack. Say you have a variable in your config file called 'width'. To get the value, you must tell the api to look up the variable, push it's value on the stack, get the value, then pop the value off the stack to keep the stack clean and from filling up.
In this way, it's as if your C++ application has become the CPU or assembly interpreter...can't make a good comparison lol.
I haven't made it to calling Lua functions yet, but I've looked over a few tutorials and the reference manual and it's basically the same thing;
- find the function by name
- push it on the stack
- push any and all parameters onto the stack
- call the function
- pop the function off the stack
- pop the params off the stack
- get any return values ( lua can return multiple values )
- pop return values off the stack
Since I'm using C++, I'm also having to learn some foreign C++ stuff as well, like variadic templates which will help with the function calling, since functions can have multiple arguments or no arguments.
The trouble I have with variadic templates is the unpacking. I've come up with a solution since all the arguments to the functions are sent from C++ to the Lua api as strings ( char * really ) I pass a reference to an std::vector<std::string> and just keep adding ( push_back ) each recursive iteration of a helper function. So far this has worked, but I'm open to better solutions.
Has anyone else looked into or has imtegrated Lua or another scripting language into their C++ projects?
Have any hints or advice on the topic?