scripts load from world
[Tsunagari.git] / src / script.cpp
blobc92ce12079538071abf47c98aabd62ed8a6c372a
1 /******************************
2 ** Tsunagari Tile Engine **
3 ** script.cpp **
4 ** Copyright 2011 OmegaSDG **
5 ******************************/
7 #include "common.h"
8 #include "log.h"
9 #include "resourcer.h"
10 #include "script.h"
12 enum ObjType {
13 ENTITY
16 struct CppObj {
17 ObjType type;
18 union {
19 Entity* entity;
23 Script::Script()
24 : ownState(true), L(lua_open())
26 luaL_openlibs(L);
29 Script::Script(lua_State* L)
30 :ownState(false), L(L)
34 Script::~Script()
36 if (ownState)
37 lua_close(L);
40 void Script::bindGlobalFn(const char* name, lua_CFunction fn)
42 lua_register(L, name, fn);
45 void Script::bindObjFn(const char* table, const char* index, lua_CFunction fn)
47 // Get table.
48 lua_getglobal(L, table);
50 // table.name = fn
51 lua_pushstring(L, index);
52 lua_pushcfunction(L, fn);
53 lua_settable(L, -3);
55 // Done with table.
56 lua_remove(L, -1);
59 void Script::bindInt(const char* name, lua_Integer i)
61 lua_pushinteger(L, i);
62 lua_setglobal(L, name);
65 void Script::bindEntity(const char* name, Entity* entity)
67 // Create table to hold our object and its functions/variables.
68 lua_createtable(L, 0, 3);
70 lua_pushstring(L, "object");
72 // Create type-aware wrapper around Entity.
73 CppObj* obj = (CppObj*)lua_newuserdata(L, sizeof(CppObj));
74 obj->type = ENTITY;
75 obj->entity = entity;
77 // table.object = entity
78 lua_settable(L, -3);
80 // Bind table to Lua.
81 lua_setglobal(L, name);
84 Entity* Script::getEntity(int pos)
86 // Get table.object
87 if (!lua_istable(L, pos))
88 return NULL;
89 lua_pushstring(L, "object");
90 lua_gettable(L, pos);
92 // Check if table.object is an Entity
93 if (!lua_isuserdata(L, -1))
94 return NULL;
95 CppObj* obj = (CppObj*)lua_touserdata(L, -1);
96 if (obj->type != ENTITY)
97 return NULL;
98 return obj->entity;
101 void Script::run(Resourcer* rc, const char* fn)
103 if (!rc->getLuaScript(fn, L)) // error logged
104 return;
106 // TODO: make fourth parameter to lua_call an error handler so we can
107 // gather stack trace through Lua state... we can't do it after the
108 // call
109 switch (lua_pcall(L, 0, 0, 0)) {
110 case LUA_ERRRUN:
111 Log::err("Script::run", lua_tostring(L, -1));
112 break;
113 case LUA_ERRMEM:
114 // Should we even bother with this?
115 Log::err("Script::run", "Lua: out of memory");
116 break;
117 case LUA_ERRERR:
118 Log::err("Script::run", "error in Lua error facility"
119 "... what did you do!?");
120 break;