先看require的帮助文档
If the loader returns any non-nil value,
requireassigns the returned value topackage.loaded[modname]. If the loader does not return a non-nil value and has not assigned any value topackage.loaded[modname], thenrequireassigns true to this entry
这句话的意思就是:如果加载器返回的是一个非空值,那么将这个非空值赋值到package.loaded[modname]也就是require的返回值。如果加载器没有返回值,那么会赋值给它一个true。
那么,为什么loader没有返回值呢?无非2中情况
xxx.so(或xxx.dll)共享库的约定接口int luaopen_xxx函数
1、没有向lua堆栈返回任何内容,即没有向lua导出任何函数。
2、导出内容了,但是没告诉lua。luaopen_xxx签名遵从lua_CFunction,这个函数的通过
returns in C the number of results(用C语言返回结果的个数)。
也就是luaopen_xxx的返回值必须不为0,通常导出函数表,return 1.


这篇博客详细解释了 Lua 中 `require` 函数的工作原理。当加载器执行后,如果返回非空值,该值会被赋给 `package.loaded[modname]`。若加载器没有明确返回值,但已设置 `package.loaded[modname]`,则其值为 true。对于 C 库的 luaopen_xxx 函数,必须返回非零值以导出函数表。总结了 loader 返回值的重要性以及对模块加载的影响。

897

被折叠的 条评论
为什么被折叠?



