gpt4 book ai didi

c++ - 从 .lua 的使用句柄调用 lua 函数?

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:54 24 4
gpt4 key购买 nike

我正在做一个试图将 lua 与 c++ 集成的小项目。然而,我的问题如下:

我有多个 lua 脚本,我们称它们为 s1.lua s2.lua 和 s3.lua。其中每一个都具有以下功能:setVars() 和 executeResults()。

现在我可以通过 LuaL_dofile 调用 lua 文件,并在使用 setVars() 和/或 executeResults() 后立即调用。然而这里的问题是,在我加载 s2.lua 之后,我不能再调用 s1.lua 的函数。这意味着我必须重做 s1.lua 上的 LuaL_dofile 才能重新获得对该函数的访问权限,这样做我将无法访问 s2.lua 中的函数。

有没有一种方法可以简单地连续加载所有lua文件,然后开始随意调用它们的函数?像 s1->executeResults() s5->executeResults() s3->setVars() 等

我目前已经有一个系统使用 boost::filesystem 来检测文件夹中的所有 lua 文件,然后我将这些文件名保存在一个 vector 中,然后简单地迭代该 vector 以连续加载每个 lua 文件。

放弃用 lua 文件名填充 vector ,我的插件加载函数现在看起来像这样:

void Lua_plugin::load_Plugins(){
std::vector<std::string>::const_iterator it;
for (it=Lua_PluginList.begin(); it!=Lua_PluginList.end(); it++){
std::cout<<"File loading: " << *it << std::endl;
std::string filename = *it;
std::string filepath = scriptdir+filename;
if (luaL_loadfile(L, filepath.c_str()) || lua_pcall(L, 0, 0, 0)) {
std::cout << "ScriptEngine: error loading script. Error returned was: " << lua_tostring(L, -1) << std::endl;
}
}
}

为了更清楚一点,我在 .lua 中的内容是这样的:

-- s1.lua

setVars()
--do stuff
end

executeResults()
--dostuff
end

等,但我希望能够在连续加载后调用 s1.lua 的 setVars() 和 s2.lua 的 setVars()。

最佳答案

这实际上是 gwell 使用 C API 提出的:

#include <stdio.h>

#include "lua.h"

static void
executescript(lua_State *L, const char *filename, const char *function)
{
/* retrieve the environment from the resgistry */
lua_getfield(L, LUA_REGISTRYINDEX, filename);

/* get the desired function from the environment */
lua_getfield(L, -1, function);

return lua_call(L, 0, 0);
}

static void
loadscript(lua_State *L, const char *filename)
{
/* load the lua script into memory */
luaL_loadfile(L, filename);

/* create a new function environment and store it in the registry */
lua_createtable(L, 0, 1);
lua_getglobal(L, "print");
lua_setfield(L, -2, "print");
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, filename);

/* set the environment for the loaded script and execute it */
lua_setfenv(L, -2);
lua_call(L, 0, 0);

/* run the script initialization function */
executescript(L, filename, "init");
}

int
main(int argc, char *argv[])
{
lua_State *L;
int env1, env2;

L = (lua_State *) luaL_newstate();
luaL_openlibs(L);

loadscript(L, "test1.lua");
loadscript(L, "test2.lua");

executescript(L, "test1.lua", "run");
executescript(L, "test2.lua", "run");
executescript(L, "test2.lua", "run");
executescript(L, "test1.lua", "run");

return 0;
}

测试脚本:

-- test1.lua
function init() output = 'test1' end
function run() print(output) end

-- test2.lua
function init() output = 'test2' end
function run() print(output) end

输出:

test1
test2
test2
test1

为简洁起见,我省略了所有错误处理,但您需要检查 luaL_loadfile 的返回值并使用 lua_pcall 而不是 lua_call .

关于c++ - 从 .lua 的使用句柄调用 lua 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3432231/

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