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?
Asked
Active
Viewed 5,642 times
2 Answers
6
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.

interjay
- 107,303
- 21
- 270
- 254
-
-
See how errors are handled in this example: http://www.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. – interjay Jan 30 '10 at 21:57
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.

einverne
- 6,454
- 6
- 45
- 91