2
0

LuaElementInstancer.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "LuaElementInstancer.h"
  2. #include <RmlUi/Core/Log.h>
  3. #include <RmlUi/Core/Platform.h>
  4. #include <RmlUi/Lua/Interpreter.h>
  5. #include <RmlUi/Lua/LuaType.h>
  6. namespace Rml {
  7. namespace Lua {
  8. // This will be called from ElementInstancernew
  9. LuaElementInstancer::LuaElementInstancer(lua_State* L) : ElementInstancer(), ref_InstanceElement(LUA_NOREF)
  10. {
  11. if (lua_type(L, 1) != LUA_TFUNCTION && !lua_isnoneornil(L, 1))
  12. {
  13. Log::Message(Log::LT_ERROR, "The argument to ElementInstancer.new has to be a function or nil. You passed in a %s.", luaL_typename(L, 1));
  14. return;
  15. }
  16. PushFunctionsTable(L); // top of the table is now ELEMENTINSTANCERFUNCTIONS table
  17. lua_pushvalue(L, 1); // copy of the function
  18. ref_InstanceElement = luaL_ref(L, -2);
  19. lua_pop(L, 1); // pop the ELEMENTINSTANCERFUNCTIONS table
  20. }
  21. ElementPtr LuaElementInstancer::InstanceElement(Element* /*parent*/, const String& tag, const XMLAttributes& /*attributes*/)
  22. {
  23. lua_State* L = Interpreter::GetLuaState();
  24. int top = lua_gettop(L);
  25. ElementPtr ret = nullptr;
  26. if (ref_InstanceElement != LUA_REFNIL && ref_InstanceElement != LUA_NOREF)
  27. {
  28. PushFunctionsTable(L);
  29. lua_rawgeti(L, -1, ref_InstanceElement); // push the function
  30. lua_pushstring(L, tag.c_str()); // push the tag
  31. Interpreter::ExecuteCall(1, 1); // we pass in a string, and we want to get an Element back
  32. ret = std::move(*LuaType<ElementPtr>::check(L, -1));
  33. }
  34. else
  35. {
  36. Log::Message(Log::LT_WARNING, "Attempt to call the function for ElementInstancer.InstanceElement, the function does not exist.");
  37. }
  38. lua_settop(L, top);
  39. return ret;
  40. }
  41. void LuaElementInstancer::ReleaseElement(Element* element)
  42. {
  43. delete element;
  44. }
  45. void LuaElementInstancer::PushFunctionsTable(lua_State* L)
  46. {
  47. // make sure there is an area to save the function
  48. lua_getglobal(L, "ELEMENTINSTANCERFUNCTIONS");
  49. if (lua_isnoneornil(L, -1))
  50. {
  51. lua_newtable(L);
  52. lua_setglobal(L, "ELEMENTINSTANCERFUNCTIONS");
  53. lua_pop(L, 1); // pop the unsucessful getglobal
  54. lua_getglobal(L, "ELEMENTINSTANCERFUNCTIONS");
  55. }
  56. }
  57. } // namespace Lua
  58. } // namespace Rml