是否可以 require() 使用 luaL_loadstring() 加载的脚本? [英] Is it possible to require() a script that is loaded using luaL_loadstring()?

查看:28
本文介绍了是否可以 require() 使用 luaL_loadstring() 加载的脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Lua 的初学者.

I'm a beginner in 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>
", 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
", lua_tostring(L, -1));
        lua_close(L);
        return 1;
    }

    lua_close(L);
}

输入脚本:

local fromstring = require("fromstring")
fromstring.test()

输出:

Test

这篇关于是否可以 require() 使用 luaL_loadstring() 加载的脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆