1

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);
3
  • Yes, it is possible. If you want more of an answer, you'll have to provide a bit more context: what have you tried, and why doesn't it appear to be working? Commented Jun 25, 2010 at 1:38
  • I can't just get a example of how to do it? I'm just trying to learn C++ and Lua. I don't know what to start with. Commented Jun 25, 2010 at 1:44
  • Lua error: lua: [string "init.lua"]:1: attempt to call global 'getinput' (a nil value) Commented Jun 25, 2010 at 2:06

5 Answers 5

2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

+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 - you are correct. I was just trying to keep it as simple as possible.
1

Have you checked out Programming in Lua?

Comments

1

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

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.