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