LuaScript.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "EngineEvents.h"
  25. #include "File.h"
  26. #include "Log.h"
  27. #include "Profiler.h"
  28. #include "LuaScript.h"
  29. #include "ResourceCache.h"
  30. #include "Scene.h"
  31. extern "C"
  32. {
  33. #include <lua.h>
  34. #include <lualib.h>
  35. #include <lauxlib.h>
  36. }
  37. #include "tolua++.h"
  38. #include "DebugNew.h"
  39. extern int tolua_Audio_open(lua_State*);
  40. extern int tolua_Container_open(lua_State*);
  41. extern int tolua_Core_open(lua_State*);
  42. extern int tolua_Engine_open(lua_State*);
  43. extern int tolua_Graphics_open(lua_State*);
  44. extern int tolua_Input_open(lua_State*);
  45. extern int tolua_IO_open(lua_State*);
  46. extern int tolua_Math_open(lua_State*);
  47. extern int tolua_Navigation_open(lua_State*);
  48. extern int tolua_Network_open(lua_State*);
  49. extern int tolua_Physics_open(lua_State*);
  50. extern int tolua_Resource_open(lua_State*);
  51. extern int tolua_Scene_open(lua_State*);
  52. extern int tolua_UI_open(lua_State*);
  53. extern int tolua_LuaScript_open(lua_State*);
  54. namespace Urho3D
  55. {
  56. OBJECTTYPESTATIC(LuaScript);
  57. static Context* scriptContext_ = 0;
  58. LuaScript::LuaScript(Context* context) :
  59. Object(context),
  60. luaState_(0)
  61. {
  62. scriptContext_ = context_;
  63. luaState_ = luaL_newstate();
  64. if (!luaState_)
  65. {
  66. LOGERROR("Could not create Lua state");
  67. return;
  68. }
  69. luaL_openlibs(luaState_);
  70. ReplacePrintFunction();
  71. tolua_Audio_open(luaState_);
  72. tolua_Container_open(luaState_);
  73. tolua_Core_open(luaState_);
  74. tolua_Engine_open(luaState_);
  75. tolua_Graphics_open(luaState_);
  76. tolua_Input_open(luaState_);
  77. tolua_IO_open(luaState_);
  78. tolua_Math_open(luaState_);
  79. tolua_Navigation_open(luaState_);
  80. tolua_Network_open(luaState_);
  81. tolua_Physics_open(luaState_);
  82. tolua_Resource_open(luaState_);
  83. tolua_Scene_open(luaState_);
  84. tolua_UI_open(luaState_);
  85. tolua_LuaScript_open(luaState_);
  86. // Subscribe to console commands
  87. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(LuaScript, HandleConsoleCommand));
  88. }
  89. LuaScript::~LuaScript()
  90. {
  91. lua_close(luaState_);
  92. }
  93. bool LuaScript::ExecuteFile(const char* fileName)
  94. {
  95. if (!fileName)
  96. return false;
  97. PROFILE(ExecuteFile);
  98. ResourceCache* cache = GetSubsystem<ResourceCache>();
  99. if (!cache)
  100. return false;
  101. SharedPtr<File> file = cache->GetFile(fileName);
  102. if (!file)
  103. return false;
  104. unsigned size = file->GetSize();
  105. char* buffer = new char[size];
  106. file->Read(buffer, size);
  107. int top = lua_gettop(luaState_);
  108. int error = luaL_loadbuffer(luaState_, buffer, size, fileName);
  109. delete [] buffer;
  110. if (error)
  111. {
  112. String message = lua_tostring(luaState_, -1);
  113. lua_settop(luaState_, top);
  114. LOGRAW(String("Lua: Unable to execute Lua file '") + fileName + "'. ");
  115. LOGRAW("Lua: " + message);
  116. return false;
  117. }
  118. if (lua_pcall(luaState_, 0, 0, 0))
  119. {
  120. String message = lua_tostring(luaState_, -1);
  121. lua_settop(luaState_, top);
  122. LOGRAW(String("Lua: Unable to execute Lua script file '") + fileName + "'.");
  123. LOGRAW("Lua: " + message);
  124. return false;
  125. }
  126. lua_settop(luaState_, top);
  127. return true;
  128. }
  129. bool LuaScript::ExecuteString(const char* string)
  130. {
  131. if (string == 0)
  132. return false;
  133. PROFILE(ExecuteString);
  134. int top = lua_gettop(luaState_);
  135. if (luaL_dostring(luaState_, string) != 0)
  136. {
  137. String message = lua_tostring(luaState_, -1);
  138. lua_settop(luaState_, top);
  139. LOGRAW(String("Lua: Unable to execute Lua string '") + string + "'.");
  140. LOGRAW("Lua: " + message);
  141. return false;
  142. }
  143. lua_settop(luaState_, top);
  144. return true;
  145. }
  146. bool LuaScript::ExecuteFunction(const char* funcName)
  147. {
  148. if (funcName == 0)
  149. return false;
  150. PROFILE(ExecuteFunction);
  151. int top = lua_gettop(luaState_);
  152. lua_getglobal(luaState_, funcName);
  153. if (!lua_isfunction(luaState_, -1))
  154. {
  155. lua_settop(luaState_, top);
  156. LOGRAW(String("Lua: Unable to get lua global: '") + funcName + "'.");
  157. return false;
  158. }
  159. if (lua_pcall(luaState_, 0, 0, 0))
  160. {
  161. String message = lua_tostring(luaState_, -1);
  162. lua_settop(luaState_, top);
  163. LOGRAW(String("Lua: Unable to execute function '") + funcName + "'.");
  164. LOGRAW("Lua: " + message);
  165. return false;
  166. }
  167. return true;
  168. }
  169. void LuaScript::SetDefaultScene( Scene* scene )
  170. {
  171. defaultScene_ = scene;
  172. }
  173. Scene* LuaScript::GetDefaultScene() const
  174. {
  175. return defaultScene_;
  176. }
  177. void LuaScript::SubscribeLuaEvent(const char* event, const char* funcName)
  178. {
  179. StringHash eventType(event);
  180. eventFunctionMap_[eventType].Push(String(funcName));
  181. SubscribeToEvent(eventType, HANDLER(LuaScript, HandleEvent));
  182. }
  183. void LuaScript::ReplacePrintFunction()
  184. {
  185. static const struct luaL_reg printlib[] =
  186. {
  187. {"print", &LuaScript::Print},
  188. { NULL, NULL}
  189. };
  190. lua_getglobal(luaState_, "_G");
  191. luaL_register(luaState_, NULL, printlib);
  192. lua_pop(luaState_, 1);
  193. }
  194. int LuaScript::Print(lua_State *L)
  195. {
  196. String string;
  197. int n = lua_gettop(L);
  198. lua_getglobal(L, "tostring");
  199. for (int i = 1; i <= n; i++)
  200. {
  201. const char *s;
  202. lua_pushvalue(L, -1); /* function to be called */
  203. lua_pushvalue(L, i); /* value to print */
  204. lua_call(L, 1, 1);
  205. s = lua_tostring(L, -1); /* get result */
  206. if (s == NULL)
  207. return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print"));
  208. if (i > 1)
  209. string.Append(" "); // fputs("\t", stdout);
  210. string.Append(s); // fputs(s, stdout);
  211. lua_pop(L, 1); /* pop result */
  212. }
  213. LOGRAW(String("Lua: ") + string); // fputs("\n", stdout);
  214. return 0;
  215. }
  216. int LuaScript::PCallCallback(lua_State* L)
  217. {
  218. String message = lua_tostring(L, -1);
  219. LOGRAW("Lua pcall error: " + message);
  220. return 0;
  221. }
  222. void LuaScript::HandleEvent(StringHash eventType, VariantMap& eventData)
  223. {
  224. HashMap<StringHash, Vector<String> >::ConstIterator it = eventFunctionMap_.Find(eventType);
  225. if (it == eventFunctionMap_.End())
  226. return;
  227. for (unsigned i = 0; i < it->second_.Size(); ++i)
  228. {
  229. const String& funcName = it->second_[i];
  230. int top = lua_gettop(luaState_);
  231. lua_getglobal(luaState_, funcName.CString());
  232. if (!lua_isfunction(luaState_, -1))
  233. {
  234. lua_settop(luaState_, top);
  235. LOGRAW(String("Lua: Unable to get lua global: '") + funcName + "'.");
  236. return;
  237. }
  238. tolua_pushusertype(luaState_, (void*)&eventType, "StringHash");
  239. tolua_pushusertype(luaState_, (void*)&eventData, "VariantMap");
  240. if (lua_pcall(luaState_, 2, 0, 0))
  241. {
  242. String message = lua_tostring(luaState_, -1);
  243. lua_settop(luaState_, top);
  244. LOGRAW(String("Lua: Unable to execute function '") + funcName + "'.");
  245. LOGRAW("Lua: " + message);
  246. return;
  247. }
  248. }
  249. }
  250. void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  251. {
  252. using namespace ConsoleCommand;
  253. ExecuteString(eventData[P_COMMAND].GetString().CString());
  254. }
  255. Context* GetLuaScriptContext()
  256. {
  257. return scriptContext_;
  258. }
  259. void SubscribeToEvent(const char* eventType, const char* funcName)
  260. {
  261. LuaScript* luaScript = scriptContext_->GetSubsystem<LuaScript>();
  262. luaScript->SubscribeLuaEvent(eventType, funcName);
  263. }
  264. }