LuaFile.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. // Copyright (c) 2008-2022 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Core/Context.h"
  5. #include "../IO/Deserializer.h"
  6. #include "../IO/FileSystem.h"
  7. #include "../IO/Log.h"
  8. #include "../LuaScript/LuaFile.h"
  9. #include "../Core/ProcessUtils.h"
  10. #include "../IO/Serializer.h"
  11. extern "C"
  12. {
  13. #include <lua.h>
  14. #include <lauxlib.h>
  15. }
  16. #include "../DebugNew.h"
  17. namespace Urho3D
  18. {
  19. LuaFile::LuaFile(Context* context) :
  20. Resource(context),
  21. size_(0),
  22. hasLoaded_(false),
  23. hasExecuted_(false)
  24. {
  25. }
  26. LuaFile::~LuaFile() = default;
  27. void LuaFile::RegisterObject(Context* context)
  28. {
  29. context->RegisterFactory<LuaFile>();
  30. }
  31. bool LuaFile::BeginLoad(Deserializer& source)
  32. {
  33. size_ = source.GetSize();
  34. if (size_ == 0)
  35. return false;
  36. // Read all data.
  37. data_ = new char[size_];
  38. if (source.Read(data_, size_) != size_)
  39. return false;
  40. SetMemoryUse(size_);
  41. return true;
  42. }
  43. bool LuaFile::Save(Serializer& dest) const
  44. {
  45. if (size_ == 0)
  46. return false;
  47. dest.Write(data_, size_);
  48. return true;
  49. }
  50. bool LuaFile::LoadChunk(lua_State* luaState)
  51. {
  52. if (hasLoaded_)
  53. return true;
  54. if (size_ == 0 || !luaState)
  55. return false;
  56. // Get file base name
  57. String name = GetName();
  58. i32 extPos = name.FindLast('.');
  59. if (extPos != String::NPOS)
  60. name = name.Substring(0, extPos);
  61. if (luaL_loadbuffer(luaState, data_, size_, name.CString()))
  62. {
  63. const char* message = lua_tostring(luaState, -1);
  64. URHO3D_LOGERRORF("Load Buffer failed for %s: %s", GetName().CString(), message);
  65. lua_pop(luaState, 1);
  66. return false;
  67. }
  68. URHO3D_LOGINFO("Loaded Lua script " + GetName());
  69. hasLoaded_ = true;
  70. return true;
  71. }
  72. bool LuaFile::LoadAndExecute(lua_State* luaState)
  73. {
  74. if (hasExecuted_)
  75. return true;
  76. if (!LoadChunk(luaState))
  77. return false;
  78. if (lua_pcall(luaState, 0, 0, 0))
  79. {
  80. const char* message = lua_tostring(luaState, -1);
  81. URHO3D_LOGERRORF("Lua Execute failed for %s: %s", GetName().CString(), message);
  82. lua_pop(luaState, 1);
  83. return false;
  84. }
  85. URHO3D_LOGINFO("Executed Lua script " + GetName());
  86. hasExecuted_ = true;
  87. return true;
  88. }
  89. }