From b892f0a8774f573d7ec9b02617428871b8d3a2b3 Mon Sep 17 00:00:00 2001 From: Roberto Ierusalimschy Date: Thu, 26 Oct 2000 10:47:05 -0200 Subject: new API function `createuserdata' --- liolib.c | 30 +++++++++--------------------- 1 file changed, 9 insertions(+), 21 deletions(-) (limited to 'liolib.c') diff --git a/liolib.c b/liolib.c index 0e58a942..b1fddebe 100644 --- a/liolib.c +++ b/liolib.c @@ -1,5 +1,5 @@ /* -** $Id: liolib.c,v 1.86 2000/10/02 20:10:55 roberto Exp roberto $ +** $Id: liolib.c,v 1.87 2000/10/20 16:39:03 roberto Exp roberto $ ** Standard I/O (and system) library ** See Copyright Notice in lua.h */ @@ -159,18 +159,9 @@ static int io_close (lua_State *L) { static int file_collect (lua_State *L) { IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1); - lua_pop(L, 1); /* remove upvalue */ - if (ctrl == (IOCtrl *)lua_touserdata(L, 1)) { - /* collecting `ctrl' itself */ - lua_unref(L, ctrl->ref[INFILE]); - lua_unref(L, ctrl->ref[OUTFILE]); - free(ctrl); - } - else { /* collecting a file: Close it */ - FILE *f = getnonullfile(L, ctrl, 1); - if (f != stdin && f != stdout && f != stderr) - CLOSEFILE(L, f); - } + FILE *f = getnonullfile(L, ctrl, 1); + if (f != stdin && f != stdout && f != stderr) + CLOSEFILE(L, f); return 0; } @@ -690,14 +681,13 @@ static const struct luaL_reg iolibtag[] = { static void openwithcontrol (lua_State *L) { - IOCtrl *ctrl = (IOCtrl *)malloc(sizeof(IOCtrl)); + IOCtrl *ctrl = (IOCtrl *)lua_newuserdata(L, sizeof(IOCtrl)); unsigned int i; - int ctrltag = lua_newtag(L); ctrl->iotag = lua_newtag(L); ctrl->closedtag = lua_newtag(L); for (i=0; iiotag, ctrltag); + lua_pushcclosure(L, file_collect, 1); /* pops `ctrl' from stack */ + lua_settagmethod(L, ctrl->iotag, "gc"); + lua_pop(L, 1); /* remove tag method returned by previous call */ } -- cgit v1.2.3-55-g6feb