浏览代码

files are closed when collected (again)

Roberto Ierusalimschy 25 年之前
父节点
当前提交
f63d7753b8
共有 1 个文件被更改,包括 14 次插入2 次删除
  1. 14 2
      liolib.c

+ 14 - 2
liolib.c

@@ -1,5 +1,5 @@
 /*
 /*
-** $Id: liolib.c,v 1.64 2000/05/24 13:54:49 roberto Exp roberto $
+** $Id: liolib.c,v 1.65 2000/05/26 19:17:57 roberto Exp roberto $
 ** Standard I/O (and system) library
 ** Standard I/O (and system) library
 ** See Copyright Notice in lua.h
 ** See Copyright Notice in lua.h
 */
 */
@@ -160,7 +160,7 @@ static void setreturn (lua_State *L, IOCtrl *ctrl, FILE *f, int inout) {
 
 
 
 
 static int closefile (lua_State *L, IOCtrl *ctrl, FILE *f) {
 static int closefile (lua_State *L, IOCtrl *ctrl, FILE *f) {
-  if (f == stdin || f == stdout)
+  if (f == stdin || f == stdout || f == stderr)
     return 1;
     return 1;
   else {
   else {
     if (f == ctrl->file[INFILE])
     if (f == ctrl->file[INFILE])
@@ -180,6 +180,14 @@ static void io_close (lua_State *L) {
 }
 }
 
 
 
 
+static void file_collect (lua_State *L) {
+  IOCtrl *ctrl = (IOCtrl *)lua_getuserdata(L, lua_getparam(L, 1));
+  FILE *f = getnonullfile(L, ctrl, 2);
+  if (f != stdin && f != stdout && f != stderr)
+    CLOSEFILE(L, f);
+}
+
+
 static void io_open (lua_State *L) {
 static void io_open (lua_State *L) {
   IOCtrl *ctrl = (IOCtrl *)lua_getuserdata(L, lua_getparam(L, 1));
   IOCtrl *ctrl = (IOCtrl *)lua_getuserdata(L, lua_getparam(L, 1));
   FILE *f = fopen(luaL_check_string(L, 2), luaL_check_string(L, 3));
   FILE *f = fopen(luaL_check_string(L, 2), luaL_check_string(L, 3));
@@ -649,6 +657,10 @@ static void openwithcontrol (lua_State *L) {
   lua_pushusertag(L, ctrl, ctrltag);
   lua_pushusertag(L, ctrl, ctrltag);
   lua_pushcclosure(L, ctrl_collect, 1); 
   lua_pushcclosure(L, ctrl_collect, 1); 
   lua_settagmethod(L, ctrltag, "gc");
   lua_settagmethod(L, ctrltag, "gc");
+  /* close files when collected */
+  lua_pushusertag(L, ctrl, ctrltag);
+  lua_pushcclosure(L, file_collect, 1); 
+  lua_settagmethod(L, ctrl->iotag, "gc");
 }
 }
 
 
 void lua_iolibopen (lua_State *L) {
 void lua_iolibopen (lua_State *L) {