lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi all,

Sorry if this has been answered before but why can't I set the 'gc' tag
method from inside a lua program? I need to call a 'destructor' method
whenever an instance of my class system is destroyed.

I know I can do it in C but why should I do

-----cut-----
static int destructor(lua_State *L) { // instance
	lua_pushstring(L,"destructor"); // instance 'destructor'
	lua_gettable(L,-1);             // instance destructor_function
	if (lua_isfunction(L,-1)) {
		lua_pushvalue(L,-2);      // instance destructor_function
instance
		lua_call(L,1,0);          // instance
	}
	return 0;
}

int main() {
	...
	instancetag = lua_newtag(L);
	lua_pushcfunction(L,destructor);
	settagmethod(L, instancetag, "gc");
	...
}
-----cut-----

instead of just

-----cut-----
function destructor(instance)
	if type(instance.destructor)=='function' then
		instance:destructor()
	end
end

instancetag=newtag()
settagmethod(instancetag, 'gc', destructor)
-----cut-----

? I'm using lua 4.0.

Thanks,

André de Leiradella