问题描述
我是Lua的初学者.
我想知道是否可以使用require('filename')
要求使用luaL_loadstring()
加载的脚本.
I wonder if it is possible to use require('filename')
to require a script that is loaded using luaL_loadstring()
.
由于luaL_loadstring(lua_State *L, const char *s)
没有指定任何文件名,所以我不知道如何使用require()
从其他脚本加载该脚本.
Since luaL_loadstring(lua_State *L, const char *s)
doesn't specify any filename, I don't know how to use require()
to load this script from other script.
require()
仅适用于实际的.lua
文件吗?
Does require()
only works with actual .lua
files?
推荐答案
luaL_loadstring
创建一个Lua函数,该函数在被调用时将执行给定的字符串.我们可以使用这个事实,因为Lua C模块还简单地调用函数luaopen_MODULE
.此函数返回包含模块内容的表.也就是说,如果我们想通过luaL_loadstring
加载模块,则以字符串形式给出的脚本必须返回一个表.剩下要做的唯一一件事就是让解释器知道在哪里可以找到模块.因此,我们只需在package.preload
中创建一个条目.
luaL_loadstring
creates a Lua function which, when called, executes the string it was given. We can use this fact, because Lua C modules also simply call a function luaopen_MODULE
. This function returns a table with the module content. That is to say, if we want to load a module via luaL_loadstring
the script given as a string has to return a table. The only thing left to do is letting the interpreter know where to find the module. Therefore we simply create an entry in package.preload
.
有趣的部分在破折号之间.剩下的只是使解释器运行的样板. (可能无法在5.1中使用)
The interesting part is between the dashes. The rest is just boilerplate to get the interpreter running. (Might not work in 5.1)
#include <stdio.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <script.lua>\n", argv[0]);
return 1;
}
lua_State * L = luaL_newstate();
luaL_openlibs(L);
// ---- Register our "fromstring" module ----
lua_getglobal(L, "package");
lua_getfield(L, -1, "preload");
luaL_loadstring(L, "return { test = function() print('Test') end }");
lua_setfield(L, -2, "fromstring");
// ------------------------------------------
if (luaL_dofile(L, argv[1]) != 0) {
fprintf(stderr,"lua: %s\n", lua_tostring(L, -1));
lua_close(L);
return 1;
}
lua_close(L);
}
输入脚本:
local fromstring = require("fromstring")
fromstring.test()
输出:
Test
这篇关于是否有可能require()使用luaL_loadstring()加载的脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!