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