返回介绍

require (modname)

发布于 2019-08-25 13:17:15 字数 2581 浏览 994 评论 0 收藏 0

Loads the given module.
The function starts by looking into the table package.loaded
to determine whether modname is already loaded.
If it is, then require returns the value stored
at package.loaded[modname].
Otherwise, it tries to find a loader for the module.

To find a loader,
first require queries package.preload[modname].
If it has a value,
this value (which should be a function) is the loader.
Otherwise require searches for a Lua loader using the
path stored in package.path.
If that also fails, it searches for a C loader using the
path stored in package.cpath.
If that also fails,
it tries an all-in-one loader (see below).

When loading a C library,
require first uses a dynamic link facility to link the
application with the library.
Then it tries to find a C function inside this library to
be used as the loader.
The name of this C function is the string "luaopen_"
concatenated with a copy of the module name where each dot
is replaced by an underscore.
Moreover, if the module name has a hyphen,
its prefix up to (and including) the first hyphen is removed.
For instance, if the module name is a.v1-b.c,
the function name will be luaopen_b_c.

If require finds neither a Lua library nor a
C library for a module,
it calls the all-in-one loader.
This loader searches the C path for a library for
the root name of the given module.
For instance, when requiring a.b.c,
it will search for a C library for a.
If found, it looks into it for an open function for
the submodule;
in our example, that would be luaopen_a_b_c.
With this facility, a package can pack several C submodules
into one single library,
with each submodule keeping its original open function.

Once a loader is found,
require calls the loader with a single argument, modname.
If the loader returns any value,
require assigns it to package.loaded[modname].
If the loader returns no value and
has not assigned any value to package.loaded[modname],
then require assigns true to this entry.
In any case, require returns the
final value of package.loaded[modname].

If there is any error loading or running the module,
or if it cannot find any loader for the module,
then require signals an error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文