Lua package containing subpackages
I wrote several modules for Lua in C. Each of them contains a Lua useridata datatype and I load and use them like this:
A = require("A")
B = require("B")
a = A.new(3,{1,2,3})
b1 = B.new(1)
b2 = B.new(2) * b1
Now I would like to put both types of user data into one shared library AandB
that can be used like
AB = require("AandB")
AB.A.new(3,{1,2,3})
What's a good way to achieve this? Right now my functions luaopen_*
look like this:
int luaopen_A(lua_State *L) {
luaL_newmetatable(L, A_MT);
luaL_setfuncs(L, A_methods, 0);
luaL_newlib(L, A_functions);
return 1;
};
And is it possible then to load only a part, for example. for example A = require("AandB.A")
:?
require("AandB.A")
works if you define luaopen_AandB_A
in your C library which one needs to be called AandB.so
.
Generally require
replaces periods with underscores when trying C libraries.
One thing you can do is to write a module lua script, which will pull both A
and B
. Then you can require the script from your used code:
-- AandB.lua
return { A = require 'A', B = require 'B' }
If you want to load part of your module, you can simply do:
A = require "AandB".A