[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: imbedding and execution
- From: "Littlefield, Tyler" <tyler@...>
- Date: Mon, 29 Aug 2011 13:16:34 -0600
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!