# How do i set Lua variables?

You can pretty easily read variables, but what about writing them to the lua file?

Ive given it a little go, but it doesnt seem to work...

void Lua::setBool(string path, string var, bool val) { //"Lua" is a class with my Lua functions (such as get bool, get float...)
lua_State *L = luaL_newstate();
luaL_openlibs(L);
if (luaL_dofile(L, path.c_str())) { // For some reason, "!luaL_dofile" triggers if i input the path Correctly
string msg = "Unable to open file " + path;
MessageBox(NULL, msg.c_str(), "Lua IO", MB_ICONERROR);
}

lua_pushboolean(L, val);
lua_setglobal(L, var.c_str());

lua_close(L);
}


And yes, ive inputted "var" and "path" correctly.

If you want to write them to the Lua file--as in the script text file itself--you'll have to do it as you would any other text file. As far as I know, Lua doesn't include any way to do this.

• Lua doesn't provide any way to modify a chunk after it's been loaded, or to automagically convert it back into uncompiled source, but it certainly provides you the tools to modify or procedurally generate code. The io library would be the place to start when you want to load/save files. lua.org/manual/5.3/manual.html#6.8 – bcrist Jan 26 '16 at 2:44

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)

• But if i want to write to the lua file? does lua have anything to do that? – user68817 Jan 25 '16 at 10:50