Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

115 linhas
2.5 KiB

  1. //
  2. // Lol Engine
  3. //
  4. // Copyright: (c) 2010-2013 Sam Hocevar <sam@hocevar.net>
  5. // This program is free software; you can redistribute it and/or
  6. // modify it under the terms of the Do What The Fuck You Want To
  7. // Public License, Version 2, as published by Sam Hocevar. See
  8. // http://www.wtfpl.net/ for more details.
  9. //
  10. #include <lol/engine-internal.h>
  11. #include <cstring>
  12. #include <cstdlib>
  13. #include <ctype.h>
  14. #include "lua/lua.hpp"
  15. namespace lol
  16. {
  17. /*
  18. * World implementation class
  19. */
  20. class WorldData
  21. {
  22. friend class World;
  23. static int LuaPanic(lua_State* L)
  24. {
  25. char const *message = lua_tostring(L, -1);
  26. Log::Error("%s\n", message);
  27. DebugAbort();
  28. return 0;
  29. }
  30. static int LuaDoFile(lua_State *L)
  31. {
  32. if (lua_isnoneornil(L, 1))
  33. return LUA_ERRFILE;
  34. char const *filename = lua_tostring(L, 1);
  35. int status = LUA_ERRFILE;
  36. array<String> pathlist = System::GetPathList(filename);
  37. File f;
  38. for (int i = 0; i < pathlist.Count(); ++i)
  39. {
  40. f.Open(pathlist[i], FileAccess::Read);
  41. if (f.IsValid())
  42. {
  43. String s = f.ReadString();
  44. f.Close();
  45. Log::Debug("loading Lua file %s\n", pathlist[i].C());
  46. status = luaL_dostring(L, s.C());
  47. break;
  48. }
  49. }
  50. if (status == LUA_ERRFILE)
  51. Log::Error("could not find Lua file %s\n", filename);
  52. lua_pop(L, 1);
  53. return status;
  54. }
  55. lua_State *m_lua_state;
  56. };
  57. static WorldData g_world_data;
  58. World g_world;
  59. /*
  60. * Public World class
  61. */
  62. World::World()
  63. {
  64. /* Initialise the Lua engine */
  65. g_world_data.m_lua_state = luaL_newstate();
  66. lua_atpanic(g_world_data.m_lua_state, WorldData::LuaPanic);
  67. luaL_openlibs(g_world_data.m_lua_state);
  68. /* Override dofile() */
  69. lua_pushcfunction(g_world_data.m_lua_state, WorldData::LuaDoFile);
  70. lua_setglobal(g_world_data.m_lua_state, "dofile");
  71. }
  72. World::~World()
  73. {
  74. lua_close(g_world_data.m_lua_state);
  75. }
  76. bool World::ExecLua(String const &lua)
  77. {
  78. lua_pushstring(g_world_data.m_lua_state, lua.C());
  79. int status = WorldData::LuaDoFile(g_world_data.m_lua_state);
  80. return status == 0;
  81. }
  82. double World::GetLuaNumber(String const &var)
  83. {
  84. double ret;
  85. lua_getglobal(g_world_data.m_lua_state, var.C());
  86. ret = lua_tonumber(g_world_data.m_lua_state, -1);
  87. lua_pop(g_world_data.m_lua_state, 1);
  88. return ret;
  89. }
  90. } /* namespace lol */