views:

100

answers:

5

Is it possible to add a function to Lua via C++ that returns a string? -edit- Ok, this code wont work. 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);
+1  A: 

Have you checked out Programming in Lua?

Cogwheel - Matthew Orlando
+1  A: 

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

Anon
Thanks, but I updated my post with a new problem.
Someguynamedpie
A: 

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.

A: 

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.

gwell
+1  A: 

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);
}
Nick
+1 the OP needs complete code I think. To the OP: If you take this, you **must** also always check every call to loadstring or pcall. And use lua_close at the end.
kaizer.se
@kaizer - you are correct. I was just trying to keep it as simple as possible.
Nick