2013-11-14 22:41:54 +00:00
|
|
|
/*
|
|
|
|
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
|
|
|
|
Released under Apache 2.0 license as described in the file LICENSE.
|
|
|
|
|
|
|
|
Author: Leonardo de Moura
|
|
|
|
*/
|
2013-11-27 03:15:49 +00:00
|
|
|
#include "util/luaref.h"
|
2013-11-14 22:41:54 +00:00
|
|
|
#include "util/debug.h"
|
|
|
|
|
|
|
|
namespace lean {
|
2013-11-27 03:15:49 +00:00
|
|
|
luaref::luaref(lua_State * L, int i) {
|
2013-11-14 22:41:54 +00:00
|
|
|
lean_assert(L);
|
|
|
|
m_state = L;
|
|
|
|
lua_pushvalue(m_state, i);
|
|
|
|
m_ref = luaL_ref(m_state, LUA_REGISTRYINDEX);
|
|
|
|
}
|
|
|
|
|
2013-11-27 03:15:49 +00:00
|
|
|
luaref::luaref(luaref const & r) {
|
2013-11-14 22:41:54 +00:00
|
|
|
m_state = r.m_state;
|
|
|
|
if (m_state) {
|
|
|
|
r.push();
|
|
|
|
m_ref = luaL_ref(m_state, LUA_REGISTRYINDEX);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-11-27 03:15:49 +00:00
|
|
|
luaref::luaref(luaref && r) {
|
2013-11-14 22:41:54 +00:00
|
|
|
m_state = r.m_state;
|
|
|
|
m_ref = r.m_ref;
|
|
|
|
r.m_state = nullptr;
|
|
|
|
}
|
|
|
|
|
2013-11-27 03:15:49 +00:00
|
|
|
luaref::~luaref() {
|
2013-11-14 22:41:54 +00:00
|
|
|
if (m_state)
|
|
|
|
luaL_unref(m_state, LUA_REGISTRYINDEX, m_ref);
|
|
|
|
}
|
|
|
|
|
2013-11-28 21:09:30 +00:00
|
|
|
void luaref::release() {
|
|
|
|
if (m_state) {
|
|
|
|
luaL_unref(m_state, LUA_REGISTRYINDEX, m_ref);
|
|
|
|
m_state = nullptr;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-11-27 03:15:49 +00:00
|
|
|
luaref & luaref::operator=(luaref const & r) {
|
2013-11-30 08:34:38 +00:00
|
|
|
if (m_state != nullptr && r.m_state != nullptr && m_ref == r.m_ref)
|
2013-11-14 22:41:54 +00:00
|
|
|
return *this;
|
|
|
|
if (m_state)
|
|
|
|
luaL_unref(m_state, LUA_REGISTRYINDEX, m_ref);
|
|
|
|
m_state = r.m_state;
|
|
|
|
if (m_state) {
|
|
|
|
r.push();
|
|
|
|
m_ref = luaL_ref(m_state, LUA_REGISTRYINDEX);
|
|
|
|
}
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2013-11-27 03:15:49 +00:00
|
|
|
void luaref::push() const {
|
2013-11-14 22:41:54 +00:00
|
|
|
lean_assert(m_state);
|
|
|
|
lua_rawgeti(m_state, LUA_REGISTRYINDEX, m_ref);
|
|
|
|
}
|
|
|
|
|
2013-11-27 03:15:49 +00:00
|
|
|
int luaref_lt_proc::operator()(luaref const & r1, luaref const & r2) const {
|
2013-11-14 22:41:54 +00:00
|
|
|
lean_assert(r1.get_state() == r2.get_state());
|
|
|
|
lua_State * L = r1.get_state();
|
|
|
|
r1.push();
|
|
|
|
r2.push();
|
|
|
|
int r;
|
|
|
|
if (lessthan(L, -2, -1)) {
|
|
|
|
r = -1;
|
|
|
|
} else if (lessthan(L, -1, -2)) {
|
|
|
|
r = 1;
|
|
|
|
} else if (equal(L, -2, -1)) {
|
|
|
|
r = 0;
|
|
|
|
} else {
|
|
|
|
throw exception("'<' is not a total order for the elements inserted on the table");
|
|
|
|
}
|
|
|
|
lua_pop(L, 2);
|
|
|
|
return r;
|
|
|
|
}
|
|
|
|
}
|