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