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