Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

119 rader
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. #if defined HAVE_CONFIG_H
  11. # include "config.h"
  12. #endif
  13. #include <cstring>
  14. #include <cstdlib>
  15. #include <ctype.h>
  16. #include "core.h"
  17. #include "lua/lua.hpp"
  18. namespace lol
  19. {
  20. /*
  21. * World implementation class
  22. */
  23. class WorldData
  24. {
  25. friend class World;
  26. static int LuaPanic(lua_State* L)
  27. {
  28. char const *message = lua_tostring(L, -1);
  29. Log::Error("%s\n", message);
  30. DebugAbort();
  31. return 0;
  32. }
  33. static int LuaDoFile(lua_State *L)
  34. {
  35. if (lua_isnoneornil(L, 1))
  36. return LUA_ERRFILE;
  37. char const *filename = lua_tostring(L, 1);
  38. int status = LUA_ERRFILE;
  39. Array<String> pathlist = System::GetPathList(filename);
  40. File f;
  41. for (int i = 0; i < pathlist.Count(); ++i)
  42. {
  43. f.Open(pathlist[i], FileAccess::Read);
  44. if (f.IsValid())
  45. {
  46. String s = f.ReadString();
  47. f.Close();
  48. Log::Debug("loading Lua file %s\n", pathlist[i].C());
  49. status = luaL_dostring(L, s.C());
  50. break;
  51. }
  52. }
  53. if (status == LUA_ERRFILE)
  54. Log::Error("could not find Lua file %s\n", filename);
  55. lua_pop(L, 1);
  56. return status;
  57. }
  58. lua_State *m_lua_state;
  59. };
  60. static WorldData g_world_data;
  61. World g_world;
  62. /*
  63. * Public World class
  64. */
  65. World::World()
  66. {
  67. /* Initialise the Lua engine */
  68. g_world_data.m_lua_state = luaL_newstate();
  69. lua_atpanic(g_world_data.m_lua_state, WorldData::LuaPanic);
  70. luaL_openlibs(g_world_data.m_lua_state);
  71. /* Override dofile() */
  72. lua_pushcfunction(g_world_data.m_lua_state, WorldData::LuaDoFile);
  73. lua_setglobal(g_world_data.m_lua_state, "dofile");
  74. }
  75. World::~World()
  76. {
  77. lua_close(g_world_data.m_lua_state);
  78. }
  79. bool World::ExecLua(String const &lua)
  80. {
  81. lua_pushstring(g_world_data.m_lua_state, lua.C());
  82. int status = WorldData::LuaDoFile(g_world_data.m_lua_state);
  83. return status == 0;
  84. }
  85. double World::GetLuaNumber(String const &var)
  86. {
  87. double ret;
  88. lua_getglobal(g_world_data.m_lua_state, var.C());
  89. ret = lua_tonumber(g_world_data.m_lua_state, -1);
  90. lua_pop(g_world_data.m_lua_state, 1);
  91. return ret;
  92. }
  93. } /* namespace lol */