简体   繁体   English

Lua函数使用C ++返回字符串

[英]Lua function return string with C++

Is it possible to add a function to Lua via C++ that returns a string? 是否可以通过返回字符串的C ++向Lua添加函数? -edit- Ok, this code wont work. -edit-好的,这段代码不行。 Any help? 有帮助吗?

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;
}
Registering Function:

lua_register(L,"getinput",flua_getinput);

Are you trying to do something like this? 你想做这样的事吗?

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);
}

你有没有看过Lua编程

此页面显示了如何从中获取char *。

The easiest way is to use luabind. 最简单的方法是使用luabind。 It automatically detects and deals with std::string so you can simply take a function like, std::string f() and bind it to lua, and it'll automatically be converted to a native lua string when the lua script calls it. 它会自动检测并处理std :: string,因此您可以简单地使用类似std :: string f()的函数并将其绑定到lua,并在lua脚本调用它时自动转换为本机lua字符串。

If you are getting the error attempt to call global 'getinput' (a nil value) then the problem is that the lua_register call is not being hit. 如果您attempt to call global 'getinput' (a nil value)那么问题是lua_register调用没有被命中。 The getinput function must be loaded by calling the registration function, or by using require if it is in a library. 必须通过调用注册函数来加载getinput函数,或者如果它在库中,则使用require来加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM