I have a C++ program that creates a lua_State and run custom Lua script. If I would like to have the lua_State pre-load cjson instead of requiring calling "require" in the Lua code, can I know whether it is possible and how can I do that?
2 Answers
Yes, it's possible. Use luaL_requiref for that. Use this or this function as argument. You'll need to link the cjson code to your executable, and the compiler would probably appreciate a function declaration for the luaopen_* functions. If you use Lua 5.1 (which doesn't have luaL_requiref yet) you can use or steal from Compat-5.3.
You could call require once through C++ and make a global variable out of the return value if you don't want to call require in scripts.
For example in C++ do:
if (luaL_dostring(L, "cjson = require(\"cjson\")")) // run code
std::cout << luaL_checkstring (L, -1) << std::endl; // print error
and after that you can use cjson in your scripts like cjson.new() without any require or such calls as it exists as a global variable.
Since require was used by C++ then calling require in lua later on will not run the cjson file again unlike using dofile or similar