Lua package containing subpackages

147 views Asked by At

I have written a number of modules for Lua in C. Each of these contains a Lua userdata type 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 userdata types in a single shared library AandB that can be used like this

AB = require("AandB")
AB.A.new(3,{1,2,3})

What is a good way to achieve this? Right now my luaopen_* functions 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 still load only part, e.g. like this: A = require("AandB.A")?

2

There are 2 answers

2
lhf On

require("AandB.A") works if you define luaopen_AandB_A in your C library, which must be called AandB.so.

In general, require replaces dots with underscores when trying C libraries.

1
greatwolf On

One thing you can do is to write a lua script module that pulls in both A and B. You can then require that script from your using code:

-- AandB.lua
return { A = require 'A', B = require 'B' }

If you only want to load part of your module, you can just do:

A = require "AandB".A