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