lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


There is a hook in the pcall IIRC; also, one lib I wrote (lua-icxx, compare http://lua-users.org/wiki/SimpleLuaIcxxExample  to http://lua-users.org/wiki/SimpleLuaApiExample), combined with SWIG, will save you loads of time and allow you script your app not just with Lua but (without extra code) with Python etc. 
Oliver

On Mon, Aug 29, 2011 at 3:16 PM, Littlefield, Tyler <tyler@tysdomain.com> wrote:
Hello all:
I have started work on a project a while back, and wanted to use Lua as the scripting language for customization of objects. First, I've set up an Execute function, so that each object (hopefully) gets it's own global environment. I'm curious if there's a way to make the errors that occur go somewhere else so I can log them; right now my Execute function executes, but nothing happens from there. Here is the function:
void Script::Execute(Entity* obj, const std::string &code)
{
 int index = 0;
 char id[16];
 void* table = 0;
//we need to create a new metatable for the object so we have a sanitary execution context.
 if (!obj)
   {
     return;
   }
 NumberToString(id, obj->GetOnum());
 if (!luaL_newmetatable(state, id))
   {
     return;
   }
 lua_pushstring(state, "__index");
 lua_pushvalue(state, LUA_GLOBALSINDEX);
 lua_settable(state, -3); //table is at -1 again

//we load our code to be executed.
 int status = luaL_loadbuffer(state, code.c_str(), code.length(), "execution");
 if (!status)
   {
//we set the table
     lua_getmetatable(state, -2);
//now we setfenv
     lua_setfenv(state, -2); //the function is back at -1
//we push our traceback function on to the stack.

     lua_getglobal(state, "debug");
     lua_getfield(state, -1, "traceback");
     lua_remove(state, -2); //the traceback field is at the top of the stack.
     index = lua_gettop(state);
//we call the code.
     status = lua_pcall(state, 0, 0, index);
     lua_remove(state, index);
//if it failed, we garbage collect.
     if (status)
       {
         lua_gc(state, LUA_GCCOLLECT, 0);
       }
   }
}

Also: I've started setting up wrappers around a lot of my functions. If someone could take a peak, whether in depth or just a quick glance and give me feedback, I would really appreciate it. I am new to all of this, so I want to make sure I'm doing it right.
First, the main project link:
http://code.google.com/p/aspenmud
The scripts folder, where the Lua code can be found:
http://code.google.com/p/aspenmud/source/browse/#svn%2Ftrunk%2Fsrc%2Fscripts--

Take care,
Ty
my website:
http://tds-solutions.net
my blog:
http://tds-solutions.net/blog
skype: st8amnd127
My programs don't have bugs; they're randomly added features!