Reference.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * Copyright (c) 2006-2019 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "Reference.h"
  21. #include "runtime.h"
  22. namespace love
  23. {
  24. const char REFERENCE_TABLE_NAME[] = "love-references";
  25. Reference::Reference()
  26. : pinnedL(nullptr)
  27. , idx(LUA_REFNIL)
  28. {
  29. }
  30. Reference::Reference(lua_State *L)
  31. : pinnedL(nullptr)
  32. , idx(LUA_REFNIL)
  33. {
  34. ref(L);
  35. }
  36. Reference::~Reference()
  37. {
  38. unref();
  39. }
  40. void Reference::ref(lua_State *L)
  41. {
  42. unref(); // Previously created reference needs to be cleared
  43. pinnedL = luax_getpinnedthread(L);
  44. luax_insist(L, LUA_REGISTRYINDEX, REFERENCE_TABLE_NAME);
  45. lua_insert(L, -2); // Move reference table behind value.
  46. idx = luaL_ref(L, -2);
  47. lua_pop(L, 1);
  48. }
  49. void Reference::unref()
  50. {
  51. if (idx != LUA_REFNIL)
  52. {
  53. // We use a pinned thread/coroutine for the Lua state because we know it
  54. // hasn't been garbage collected and is valid, as long as the whole lua
  55. // state is still open.
  56. luax_insist(pinnedL, LUA_REGISTRYINDEX, REFERENCE_TABLE_NAME);
  57. luaL_unref(pinnedL, -1, idx);
  58. lua_pop(pinnedL, 1);
  59. idx = LUA_REFNIL;
  60. }
  61. }
  62. void Reference::push(lua_State *L)
  63. {
  64. if (idx != LUA_REFNIL)
  65. {
  66. luax_insist(L, LUA_REGISTRYINDEX, REFERENCE_TABLE_NAME);
  67. lua_rawgeti(L, -1, idx);
  68. lua_remove(L, -2);
  69. }
  70. else
  71. lua_pushnil(L);
  72. }
  73. } // love