00001
00002
00003
00004
00005
00006
00007
00008
00009
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00030
00031
00032 #include "luacallback.h"
00033 #include "stratagus.h"
00034 #include "script.h"
00035
00036
00043 LuaCallback::LuaCallback(lua_State *l, lua_Object f) :
00044 luastate(l), arguments(0)
00045 {
00046 if (!lua_isfunction(l, f)) {
00047 LuaError(l, "Argument isn't a function");
00048 Assert(0);
00049 }
00050 lua_pushvalue(l, f);
00051 luaref = luaL_ref(l, LUA_REGISTRYINDEX);
00052 }
00053
00058 void LuaCallback::pushPreamble()
00059 {
00060 base = lua_gettop(luastate);
00061 lua_getglobal(luastate, "_TRACEBACK");
00062 lua_rawgeti(luastate, LUA_REGISTRYINDEX, luaref);
00063 arguments = 0;
00064 }
00065
00066
00072 void LuaCallback::pushInteger(int value)
00073 {
00074 lua_pushnumber(luastate, value);
00075 arguments++;
00076 }
00077
00078
00084 void LuaCallback::pushString(const std::string &s)
00085 {
00086 lua_pushstring(luastate, s.c_str());
00087 arguments++;
00088 }
00089
00090
00096 void LuaCallback::run()
00097 {
00098 int status;
00099
00100
00101 status = lua_pcall(luastate, arguments, 0, base);
00102 if (status) {
00103 const char *msg;
00104 msg = lua_tostring(luastate, -1);
00105 if (msg == NULL) {
00106 msg = "(error with no message)";
00107 }
00108 fprintf(stderr, "%s\n", msg);
00109 lua_pop(luastate, 1);
00110 }
00111 }
00112
00116 LuaCallback::~LuaCallback()
00117 {
00118 luaL_unref(luastate, LUA_REGISTRYINDEX, luaref);
00119 }
00120