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