Debian Codegraph @

libs/lua53/lua53-src/src/liolib.c

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