[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: execute function:second revision
- From: "Littlefield, Tyler" <tyler@...>
- Date: Tue, 30 Aug 2011 18:26:24 -0600
Hello:
Here's my revised execution function. Everything seems to work until I
get to the pcall, where it fails. What am I doing wrong here?
Also, if there is a way to make this cleaner/remove the meta table after
I'm done executing, I'd appreciate any advice.
void Script::Execute(Entity* obj, const std::string &code)
{
std::cout << "Executing " << code << std::endl;
char id[16];
World* world = World::GetPtr();
//we need to create a new metatable for the object so we have a sanitary
execution context.
if (!obj)
{
std::cout << "Invalid object." << std::endl;
return;
}
if (obj->IsPlayer())
{
memcpy(id, obj->GetName().c_str(), obj->GetName().length());
}
else
{
NumberToString(id, obj->GetOnum());
}
if (!luaL_newmetatable(state, id))
{
std::cout << "Could not create metatable." << std::endl;
std::cout << id << std::endl;
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.
if (!luaL_loadbuffer(state, code.c_str(), code.length(), "execution"))
{
//we set the table
lua_getmetatable(state, -2);
//now we setfenv
lua_setfenv(state, -2); //the function is back at -1
//we call the code.
if (lua_pcall(state, 0, 0, 0))
{
std::cout << "pcall failed." << std::endl;
world->WriteLog(lua_tostring(state, -1), SCRIPT, "script");
lua_gc(state, LUA_GCCOLLECT, 0);
}
}
}
--
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!