gpt4 book ai didi

c++ - 返回字符串 vector 的最简单的 lua 函数

转载 作者:行者123 更新时间:2023-11-30 03:09:52 27 4
gpt4 key购买 nike

我需要一个非常简单的 c++ 函数,它调用一个返回字符串数组的 lua 函数,并将它们存储为一个 c++ vector 。该函数看起来像这样:

std::vector<string> call_lua_func(string lua_source_code);

(其中 lua 源代码包含一个返回字符串数组的 lua 函数)。

有什么想法吗?

谢谢!

最佳答案

这里有一些可能对您有用的资源。它可能需要更多的润色和测试。它期望 Lua block 返回字符串数组,但稍作修改就可以调用 block 中的命名函数。因此,按原样,它可以使用 "return {'a'}" 作为参数,但不能使用 "function a() return {'a'} end"作为参数。

extern "C" {
#include "../src/lua.h"
#include "../src/lauxlib.h"
}

std::vector<string> call_lua_func(string lua_source_code)
{
std::vector<string> list_strings;

// create a Lua state
lua_State *L = luaL_newstate();
lua_settop(L,0);

// execute the string chunk
luaL_dostring(L, lua_source_code.c_str());

// if only one return value, and value is a table
if(lua_gettop(L) == 1 && lua_istable(L, 1))
{
// for each entry in the table
int len = lua_objlen(L, 1);
for(int i=1;i <= len; i++)
{
// get the entry to stack
lua_pushinteger(L, i);
lua_gettable(L, 1);

// get table entry as string
const char *s = lua_tostring(L, -1);
if(s)
{
// push the value to the vector
list_strings.push_back(s);
}

// remove entry from stack
lua_pop(L,1);
}
}

// destroy the Lua state
lua_close(L);

return list_strings;
}

关于c++ - 返回字符串 vector 的最简单的 lua 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3710796/

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