C - LuaJit 将自定义模块名称分配给已编译的字符串

标签 c module lua luajit

我有一个小的 C 程序,它有一个字符串,它必须代表一个 Lua 模块,它看起来像这样:

const char *lua_str = " local mymodule = {} \
    function mymodule.foo() \
        print(\"Hello World!\") \
    end
    return mymodule";

或者可能使用旧方法(如果需要):

const char *lua_str = "module(\"mymodule\", package.seeall \
    function foo() \
        print(\"Hello World!\") \
    end";

让我们假设这是我的小型主机应用程序:

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

int main(int argc, char** argv)
{
    lua_State *L = lua_open();
    luaL_openlibs(L);

    luaL_dostring(L, lua_str);
    luaL_dofile(L, "test.lua");

    return 0;
}

现在在 test.lua 中可以使用那个不是由文件名决定的 static 名称的模块:

local mymodule = require "mymodule"
mymodule.foo()

基本上,我需要执行该字符串并为其指定一个代表实际模块名称的自定义名称。目前名称由文件名决定,我不希望这样。

最佳答案

如果您查看 documentation for require :

Loads the given module. The function starts by looking into the package.loaded table 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, require is guided by the package.loaders array. By changing this array, we can change how require looks for a module. The following explanation is based on the default configuration for package.loaders.

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 package.loaders).

Once a loader is found, require calls the loader with a single argument, modname. If the loader returns any value, require assigns the returned value 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.

您会看到它详细解释了 require 使用什么方法来查找给定模块名称的代码。该解释中隐含了关于如何将任意 block 已加载(或可加载)代码分配给您想要的任何给定名称的指示。

具体来说,如果您在 package.loaded[modname] 中设置一个值,该值将立即返回。如果做不到这一点,package.preload[modname] 将用作加载程序(这是一个采用模块名称的函数)。

关于C - LuaJit 将自定义模块名称分配给已编译的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25676920/

相关文章:

c - 从另一个结构访问结构数据

python - 是否有替代 python 函数作为 PHP include() 函数?

javascript - 带有 ES6 模块的命名空间

java - Maven - 在主模块中运行子模块的插件任务

resize - 在纯Lua中为jpeg图像制作缩略图?

function - 如何收集加载中的函数返回值

C语言: How to share a struct (or,如果不可能,一个数组)通过IPC在父子( fork )进程之间?

c - 如何根据strlen比较4个字符串的长度

c - 当在其条件中使用赋值和后缀运算符时,while 循环如何工作

lua - 'none'是Lua中的基本类型之一吗?