1/**
2 * Copyright (c) 2006-2023 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
21#include "Reference.h"
22#include "runtime.h"
23
24namespace love
25{
26
27const char REFERENCE_TABLE_NAME[] = "love-references";
28
29Reference::Reference()
30 : pinnedL(nullptr)
31 , idx(LUA_REFNIL)
32{
33}
34
35Reference::Reference(lua_State *L)
36 : pinnedL(nullptr)
37 , idx(LUA_REFNIL)
38{
39 ref(L);
40}
41
42Reference::~Reference()
43{
44 unref();
45}
46
47void Reference::ref(lua_State *L)
48{
49 unref(); // Previously created reference needs to be cleared
50 pinnedL = luax_getpinnedthread(L);
51 luax_insist(L, LUA_REGISTRYINDEX, REFERENCE_TABLE_NAME);
52 lua_insert(L, -2); // Move reference table behind value.
53 idx = luaL_ref(L, -2);
54 lua_pop(L, 1);
55}
56
57void Reference::unref()
58{
59 if (idx != LUA_REFNIL)
60 {
61 // We use a pinned thread/coroutine for the Lua state because we know it
62 // hasn't been garbage collected and is valid, as long as the whole lua
63 // state is still open.
64 luax_insist(pinnedL, LUA_REGISTRYINDEX, REFERENCE_TABLE_NAME);
65 luaL_unref(pinnedL, -1, idx);
66 lua_pop(pinnedL, 1);
67 idx = LUA_REFNIL;
68 }
69}
70
71void Reference::push(lua_State *L)
72{
73 if (idx != LUA_REFNIL)
74 {
75 luax_insist(L, LUA_REGISTRYINDEX, REFERENCE_TABLE_NAME);
76 lua_rawgeti(L, -1, idx);
77 lua_remove(L, -2);
78 }
79 else
80 lua_pushnil(L);
81}
82
83} // love
84