Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to make exported module non-global? #135

Open
jinq0123 opened this issue Apr 27, 2017 · 6 comments
Open

How to make exported module non-global? #135

jinq0123 opened this issue Apr 27, 2017 · 6 comments

Comments

@jinq0123
Copy link

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()
@SteveKChiu
Copy link
Owner

@jinq0123
Copy link
Author

jinq0123 commented May 8, 2017

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
Copy link
Author

jinq0123 commented May 8, 2017

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

@SteveKChiu
Copy link
Owner

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

@jinq0123
Copy link
Author

Thanks. Let me try it.

@jinq0123
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants