user187418
user187418

Reputation:

Calling a Lua string with C

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?

Upvotes: 4

Views: 6174

Answers (2)

einverne
einverne

Reputation: 6682

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.

Upvotes: 0

interjay
interjay

Reputation: 110108

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.

Upvotes: 7

Related Questions