Changed how userdata is handled

This commit is contained in:
2021-02-25 14:09:16 -05:00
parent 5f783e643b
commit 6405c34938
9 changed files with 88 additions and 167 deletions

View File

@@ -8,57 +8,6 @@ LuaNilMarker LuaNil;
LuaNewTableMarker LuaNewTable;
LuaDiscardMarker LuaDiscard;
void LuaStack::clear_tagged_pointer(LuaSlot target) {
TaggedPointer *tp = (TaggedPointer*)lua_touserdata(L_, target.index());
tp->ptr = 0;
}
void LuaStack::make_tagged_pointer(LuaSlot target, void *ptr, LuaTypeTag tag, LuaDeleterFn del) {
TaggedPointer *tp = (TaggedPointer*)lua_newuserdata(L_, sizeof(TaggedPointer));
tp->ptr = ptr;
tp->tag = tag;
tp->del = del;
lua_pushlightuserdata(L_, (void*)tag);
lua_rawget(L_, LUA_REGISTRYINDEX);
if (lua_isnil(L_, -1)) luaL_error(L_, "type not registered with LuaDefineType");
lua_setmetatable(L_, -2);
lua_replace(L_, target);
}
int LuaStack::collect_tagged_pointer(lua_State *L) {
TaggedPointer *p = (TaggedPointer*)lua_touserdata(L, 1);
if (p==0) {
luaL_error(L, "lua deleter function received a non-userdata");
}
if (p->ptr != 0) {
p->del(p->ptr);
p->ptr = 0;
}
return 0;
}
void LuaStack::register_all_userdata(lua_State *L) {
LuaVar tab, lud, classtab, classname;
LuaStack LS(L, tab, lud, classtab, classname);
auto regs = LuaFunctionReg::all();
for (const LuaFunctionReg *r : regs) {
const std::string &name = util::tolower(r->get_name());
lua_CFunction tag = r->get_func();
std::string mode = r->get_mode();
LS.set(classname, name);
if (mode.find('t') != std::string::npos) { // Register type
LS.newtable(tab);
LS.rawset(tab, "type", name);
LS.rawset(tab, "__gc", collect_tagged_pointer);
LS.makeclass(classtab, classname);
LS.rawset(tab, "__index", classtab);
LS.setlightuserdata(lud, (void *)tag);
LS.rawset(LuaRegistry, lud, tab);
}
}
LS.result();
}
LuaFunctionReg::LuaFunctionReg(const char *m, const char *n, lua_CFunction f) {
mode_ = m;
name_ = n;
@@ -251,18 +200,3 @@ void LuaStack::check_nret(int xnret, int otop, int nret) const {
luaL_error(L_, "expected %d return values", xnret);
}
}
LuaDefine(system_type, "f") {
LuaArg obj;
LuaRet tname;
LuaVar mt;
LuaStack LS(L, obj, tname, mt);
int type = LS.type(obj);
if (type == LUA_TUSERDATA) {
LS.getmetatable(mt, obj);
LS.rawget(tname, mt, "type");
} else {
LS.set(tname, lua_typename(L, type));
}
return LS.result();
}