How to make exported module non-global?
int main()
{
...
LuaBinding(L).beginModule("c_util")
.addFunction("foo", []() { return 123; })
.endModule();
...
}
This makes c_util global.
Is there any way to make it not global, so I can use it like this?
local c_util = require("c_util")
c_util.foo()
Please see the readme:
https://github.com/SteveKChiu/lua-intf#integrate-with-lua-module-system
I am not making a dll/so.
Do I have to make a c_util.dll to use require("c_util")?
If no c_util.dll, require("c_util") will say
module 'c_util' not found
Shall I do it like this:
int main()
{
...
LuaRef mod = LuaRef::createTable(L);
LuaBinding(mod).beginModule("c_util")
.addFunction("foo", []() { return 123; })
.endModule();
// set package.preload['c_util'] = mod to allow lua "require('c_util')"
LuaRef table(L, "package.preload");
table["c_util"] = mod;
...
}
"package.preload" is a table of functions, thus you need to assign function, not module (which is table) I believe if you follow the module example:
https://github.com/SteveKChiu/lua-intf#integrate-with-lua-module-system
And assume the module function is "open_my_module" (renamed from luaopen_modname example), all you need to do is:
LuaRef table(L, "package.preload");
table["c_util"] = LuaRef::createFunctionWith(L, open_my_module);
Thanks. Let me try it.
It works.
From "Programming in Lua 3ed":
For instance, a C library statically linked to Lua can register its luaopen_ function into the preload table, so that it will be called only when (and if) the user requires that module. In this way, the program does not waste time opening the module if it is not used.