开发者

Lua function return string with C++

Is it possible to add a function to Lua via C++ that returns a string? -edit- Ok, this code wont work. Any help?

int f开发者_运维问答lua_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);
}


Have you checked out Programming in Lua?


This page shows how you can get a char* from it.


The easiest way is to use 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.


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. The getinput function must be loaded by calling the registration function, or by using require if it is in a library.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜