xref: /netbsd-src/external/mit/lua/dist/src/liolib.c (revision aad9773e38ed2370a628a6416e098f9008fc10a7)
1 /*	$NetBSD: liolib.c,v 1.2 2014/07/19 18:38:34 lneto Exp $	*/
2 
3 /*
4 ** $Id: liolib.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
5 ** Standard I/O (and system) library
6 ** See Copyright Notice in lua.h
7 */
8 
9 
10 /*
11 ** This definition must come before the inclusion of 'stdio.h'; it
12 ** should not affect non-POSIX systems
13 */
14 #if !defined(_FILE_OFFSET_BITS)
15 #define	_LARGEFILE_SOURCE	1
16 #define _FILE_OFFSET_BITS	64
17 #endif
18 
19 
20 #include <ctype.h>
21 #include <errno.h>
22 #include <locale.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 
27 #define liolib_c
28 #define LUA_LIB
29 
30 #include "lua.h"
31 
32 #include "lauxlib.h"
33 #include "lualib.h"
34 
35 
36 #if !defined(l_checkmode)
37 
38 /*
39 ** Check whether 'mode' matches '[rwa]%+?b?'.
40 ** Change this macro to accept other modes for 'fopen' besides
41 ** the standard ones.
42 */
43 #define l_checkmode(mode) \
44 	(*mode != '\0' && strchr("rwa", *(mode++)) != NULL &&	\
45 	(*mode != '+' || ++mode) &&  /* skip if char is '+' */	\
46 	(*mode != 'b' || ++mode) &&  /* skip if char is 'b' */	\
47 	(*mode == '\0'))
48 
49 #endif
50 
51 /*
52 ** {======================================================
53 ** l_popen spawns a new process connected to the current
54 ** one through the file streams.
55 ** =======================================================
56 */
57 
58 #if !defined(l_popen)		/* { */
59 
60 #if defined(LUA_USE_POSIX)	/* { */
61 
62 #define l_popen(L,c,m)		(fflush(NULL), popen(c,m))
63 #define l_pclose(L,file)	(pclose(file))
64 
65 #elif defined(LUA_WIN)		/* }{ */
66 
67 #define l_popen(L,c,m)		(_popen(c,m))
68 #define l_pclose(L,file)	(_pclose(file))
69 
70 #else				/* }{ */
71 
72 /* ANSI definitions */
73 #define l_popen(L,c,m)  \
74 	  ((void)((void)c, m), \
75 	  luaL_error(L, LUA_QL("popen") " not supported"), \
76 	  (FILE*)0)
77 #define l_pclose(L,file)		((void)L, (void)file, -1)
78 
79 #endif				/* } */
80 
81 #endif				/* } */
82 
83 /* }====================================================== */
84 
85 
86 #if !defined(l_getc)		/* { */
87 
88 #if defined(LUA_USE_POSIX)
89 #define l_getc(f)		getc_unlocked(f)
90 #define l_lockfile(f)		flockfile(f)
91 #define l_unlockfile(f)		funlockfile(f)
92 #else
93 #define l_getc(f)		getc(f)
94 #define l_lockfile(f)		((void)0)
95 #define l_unlockfile(f)		((void)0)
96 #endif
97 
98 #endif				/* } */
99 
100 
101 /*
102 ** {======================================================
103 ** l_fseek: configuration for longer offsets
104 ** =======================================================
105 */
106 
107 #if !defined(l_fseek)		/* { */
108 
109 #if defined(LUA_USE_POSIX)	/* { */
110 
111 #include <sys/types.h>
112 
113 #define l_fseek(f,o,w)		fseeko(f,o,w)
114 #define l_ftell(f)		ftello(f)
115 #define l_seeknum		off_t
116 
117 #elif defined(LUA_WIN) && !defined(_CRTIMP_TYPEINFO) \
118    && defined(_MSC_VER) && (_MSC_VER >= 1400)	/* }{ */
119 
120 /* Windows (but not DDK) and Visual C++ 2005 or higher */
121 #define l_fseek(f,o,w)		_fseeki64(f,o,w)
122 #define l_ftell(f)		_ftelli64(f)
123 #define l_seeknum		__int64
124 
125 #else				/* }{ */
126 
127 /* ANSI definitions */
128 #define l_fseek(f,o,w)		fseek(f,o,w)
129 #define l_ftell(f)		ftell(f)
130 #define l_seeknum		long
131 
132 #endif				/* } */
133 
134 #endif				/* } */
135 
136 /* }====================================================== */
137 
138 
139 #define IO_PREFIX	"_IO_"
140 #define IO_INPUT	(IO_PREFIX "input")
141 #define IO_OUTPUT	(IO_PREFIX "output")
142 
143 
144 typedef luaL_Stream LStream;
145 
146 
147 #define tolstream(L)	((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
148 
149 #define isclosed(p)	((p)->closef == NULL)
150 
151 
152 static int io_type (lua_State *L) {
153   LStream *p;
154   luaL_checkany(L, 1);
155   p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
156   if (p == NULL)
157     lua_pushnil(L);  /* not a file */
158   else if (isclosed(p))
159     lua_pushliteral(L, "closed file");
160   else
161     lua_pushliteral(L, "file");
162   return 1;
163 }
164 
165 
166 static int f_tostring (lua_State *L) {
167   LStream *p = tolstream(L);
168   if (isclosed(p))
169     lua_pushliteral(L, "file (closed)");
170   else
171     lua_pushfstring(L, "file (%p)", p->f);
172   return 1;
173 }
174 
175 
176 static FILE *tofile (lua_State *L) {
177   LStream *p = tolstream(L);
178   if (isclosed(p))
179     luaL_error(L, "attempt to use a closed file");
180   lua_assert(p->f);
181   return p->f;
182 }
183 
184 
185 /*
186 ** When creating file handles, always creates a `closed' file handle
187 ** before opening the actual file; so, if there is a memory error, the
188 ** file is not left opened.
189 */
190 static LStream *newprefile (lua_State *L) {
191   LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream));
192   p->closef = NULL;  /* mark file handle as 'closed' */
193   luaL_setmetatable(L, LUA_FILEHANDLE);
194   return p;
195 }
196 
197 
198 static int aux_close (lua_State *L) {
199   LStream *p = tolstream(L);
200   lua_CFunction cf = p->closef;
201   p->closef = NULL;  /* mark stream as closed */
202   return (*cf)(L);  /* close it */
203 }
204 
205 
206 static int io_close (lua_State *L) {
207   if (lua_isnone(L, 1))  /* no argument? */
208     lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT);  /* use standard output */
209   tofile(L);  /* make sure argument is an open stream */
210   return aux_close(L);
211 }
212 
213 
214 static int f_gc (lua_State *L) {
215   LStream *p = tolstream(L);
216   if (!isclosed(p) && p->f != NULL)
217     aux_close(L);  /* ignore closed and incompletely open files */
218   return 0;
219 }
220 
221 
222 /*
223 ** function to close regular files
224 */
225 static int io_fclose (lua_State *L) {
226   LStream *p = tolstream(L);
227   int res = fclose(p->f);
228   return luaL_fileresult(L, (res == 0), NULL);
229 }
230 
231 
232 static LStream *newfile (lua_State *L) {
233   LStream *p = newprefile(L);
234   p->f = NULL;
235   p->closef = &io_fclose;
236   return p;
237 }
238 
239 
240 static void opencheck (lua_State *L, const char *fname, const char *mode) {
241   LStream *p = newfile(L);
242   p->f = fopen(fname, mode);
243   if (p->f == NULL)
244     luaL_error(L, "cannot open file " LUA_QS " (%s)", fname, strerror(errno));
245 }
246 
247 
248 static int io_open (lua_State *L) {
249   const char *filename = luaL_checkstring(L, 1);
250   const char *mode = luaL_optstring(L, 2, "r");
251   LStream *p = newfile(L);
252   const char *md = mode;  /* to traverse/check mode */
253   luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
254   p->f = fopen(filename, mode);
255   return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
256 }
257 
258 
259 /*
260 ** function to close 'popen' files
261 */
262 static int io_pclose (lua_State *L) {
263   LStream *p = tolstream(L);
264   return luaL_execresult(L, l_pclose(L, p->f));
265 }
266 
267 
268 static int io_popen (lua_State *L) {
269   const char *filename = luaL_checkstring(L, 1);
270   const char *mode = luaL_optstring(L, 2, "r");
271   LStream *p = newprefile(L);
272   p->f = l_popen(L, filename, mode);
273   p->closef = &io_pclose;
274   return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
275 }
276 
277 
278 static int io_tmpfile (lua_State *L) {
279   LStream *p = newfile(L);
280   p->f = tmpfile();
281   return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
282 }
283 
284 
285 static FILE *getiofile (lua_State *L, const char *findex) {
286   LStream *p;
287   lua_getfield(L, LUA_REGISTRYINDEX, findex);
288   p = (LStream *)lua_touserdata(L, -1);
289   if (isclosed(p))
290     luaL_error(L, "standard %s file is closed", findex + strlen(IO_PREFIX));
291   return p->f;
292 }
293 
294 
295 static int g_iofile (lua_State *L, const char *f, const char *mode) {
296   if (!lua_isnoneornil(L, 1)) {
297     const char *filename = lua_tostring(L, 1);
298     if (filename)
299       opencheck(L, filename, mode);
300     else {
301       tofile(L);  /* check that it's a valid file handle */
302       lua_pushvalue(L, 1);
303     }
304     lua_setfield(L, LUA_REGISTRYINDEX, f);
305   }
306   /* return current value */
307   lua_getfield(L, LUA_REGISTRYINDEX, f);
308   return 1;
309 }
310 
311 
312 static int io_input (lua_State *L) {
313   return g_iofile(L, IO_INPUT, "r");
314 }
315 
316 
317 static int io_output (lua_State *L) {
318   return g_iofile(L, IO_OUTPUT, "w");
319 }
320 
321 
322 static int io_readline (lua_State *L);
323 
324 
325 static void aux_lines (lua_State *L, int toclose) {
326   int n = lua_gettop(L) - 1;  /* number of arguments to read */
327   lua_pushinteger(L, n);  /* number of arguments to read */
328   lua_pushboolean(L, toclose);  /* close/not close file when finished */
329   lua_rotate(L, 2, 2);  /* move 'n' and 'toclose' to their positions */
330   lua_pushcclosure(L, io_readline, 3 + n);
331 }
332 
333 
334 static int f_lines (lua_State *L) {
335   tofile(L);  /* check that it's a valid file handle */
336   aux_lines(L, 0);
337   return 1;
338 }
339 
340 
341 static int io_lines (lua_State *L) {
342   int toclose;
343   if (lua_isnone(L, 1)) lua_pushnil(L);  /* at least one argument */
344   if (lua_isnil(L, 1)) {  /* no file name? */
345     lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT);  /* get default input */
346     lua_replace(L, 1);  /* put it at index 1 */
347     tofile(L);  /* check that it's a valid file handle */
348     toclose = 0;  /* do not close it after iteration */
349   }
350   else {  /* open a new file */
351     const char *filename = luaL_checkstring(L, 1);
352     opencheck(L, filename, "r");
353     lua_replace(L, 1);  /* put file at index 1 */
354     toclose = 1;  /* close it after iteration */
355   }
356   aux_lines(L, toclose);
357   return 1;
358 }
359 
360 
361 /*
362 ** {======================================================
363 ** READ
364 ** =======================================================
365 */
366 
367 
368 /* maximum length of a numeral */
369 #define MAXRN		200
370 
371 /* auxiliary structure used by 'read_number' */
372 typedef struct {
373   FILE *f;  /* file being read */
374   int c;  /* current character (look ahead) */
375   int n;  /* number of elements in buffer 'buff' */
376   char buff[MAXRN + 1];  /* +1 for ending '\0' */
377 } RN;
378 
379 
380 /*
381 ** Add current char to buffer (if not out of space) and read next one
382 */
383 static int nextc (RN *rn) {
384   if (rn->n >= MAXRN) {  /* buffer overflow? */
385     rn->buff[0] = '\0';  /* invalidate result */
386     return 0;  /* fail */
387   }
388   else {
389     rn->buff[rn->n++] = rn->c;  /* save current char */
390     rn->c = l_getc(rn->f);  /* read next one */
391     return 1;
392   }
393 }
394 
395 
396 /*
397 ** Accept current char if it is in 'set' (of size 1 or 2)
398 */
399 static int test2 (RN *rn, const char *set) {
400   if (rn->c == set[0] || (rn->c == set[1] && rn->c != '\0'))
401     return nextc(rn);
402   else return 0;
403 }
404 
405 
406 /*
407 ** Read a sequence of (hexa)digits
408 */
409 static int readdigits (RN *rn, int hexa) {
410   int count = 0;
411   while ((hexa ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
412     count++;
413   return count;
414 }
415 
416 
417 /* access to locale "radix character" (decimal point) */
418 #if !defined(getlocaledecpoint)
419 #define getlocaledecpoint()     (localeconv()->decimal_point[0])
420 #endif
421 
422 
423 /*
424 ** Read a number: first reads a valid prefix of a numeral into a buffer.
425 ** Then it calls 'lua_strtonum' to check whether the format is correct
426 ** and to convert it to a Lua number
427 */
428 static int read_number (lua_State *L, FILE *f) {
429   RN rn;
430   int count = 0;
431   int hexa = 0;
432   char decp[2] = ".";
433   rn.f = f; rn.n = 0;
434   decp[0] = getlocaledecpoint();  /* get decimal point from locale */
435   l_lockfile(rn.f);
436   do { rn.c = l_getc(rn.f); } while (isspace(rn.c));  /* skip spaces */
437   test2(&rn, "-+");  /* optional signal */
438   if (test2(&rn, "0")) {
439     if (test2(&rn, "xX")) hexa = 1;  /* numeral is hexadecimal */
440     else count = 1;  /* count initial '0' as a valid digit */
441   }
442   count += readdigits(&rn, hexa);  /* integral part */
443   if (test2(&rn, decp))  /* decimal point? */
444     count += readdigits(&rn, hexa);  /* fractionary part */
445   if (count > 0 && test2(&rn, (hexa ? "pP" : "eE"))) {  /* exponent mark? */
446     test2(&rn, "-+");  /* exponent signal */
447     readdigits(&rn, 0);  /* exponent digits */
448   }
449   ungetc(rn.c, rn.f);  /* unread look-ahead char */
450   l_unlockfile(rn.f);
451   rn.buff[rn.n] = '\0';  /* finish string */
452   if (lua_strtonum(L, rn.buff))  /* is this a valid number? */
453     return 1;  /* ok */
454   else {  /* invalid format */
455    lua_pushnil(L);  /* "result" to be removed */
456    return 0;  /* read fails */
457   }
458 }
459 
460 
461 static int test_eof (lua_State *L, FILE *f) {
462   int c = getc(f);
463   ungetc(c, f);  /* no-op when c == EOF */
464   lua_pushlstring(L, NULL, 0);
465   return (c != EOF);
466 }
467 
468 
469 static int read_line (lua_State *L, FILE *f, int chop) {
470   luaL_Buffer b;
471   int c;
472   luaL_buffinit(L, &b);
473   l_lockfile(f);
474   while ((c = l_getc(f)) != EOF && c != '\n')
475     luaL_addchar(&b, c);
476   l_unlockfile(f);
477   if (!chop && c == '\n') luaL_addchar(&b, c);
478   luaL_pushresult(&b);  /* close buffer */
479   return (c == '\n' || lua_rawlen(L, -1) > 0);
480 }
481 
482 
483 static void read_all (lua_State *L, FILE *f) {
484   size_t nr;
485   luaL_Buffer b;
486   luaL_buffinit(L, &b);
487   do {  /* read file in chunks of LUAL_BUFFERSIZE bytes */
488     char *p = luaL_prepbuffsize(&b, LUAL_BUFFERSIZE);
489     nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
490     luaL_addsize(&b, nr);
491   } while (nr == LUAL_BUFFERSIZE);
492   luaL_pushresult(&b);  /* close buffer */
493 }
494 
495 
496 static int read_chars (lua_State *L, FILE *f, size_t n) {
497   size_t nr;  /* number of chars actually read */
498   char *p;
499   luaL_Buffer b;
500   luaL_buffinit(L, &b);
501   p = luaL_prepbuffsize(&b, n);  /* prepare buffer to read whole block */
502   nr = fread(p, sizeof(char), n, f);  /* try to read 'n' chars */
503   luaL_addsize(&b, nr);
504   luaL_pushresult(&b);  /* close buffer */
505   return (nr > 0);  /* true iff read something */
506 }
507 
508 
509 static int g_read (lua_State *L, FILE *f, int first) {
510   int nargs = lua_gettop(L) - 1;
511   int success;
512   int n;
513   clearerr(f);
514   if (nargs == 0) {  /* no arguments? */
515     success = read_line(L, f, 1);
516     n = first+1;  /* to return 1 result */
517   }
518   else {  /* ensure stack space for all results and for auxlib's buffer */
519     luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
520     success = 1;
521     for (n = first; nargs-- && success; n++) {
522       if (lua_type(L, n) == LUA_TNUMBER) {
523         size_t l = (size_t)lua_tointeger(L, n);
524         success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
525       }
526       else {
527         const char *p = luaL_checkstring(L, n);
528         if (*p == '*') p++;  /* skip optional '*' (for compatibility) */
529         switch (*p) {
530           case 'n':  /* number */
531             success = read_number(L, f);
532             break;
533           case 'l':  /* line */
534             success = read_line(L, f, 1);
535             break;
536           case 'L':  /* line with end-of-line */
537             success = read_line(L, f, 0);
538             break;
539           case 'a':  /* file */
540             read_all(L, f);  /* read entire file */
541             success = 1; /* always success */
542             break;
543           default:
544             return luaL_argerror(L, n, "invalid format");
545         }
546       }
547     }
548   }
549   if (ferror(f))
550     return luaL_fileresult(L, 0, NULL);
551   if (!success) {
552     lua_pop(L, 1);  /* remove last result */
553     lua_pushnil(L);  /* push nil instead */
554   }
555   return n - first;
556 }
557 
558 
559 static int io_read (lua_State *L) {
560   return g_read(L, getiofile(L, IO_INPUT), 1);
561 }
562 
563 
564 static int f_read (lua_State *L) {
565   return g_read(L, tofile(L), 2);
566 }
567 
568 
569 static int io_readline (lua_State *L) {
570   LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
571   int i;
572   int n = (int)lua_tointeger(L, lua_upvalueindex(2));
573   if (isclosed(p))  /* file is already closed? */
574     return luaL_error(L, "file is already closed");
575   lua_settop(L , 1);
576   luaL_checkstack(L, n, "too many arguments");
577   for (i = 1; i <= n; i++)  /* push arguments to 'g_read' */
578     lua_pushvalue(L, lua_upvalueindex(3 + i));
579   n = g_read(L, p->f, 2);  /* 'n' is number of results */
580   lua_assert(n > 0);  /* should return at least a nil */
581   if (!lua_isnil(L, -n))  /* read at least one value? */
582     return n;  /* return them */
583   else {  /* first result is nil: EOF or error */
584     if (n > 1) {  /* is there error information? */
585       /* 2nd result is error message */
586       return luaL_error(L, "%s", lua_tostring(L, -n + 1));
587     }
588     if (lua_toboolean(L, lua_upvalueindex(3))) {  /* generator created file? */
589       lua_settop(L, 0);
590       lua_pushvalue(L, lua_upvalueindex(1));
591       aux_close(L);  /* close it */
592     }
593     return 0;
594   }
595 }
596 
597 /* }====================================================== */
598 
599 
600 static int g_write (lua_State *L, FILE *f, int arg) {
601   int nargs = lua_gettop(L) - arg;
602   int status = 1;
603   for (; nargs--; arg++) {
604     if (lua_type(L, arg) == LUA_TNUMBER) {
605       /* optimization: could be done exactly as for strings */
606       int len = lua_isinteger(L, arg)
607                 ? fprintf(f, LUA_INTEGER_FMT, lua_tointeger(L, arg))
608                 : fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg));
609       status = status && (len > 0);
610     }
611     else {
612       size_t l;
613       const char *s = luaL_checklstring(L, arg, &l);
614       status = status && (fwrite(s, sizeof(char), l, f) == l);
615     }
616   }
617   if (status) return 1;  /* file handle already on stack top */
618   else return luaL_fileresult(L, status, NULL);
619 }
620 
621 
622 static int io_write (lua_State *L) {
623   return g_write(L, getiofile(L, IO_OUTPUT), 1);
624 }
625 
626 
627 static int f_write (lua_State *L) {
628   FILE *f = tofile(L);
629   lua_pushvalue(L, 1);  /* push file at the stack top (to be returned) */
630   return g_write(L, f, 2);
631 }
632 
633 
634 static int f_seek (lua_State *L) {
635   static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
636   static const char *const modenames[] = {"set", "cur", "end", NULL};
637   FILE *f = tofile(L);
638   int op = luaL_checkoption(L, 2, "cur", modenames);
639   lua_Integer p3 = luaL_optinteger(L, 3, 0);
640   l_seeknum offset = (l_seeknum)p3;
641   luaL_argcheck(L, (lua_Integer)offset == p3, 3,
642                   "not an integer in proper range");
643   op = l_fseek(f, offset, mode[op]);
644   if (op)
645     return luaL_fileresult(L, 0, NULL);  /* error */
646   else {
647     lua_pushinteger(L, (lua_Integer)l_ftell(f));
648     return 1;
649   }
650 }
651 
652 
653 static int f_setvbuf (lua_State *L) {
654   static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
655   static const char *const modenames[] = {"no", "full", "line", NULL};
656   FILE *f = tofile(L);
657   int op = luaL_checkoption(L, 2, NULL, modenames);
658   lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
659   int res = setvbuf(f, NULL, mode[op], sz);
660   return luaL_fileresult(L, res == 0, NULL);
661 }
662 
663 
664 
665 static int io_flush (lua_State *L) {
666   return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
667 }
668 
669 
670 static int f_flush (lua_State *L) {
671   return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
672 }
673 
674 
675 /*
676 ** functions for 'io' library
677 */
678 static const luaL_Reg iolib[] = {
679   {"close", io_close},
680   {"flush", io_flush},
681   {"input", io_input},
682   {"lines", io_lines},
683   {"open", io_open},
684   {"output", io_output},
685   {"popen", io_popen},
686   {"read", io_read},
687   {"tmpfile", io_tmpfile},
688   {"type", io_type},
689   {"write", io_write},
690   {NULL, NULL}
691 };
692 
693 
694 /*
695 ** methods for file handles
696 */
697 static const luaL_Reg flib[] = {
698   {"close", io_close},
699   {"flush", f_flush},
700   {"lines", f_lines},
701   {"read", f_read},
702   {"seek", f_seek},
703   {"setvbuf", f_setvbuf},
704   {"write", f_write},
705   {"__gc", f_gc},
706   {"__tostring", f_tostring},
707   {NULL, NULL}
708 };
709 
710 
711 static void createmeta (lua_State *L) {
712   luaL_newmetatable(L, LUA_FILEHANDLE);  /* create metatable for file handles */
713   lua_pushvalue(L, -1);  /* push metatable */
714   lua_setfield(L, -2, "__index");  /* metatable.__index = metatable */
715   luaL_setfuncs(L, flib, 0);  /* add file methods to new metatable */
716   lua_pop(L, 1);  /* pop new metatable */
717 }
718 
719 
720 /*
721 ** function to (not) close the standard files stdin, stdout, and stderr
722 */
723 static int io_noclose (lua_State *L) {
724   LStream *p = tolstream(L);
725   p->closef = &io_noclose;  /* keep file opened */
726   lua_pushnil(L);
727   lua_pushliteral(L, "cannot close standard file");
728   return 2;
729 }
730 
731 
732 static void createstdfile (lua_State *L, FILE *f, const char *k,
733                            const char *fname) {
734   LStream *p = newprefile(L);
735   p->f = f;
736   p->closef = &io_noclose;
737   if (k != NULL) {
738     lua_pushvalue(L, -1);
739     lua_setfield(L, LUA_REGISTRYINDEX, k);  /* add file to registry */
740   }
741   lua_setfield(L, -2, fname);  /* add file to module */
742 }
743 
744 
745 LUAMOD_API int luaopen_io (lua_State *L) {
746   luaL_newlib(L, iolib);  /* new module */
747   createmeta(L);
748   /* create (and set) default files */
749   createstdfile(L, stdin, IO_INPUT, "stdin");
750   createstdfile(L, stdout, IO_OUTPUT, "stdout");
751   createstdfile(L, stderr, NULL, "stderr");
752   return 1;
753 }
754 
755