LuaScript.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 "EngineEvents.h"
  24. #include "File.h"
  25. #include "Log.h"
  26. #include "LuaScript.h"
  27. #include "Profiler.h"
  28. #include "ResourceCache.h"
  29. #include "Scene.h"
  30. extern "C"
  31. {
  32. #include <lua.h>
  33. #include <lualib.h>
  34. #include <lauxlib.h>
  35. }
  36. #include "tolua++.h"
  37. #include "DebugNew.h"
  38. extern int tolua_AudioLuaAPI_open(lua_State*);
  39. extern int tolua_ContainerLuaAPI_open(lua_State*);
  40. extern int tolua_CoreLuaAPI_open(lua_State*);
  41. extern int tolua_EngineLuaAPI_open(lua_State*);
  42. extern int tolua_GraphicsLuaAPI_open(lua_State*);
  43. extern int tolua_InputLuaAPI_open(lua_State*);
  44. extern int tolua_IOLuaAPI_open(lua_State*);
  45. extern int tolua_MathLuaAPI_open(lua_State*);
  46. extern int tolua_NavigationLuaAPI_open(lua_State*);
  47. extern int tolua_NetworkLuaAPI_open(lua_State*);
  48. extern int tolua_PhysicsLuaAPI_open(lua_State*);
  49. extern int tolua_ResourceLuaAPI_open(lua_State*);
  50. extern int tolua_SceneLuaAPI_open(lua_State*);
  51. extern int tolua_UILuaAPI_open(lua_State*);
  52. extern int tolua_LuaScriptLuaAPI_open(lua_State*);
  53. namespace Urho3D
  54. {
  55. static Context* scriptContext_ = 0;
  56. LuaScript::LuaScript(Context* context) :
  57. Object(context),
  58. luaState_(0)
  59. {
  60. scriptContext_ = context_;
  61. luaState_ = luaL_newstate();
  62. if (!luaState_)
  63. {
  64. LOGERROR("Could not create Lua state");
  65. return;
  66. }
  67. luaL_openlibs(luaState_);
  68. ReplacePrintFunction();
  69. tolua_AudioLuaAPI_open(luaState_);
  70. tolua_ContainerLuaAPI_open(luaState_);
  71. tolua_CoreLuaAPI_open(luaState_);
  72. tolua_EngineLuaAPI_open(luaState_);
  73. tolua_GraphicsLuaAPI_open(luaState_);
  74. tolua_InputLuaAPI_open(luaState_);
  75. tolua_IOLuaAPI_open(luaState_);
  76. tolua_MathLuaAPI_open(luaState_);
  77. tolua_NavigationLuaAPI_open(luaState_);
  78. tolua_NetworkLuaAPI_open(luaState_);
  79. tolua_PhysicsLuaAPI_open(luaState_);
  80. tolua_ResourceLuaAPI_open(luaState_);
  81. tolua_SceneLuaAPI_open(luaState_);
  82. tolua_UILuaAPI_open(luaState_);
  83. tolua_LuaScriptLuaAPI_open(luaState_);
  84. // Subscribe to console commands
  85. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(LuaScript, HandleConsoleCommand));
  86. }
  87. LuaScript::~LuaScript()
  88. {
  89. lua_close(luaState_);
  90. }
  91. bool LuaScript::ExecuteFile(const char* fileName)
  92. {
  93. if (!fileName)
  94. return false;
  95. PROFILE(ExecuteFile);
  96. ResourceCache* cache = GetSubsystem<ResourceCache>();
  97. if (!cache)
  98. return false;
  99. SharedPtr<File> file = cache->GetFile(fileName);
  100. if (!file)
  101. return false;
  102. unsigned size = file->GetSize();
  103. char* buffer = new char[size];
  104. file->Read(buffer, size);
  105. int top = lua_gettop(luaState_);
  106. int error = luaL_loadbuffer(luaState_, buffer, size, fileName);
  107. delete [] buffer;
  108. if (error)
  109. {
  110. const char* message = lua_tostring(luaState_, -1);
  111. lua_settop(luaState_, top);
  112. LOGRAW(String("Lua: Unable to execute Lua file '") + fileName + "'. ");
  113. LOGRAW(String("Lua: ") + message);
  114. return false;
  115. }
  116. if (lua_pcall(luaState_, 0, 0, 0))
  117. {
  118. const char* message = lua_tostring(luaState_, -1);
  119. lua_settop(luaState_, top);
  120. LOGRAW(String("Lua: Unable to execute Lua script file '") + fileName + "'.");
  121. LOGRAW(String("Lua: ") + message);
  122. return false;
  123. }
  124. lua_settop(luaState_, top);
  125. return true;
  126. }
  127. bool LuaScript::ExecuteString(const char* string)
  128. {
  129. if (string == 0)
  130. return false;
  131. PROFILE(ExecuteString);
  132. int top = lua_gettop(luaState_);
  133. if (luaL_dostring(luaState_, string) != 0)
  134. {
  135. const char* message = lua_tostring(luaState_, -1);
  136. lua_settop(luaState_, top);
  137. LOGRAW(String("Lua: Unable to execute Lua string '") + string + "'.");
  138. LOGRAW(String("Lua: ") + message);
  139. return false;
  140. }
  141. lua_settop(luaState_, top);
  142. return true;
  143. }
  144. bool LuaScript::ExecuteFunction(const char* funcName)
  145. {
  146. if (funcName == 0)
  147. return false;
  148. PROFILE(ExecuteFunction);
  149. int top = lua_gettop(luaState_);
  150. lua_getglobal(luaState_, funcName);
  151. if (!lua_isfunction(luaState_, -1))
  152. {
  153. lua_settop(luaState_, top);
  154. LOGRAW(String("Lua: Unable to get lua global: '") + funcName + "'.");
  155. return false;
  156. }
  157. if (lua_pcall(luaState_, 0, 0, 0))
  158. {
  159. const char* message = lua_tostring(luaState_, -1);
  160. lua_settop(luaState_, top);
  161. LOGRAW(String("Lua: Unable to execute function '") + funcName + "'.");
  162. LOGRAW(String("Lua: ") + message);
  163. return false;
  164. }
  165. return true;
  166. }
  167. void LuaScript::SubscribeLuaEvent(const char* event, const char* funcName)
  168. {
  169. StringHash eventType(event);
  170. eventFunctionMap_[eventType].Push(String(funcName));
  171. SubscribeToEvent(eventType, HANDLER(LuaScript, HandleEvent));
  172. }
  173. void LuaScript::ReplacePrintFunction()
  174. {
  175. static const struct luaL_reg printlib[] =
  176. {
  177. {"print", &LuaScript::Print},
  178. { NULL, NULL}
  179. };
  180. lua_getglobal(luaState_, "_G");
  181. luaL_register(luaState_, NULL, printlib);
  182. lua_pop(luaState_, 1);
  183. }
  184. int LuaScript::Print(lua_State *L)
  185. {
  186. String string;
  187. int n = lua_gettop(L);
  188. lua_getglobal(L, "tostring");
  189. for (int i = 1; i <= n; i++)
  190. {
  191. const char *s;
  192. lua_pushvalue(L, -1); /* function to be called */
  193. lua_pushvalue(L, i); /* value to print */
  194. lua_call(L, 1, 1);
  195. s = lua_tostring(L, -1); /* get result */
  196. if (s == NULL)
  197. return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print"));
  198. if (i > 1)
  199. string.Append(" "); // fputs("\t", stdout);
  200. string.Append(s); // fputs(s, stdout);
  201. lua_pop(L, 1); /* pop result */
  202. }
  203. LOGRAW(String("Lua: ") + string); // fputs("\n", stdout);
  204. return 0;
  205. }
  206. int LuaScript::PCallCallback(lua_State* L)
  207. {
  208. String message = lua_tostring(L, -1);
  209. LOGRAW("Lua pcall error: " + message);
  210. return 0;
  211. }
  212. void LuaScript::HandleEvent(StringHash eventType, VariantMap& eventData)
  213. {
  214. HashMap<StringHash, Vector<String> >::ConstIterator it = eventFunctionMap_.Find(eventType);
  215. if (it == eventFunctionMap_.End())
  216. return;
  217. for (unsigned i = 0; i < it->second_.Size(); ++i)
  218. {
  219. const String& funcName = it->second_[i];
  220. int top = lua_gettop(luaState_);
  221. lua_getglobal(luaState_, funcName.CString());
  222. if (!lua_isfunction(luaState_, -1))
  223. {
  224. lua_settop(luaState_, top);
  225. LOGRAW(String("Lua: Unable to get lua global: '") + funcName + "'.");
  226. return;
  227. }
  228. tolua_pushusertype(luaState_, (void*)&eventType, "StringHash");
  229. tolua_pushusertype(luaState_, (void*)&eventData, "VariantMap");
  230. if (lua_pcall(luaState_, 2, 0, 0))
  231. {
  232. String message = lua_tostring(luaState_, -1);
  233. lua_settop(luaState_, top);
  234. LOGRAW(String("Lua: Unable to execute function '") + funcName + "'.");
  235. LOGRAW("Lua: " + message);
  236. return;
  237. }
  238. }
  239. }
  240. void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  241. {
  242. using namespace ConsoleCommand;
  243. ExecuteString(eventData[P_COMMAND].GetString().CString());
  244. }
  245. Context* GetContext()
  246. {
  247. return scriptContext_;
  248. }
  249. void SendEvent(const char* eventType, VariantMap& eventData)
  250. {
  251. LuaScript* luaScript = scriptContext_->GetSubsystem<LuaScript>();
  252. luaScript->SendEvent(StringHash(eventType), eventData);
  253. }
  254. void SubscribeToEvent(const char* eventType, const char* funcName)
  255. {
  256. LuaScript* luaScript = scriptContext_->GetSubsystem<LuaScript>();
  257. luaScript->SubscribeLuaEvent(eventType, funcName);
  258. }
  259. }