lua-intf icon indicating copy to clipboard operation
lua-intf copied to clipboard

How to make exported module non-global?

Open jinq0123 opened this issue 8 years ago • 6 comments

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()

jinq0123 avatar Apr 27 '17 03:04 jinq0123

Please see the readme:

https://github.com/SteveKChiu/lua-intf#integrate-with-lua-module-system

SteveKChiu avatar May 08 '17 09:05 SteveKChiu

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

jinq0123 avatar May 08 '17 10:05 jinq0123

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;
        ...
}

jinq0123 avatar May 08 '17 10:05 jinq0123

"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);

SteveKChiu avatar May 09 '17 11:05 SteveKChiu

Thanks. Let me try it.

jinq0123 avatar May 10 '17 04:05 jinq0123

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.

jinq0123 avatar May 10 '17 07:05 jinq0123