Actually, you work Lua into C++, not the other way around. Lua is a scripting language, this means that it gets compiled at runtime. C++ is a compiled language and it gets compiled before runtime. You can find a Lua engine for C++. The C++ code will determine which lua script to run and when to run these.
You'll need to download a Lua Engine which contains a library and header file. You can find this here:
http://www.lua.org/.
Now you write a Lua script. I'm not going to get into that here.
Now you open an instance of Lua, and load the script, and run it!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
int main()
{
const char* file = "myscript.lua"
lua_State *L = lua_open(); // Opens a Lua handle
luaopen_io(L); // provides io.*
luaopen_base(L);
luaopen_table(L);
luaopen_string(L);
luaopen_math(L);
luaopen_loadlib(L);
int error = luaL_loadfile(L, file); // Loads the script
if ( error==0 )
error = lua_pcall(L, 0, LUA_MULTRET, 0); // Runs the script
report_errors(L, error);
lua_close(L);
}
return 0;
}
|
Next question is: Great I've run a script... but it hasn't influenced my program. How can I communicate?
You can create your custom Lua functions. You will register this function with the script, the script has access to it and it will provide arguments which you can use. You can also send one or more return values back to Lua.
1 2 3 4 5 6 7 8 9 10 11 12
|
int my_function(lua_State *L) // arguments come from lua
{ // return value goes to lua
int argc = lua_gettop(L); // number of arguments
// each argument passed by Lua can be accessed with lua_tostring and the index
for (int i = 1, i <= argc; ++i)
std::cout << lua_tostring(L, n) << std::endl;
lua_pushnumber(L, 123); // return value
return 1; // number of return values
}
|
To make the function available to the Lua scripts, you need to register it before you call the scripts with this in line 19 of the first code snippet:
lua_register(L, "my_function", my_function);
And there you go! You have lua running with 2-way communication between C++ and Lua!