Lua包含子包的软件包。

我已经用 C 编写了许多用于 Lua 的模块。其中每个模块都包含一个 Lua 用户数据类型,并且我会像这样加载和使用它们:

A = require("A")
B = require("B")
a = A.new(3,{1,2,3})
b1 = B.new(1)
b2 = B.new(2) * b1

现在,我想将这两种用户数据类型放在单个共享库 AandB 中,可以像这样使用它:

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

如何实现这一点?现在我的 luaopen_* 函数看起来像这样:

int luaopen_A(lua_State *L) {
  luaL_newmetatable(L, A_MT);
  luaL_setfuncs(L, A_methods, 0);

  luaL_newlib(L, A_functions);

  return 1;
};

还可以像这样只加载部分代码吗,例如 A = require("AandB.A")

点赞
用户234175
用户234175

你可以编写一个 Lua 脚本模块来同时调用 AB。然后可以从需要使用的代码中 require 该脚本:

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

如果你只想加载模块中的一部分,你可以这样做:

A = require "AandB".A
2014-12-04 23:08:08
用户107090
用户107090

require(“ AandB.A”)只会在你的 C 库中定义luaopen_AandB_A,并且该库必须称为AandB.so 时才能工作。

通常情况下,require 会在尝试使用 C 库时将点替换为下划线。

2014-12-05 01:30:13