Lua函数返回C++字符串。 在C++代码中,您可以使用Lua API中的luaL_dostring()函数执行Lua代码。在Lua函数中,您可以使用Lua API中的lua_pushstring()函数将字符串压入Lua堆栈。然后在C++代码中,您可以使用lua_tostring()函数将字符串从Lua堆栈弹出并返回到C++代码中。

在通过 C++ 向 Lua 添加一个返回字符串的函数,这是可行的吗? -编辑- 好吧,这段代码不起作用。有什么帮助吗?

int flua_getinput(lua_State *L){
    if(lua_isstring(L,1)){
        cout << lua_tostring(L,1);
        cin >> input;
        cout << "\n";
        lua_pushstring(L,input);
    }else{
        cin >> input;
        cout << "\n";
        lua_pushstring(L,input);
    }
    return 1;
}
注册函数:

lua_register(L,"getinput",flua_getinput);

原文链接 https://stackoverflow.com/questions/3115028

点赞
stackoverflow用户161424
stackoverflow用户161424

你是否已经查看了《Lua 程序设计》

2010-06-25 01:46:43
stackoverflow用户339430
stackoverflow用户339430

这个页面展示了如何从 Lua 中获得一个 char*。

[This page](http://www.codeproject.com/KB/cpp/luaincpp.aspx)

2010-06-25 01:55:48
stackoverflow用户374980
stackoverflow用户374980

最简单的方法是使用 luabind。它自动检测并处理 std::string,因此只需将函数 std::string f() 绑定到 lua,并在 lua 脚本调用它时将自动转换为原生 lua 字符串。

2010-06-25 02:00:28
stackoverflow用户173806
stackoverflow用户173806

如果您遇到错误 attempt to call global 'getinput' (a nil value),则问题在于 lua_register 调用未被触发。必须通过调用注册函数或使用 require(如果它在库中)来加载 getinput 函数。

2010-06-25 17:14:44
stackoverflow用户30470
stackoverflow用户30470

你是否正在尝试做类似下面的事情?

int lua_input(lua_State* L) {
    string input;
    cin >> input;
    lua_pushstring(L, input.c_str());
    return 1;
}

int main() {
    lua_State* L=lua_open();
    luaL_openlibs(L);
    lua_register(L,"input",lua_input);
    luaL_loadstring(L, "for i=1,4 do print('you typed '..input()); end");
    lua_pcall(L, 0, 0, 0);
}
2010-06-25 17:43:46