4

I'm trying to learn how to use Lua with C, so by now I want to try running a script without loading it from a file, since I don't want to be bothered with messing up with files. Can anybody tell me which functions do I need to call for executing a simple string or what ever?

1

2 Answers 2

7

You can use luaL_dostring to execute a script from a string.

If you need help with the basics (creating a Lua state, etc.), read part IV of Programming in Lua.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, by the way do you know anything about displaying an error?
See how errors are handled in this example: lua.org/pil/24.1.html That code uses luaL_loadbuffer and lua_pcall instead of luaL_dostring, but it should work the same way.
0

I have created a function in my project to load Lua buffer, following is the code:

bool Reader::RunBuffer(const char *buff,char* ret_string,const char *name){
    int error = 0;
    char callname[256] = "";
    if( m_plua == NULL || buff == NULL || ret_string == NULL ) return false;
    if( name == NULL ){
        strcpy(callname,"noname");
    }else{
        strcpy(callname,name);
    }
    error = luaL_loadbuffer(m_plua, buff, strlen(buff),callname) || lua_pcall(m_plua, 0, 1, 0);
    if (error){
        fprintf(stderr, "%s\n", lua_tostring(m_plua, -1));
        lua_pop(m_plua, 1);
    }else{
        sprintf(ret_string, "%s", lua_tostring(m_plua, -1));
    }
    return true;
}

This code takes buff, and return ret_string. As @interjay said luaL_dostring is a choice.

Comments

Your Answer

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