# Lua protected call and debug

## Recommended Posts

two_laid    100
Hey! I'm using luabind for some kind of plugin system and I wanna use protected calls to provide detailed error messages.. This is where the file is loaded and called:
		lua_pushcfunction(this->m_lua, plugin_error);
ret = lua_pcall( this->m_lua, 0 ,0 ,-2 );
if(ret != 0) {
Log->log(LOG_ERROR, "%s", luaL_checkstring(this->m_lua,-1));
delete this;
return;
}


and the custom error function "plugin_error" is a fucntion i have found on these forums:
int plugin_error(lua_State *L)
{
lua_Debug d;
int depth = -1;
std::stringstream msg;

string err = lua_tostring(L, -1);
lua_pop(L, 1);

while(lua_getstack(L, depth, &d) != 0)
{
lua_getinfo(L, "Sln", &d);
msg << d.short_src << ":" << d.currentline;

if (d.name != 0)
{
msg << "(" << d.namewhat << " " << d.name << ")";
}
msg << " " << err << "\n" << std::endl;
depth++;
}
lua_pushstring(L, msg.str().c_str());

return 1;
}


The problem now is that upon an error (like a missing "end" after an if statement) I just get:
Quote:
 (tail call):-1( ) attempt to call a string value [C]:-1 attempt to call a string value
Apparently, I seem to always get "attempt to call a string value"-errors, no matter what the error is x,X Any idea what I'm doing wrong, or what could be done better? [Edited by - phantom on November 11, 2009 9:00:37 AM]

##### Share on other sites
Sneftel    1788
You forgot to check loadRet, which indicates whether the file compiled successfully and returned a function, or whether it did not compile successfully and instead pushed an error message on the stack.

##### Share on other sites
two_laid    100
well, i was afraid of that, but since pcall would give out an error if the file is not correct, I thought it would be alright to just check for errors after the pcall..
now I tried to check for errors right after the loadfile call and voila! It's working.. thank you :)

here's the working code:
		lua_pushcfunction(this->m_lua, plugin_error);		int loadRet = luaL_loadfile(this->m_lua, file);		if(loadRet != 0) {			plugin_error(this->m_lua);			Log->log(LOG_ERROR, "%s",luaL_checkstring(this->m_lua,-1));			delete this;			return;		}				ret = lua_pcall( this->m_lua, 0 ,0 ,-2 );		if(ret != 0) {			Log->log(LOG_ERROR, "%s", luaL_checkstring(this->m_lua,-1));			delete this;			return;		}

##### Share on other sites
Sneftel    1788
Quote:
 Original post by two_laidwell, i was afraid of that, but since pcall would give out an error if the file is not correct
pcall can't give an error if the file has invalid syntax. If the file has invalid syntax, there's no way to compile it into a function which can be pcalled.