If your intention is to modify your Lua State so that your Lua script can access parameters set from C++, you need to actually set those values before calling into Lua (luaL_dofile
is a helper for loading a chunk from a file, compiling it if necessary, and immediately executing it). So the following lines should be moved up just after luaL_openlibs
.
lua_pushboolean(L, val);
lua_setglobal(L, var.c_str());
Note that a Lua chunk is actually a function from Lua's perspective, so you can actually just push parameters onto the Lua stack and avoid polluting the global environment. Then you could access them in Lua using something like:
local paramA, paramB = ...
However you can't use luaL_dofile
to do this. It's just syntactic sugar for (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
. In order to pass parameters on the stack you'd need to expand it out so you can replace the first 0
in lua_pcall
with the number of arguments you want to pass. You can return values from Lua chunks in a similar fashion.
Regarding your confusion in the comments of your code regarding the return value of luaL_dofile
, it returns an integer status code. Most lua*
functions that aren't retrieving a value return a status code indicating if everything went alright, or a vague idea of what went wrong. If everything's peachy, it will return LUA_OK
, which happens to be defined as 0
. So you should say:
if (luaL_dofile(L, path.c_str()) != LUA_OK)