gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:47:32 26 4
gpt4 key购买 nike

我有一个小的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com