liolib.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. /*
  2. ** $Id: liolib.c,v 1.90 2000/10/27 16:15:53 roberto Exp roberto $
  3. ** Standard I/O (and system) library
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <ctype.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <time.h>
  11. #include "lua.h"
  12. #include "lauxlib.h"
  13. #include "luadebug.h"
  14. #include "lualib.h"
  15. #ifndef OLD_ANSI
  16. #include <errno.h>
  17. #include <locale.h>
  18. #define realloc(b,s) ((b) == NULL ? malloc(s) : (realloc)(b, s))
  19. #define free(b) if (b) (free)(b)
  20. #else
  21. /* no support for locale and for strerror: fake them */
  22. #define setlocale(a,b) ((void)a, strcmp((b),"C")==0?"C":NULL)
  23. #define LC_ALL 0
  24. #define LC_COLLATE 0
  25. #define LC_CTYPE 0
  26. #define LC_MONETARY 0
  27. #define LC_NUMERIC 0
  28. #define LC_TIME 0
  29. #define strerror(e) "generic I/O error"
  30. #define errno (-1)
  31. #endif
  32. #ifdef POPEN
  33. /* FILE *popen();
  34. int pclose(); */
  35. #define CLOSEFILE(L, f) ((pclose(f) == -1) ? fclose(f) : 0)
  36. #else
  37. /* no support for popen */
  38. #define popen(x,y) NULL /* that is, popen always fails */
  39. #define CLOSEFILE(L, f) (fclose(f))
  40. #endif
  41. #define INFILE 0
  42. #define OUTFILE 1
  43. typedef struct IOCtrl {
  44. int ref[2]; /* ref for strings _INPUT/_OUTPUT */
  45. int iotag; /* tag for file handles */
  46. int closedtag; /* tag for closed handles */
  47. } IOCtrl;
  48. static const char *const filenames[] = {"_INPUT", "_OUTPUT"};
  49. static int pushresult (lua_State *L, int i) {
  50. if (i) {
  51. lua_pushuserdata(L, NULL);
  52. return 1;
  53. }
  54. else {
  55. lua_pushnil(L);
  56. lua_pushstring(L, strerror(errno));
  57. lua_pushnumber(L, errno);
  58. return 3;;
  59. }
  60. }
  61. /*
  62. ** {======================================================
  63. ** FILE Operations
  64. ** =======================================================
  65. */
  66. static FILE *gethandle (lua_State *L, IOCtrl *ctrl, int f) {
  67. void *p = lua_touserdata(L, f);
  68. if (p != NULL) { /* is `f' a userdata ? */
  69. int ftag = lua_tag(L, f);
  70. if (ftag == ctrl->iotag) /* does it have the correct tag? */
  71. return (FILE *)p;
  72. else if (ftag == ctrl->closedtag)
  73. lua_error(L, "cannot access a closed file");
  74. /* else go through */
  75. }
  76. return NULL;
  77. }
  78. static FILE *getnonullfile (lua_State *L, IOCtrl *ctrl, int arg) {
  79. FILE *f = gethandle(L, ctrl, arg);
  80. luaL_arg_check(L, f, arg, "invalid file handle");
  81. return f;
  82. }
  83. static FILE *getfilebyref (lua_State *L, IOCtrl *ctrl, int inout) {
  84. FILE *f;
  85. lua_getglobals(L);
  86. lua_getref(L, ctrl->ref[inout]);
  87. lua_rawget(L, -2);
  88. f = gethandle(L, ctrl, -1);
  89. if (f == NULL)
  90. luaL_verror(L, "global variable `%.10s' is not a file handle",
  91. filenames[inout]);
  92. return f;
  93. }
  94. static void setfilebyname (lua_State *L, IOCtrl *ctrl, FILE *f,
  95. const char *name) {
  96. lua_pushusertag(L, f, ctrl->iotag);
  97. lua_setglobal(L, name);
  98. }
  99. #define setfile(L,ctrl,f,inout) (setfilebyname(L,ctrl,f,filenames[inout]))
  100. static int setreturn (lua_State *L, IOCtrl *ctrl, FILE *f, int inout) {
  101. if (f == NULL)
  102. return pushresult(L, 0);
  103. else {
  104. setfile(L, ctrl, f, inout);
  105. lua_pushusertag(L, f, ctrl->iotag);
  106. return 1;
  107. }
  108. }
  109. static int closefile (lua_State *L, IOCtrl *ctrl, FILE *f) {
  110. if (f == stdin || f == stdout || f == stderr)
  111. return 1;
  112. else {
  113. lua_pushusertag(L, f, ctrl->iotag);
  114. lua_settag(L, ctrl->closedtag);
  115. return (CLOSEFILE(L, f) == 0);
  116. }
  117. }
  118. static int io_close (lua_State *L) {
  119. IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
  120. lua_pop(L, 1); /* remove upvalue */
  121. return pushresult(L, closefile(L, ctrl, getnonullfile(L, ctrl, 1)));
  122. }
  123. static int file_collect (lua_State *L) {
  124. IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
  125. FILE *f = getnonullfile(L, ctrl, 1);
  126. if (f != stdin && f != stdout && f != stderr)
  127. CLOSEFILE(L, f);
  128. return 0;
  129. }
  130. static int io_open (lua_State *L) {
  131. IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
  132. FILE *f;
  133. lua_pop(L, 1); /* remove upvalue */
  134. f = fopen(luaL_check_string(L, 1), luaL_check_string(L, 2));
  135. if (f) {
  136. lua_pushusertag(L, f, ctrl->iotag);
  137. return 1;
  138. }
  139. else
  140. return pushresult(L, 0);
  141. }
  142. static int io_fromto (lua_State *L, int inout, const char *mode) {
  143. IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
  144. FILE *current;
  145. lua_pop(L, 1); /* remove upvalue */
  146. if (lua_isnull(L, 1)) {
  147. closefile(L, ctrl, getfilebyref(L, ctrl, inout));
  148. current = (inout == 0) ? stdin : stdout;
  149. }
  150. else if (lua_tag(L, 1) == ctrl->iotag) /* deprecated option */
  151. current = (FILE *)lua_touserdata(L, 1);
  152. else {
  153. const char *s = luaL_check_string(L, 1);
  154. current = (*s == '|') ? popen(s+1, mode) : fopen(s, mode);
  155. }
  156. return setreturn(L, ctrl, current, inout);
  157. }
  158. static int io_readfrom (lua_State *L) {
  159. return io_fromto(L, INFILE, "r");
  160. }
  161. static int io_writeto (lua_State *L) {
  162. return io_fromto(L, OUTFILE, "w");
  163. }
  164. static int io_appendto (lua_State *L) {
  165. IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
  166. FILE *current;
  167. lua_pop(L, 1); /* remove upvalue */
  168. current = fopen(luaL_check_string(L, 1), "a");
  169. return setreturn(L, ctrl, current, OUTFILE);
  170. }
  171. /*
  172. ** {======================================================
  173. ** READ
  174. ** =======================================================
  175. */
  176. #ifdef LUA_COMPAT_READPATTERN
  177. /*
  178. ** We cannot lookahead without need, because this can lock stdin.
  179. ** This flag signals when we need to read a next char.
  180. */
  181. #define NEED_OTHER (EOF-1) /* just some flag different from EOF */
  182. static int read_pattern (lua_State *L, FILE *f, const char *p) {
  183. int inskip = 0; /* {skip} level */
  184. int c = NEED_OTHER;
  185. luaL_Buffer b;
  186. luaL_buffinit(L, &b);
  187. while (*p != '\0') {
  188. switch (*p) {
  189. case '{':
  190. inskip++;
  191. p++;
  192. continue;
  193. case '}':
  194. if (!inskip) lua_error(L, "unbalanced braces in read pattern");
  195. inskip--;
  196. p++;
  197. continue;
  198. default: {
  199. const char *ep = luaI_classend(L, p); /* get what is next */
  200. int m; /* match result */
  201. if (c == NEED_OTHER) c = getc(f);
  202. m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
  203. if (m) {
  204. if (!inskip) luaL_putchar(&b, c);
  205. c = NEED_OTHER;
  206. }
  207. switch (*ep) {
  208. case '+': /* repetition (1 or more) */
  209. if (!m) goto break_while; /* pattern fails? */
  210. /* else go through */
  211. case '*': /* repetition (0 or more) */
  212. while (m) { /* reads the same item until it fails */
  213. c = getc(f);
  214. m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
  215. if (m && !inskip) luaL_putchar(&b, c);
  216. }
  217. /* go through to continue reading the pattern */
  218. case '?': /* optional */
  219. p = ep+1; /* continues reading the pattern */
  220. continue;
  221. default:
  222. if (!m) goto break_while; /* pattern fails? */
  223. p = ep; /* else continues reading the pattern */
  224. }
  225. }
  226. }
  227. } break_while:
  228. if (c != NEED_OTHER) ungetc(c, f);
  229. luaL_pushresult(&b); /* close buffer */
  230. return (*p == '\0');
  231. }
  232. #else
  233. #define read_pattern(L, f, p) (lua_error(L, "read patterns are deprecated"), 0)
  234. #endif
  235. static int read_number (lua_State *L, FILE *f) {
  236. double d;
  237. if (fscanf(f, "%lf", &d) == 1) {
  238. lua_pushnumber(L, d);
  239. return 1;
  240. }
  241. else return 0; /* read fails */
  242. }
  243. static int read_word (lua_State *L, FILE *f) {
  244. int c;
  245. luaL_Buffer b;
  246. luaL_buffinit(L, &b);
  247. do { c = fgetc(f); } while (isspace(c)); /* skip spaces */
  248. while (c != EOF && !isspace(c)) {
  249. luaL_putchar(&b, c);
  250. c = fgetc(f);
  251. }
  252. ungetc(c, f);
  253. luaL_pushresult(&b); /* close buffer */
  254. return (lua_strlen(L, -1) > 0);
  255. }
  256. static int read_line (lua_State *L, FILE *f) {
  257. int n = 0;
  258. luaL_Buffer b;
  259. luaL_buffinit(L, &b);
  260. for (;;) {
  261. char *p = luaL_prepbuffer(&b);
  262. if (!fgets(p, LUAL_BUFFERSIZE, f)) /* read fails? */
  263. break;
  264. n = strlen(p);
  265. if (p[n-1] != '\n')
  266. luaL_addsize(&b, n);
  267. else {
  268. luaL_addsize(&b, n-1); /* do not add the `\n' */
  269. break;
  270. }
  271. }
  272. luaL_pushresult(&b); /* close buffer */
  273. return (n > 0); /* read something? */
  274. }
  275. static void read_file (lua_State *L, FILE *f) {
  276. size_t len = 0;
  277. size_t size = BUFSIZ;
  278. char *buffer = NULL;
  279. for (;;) {
  280. char *newbuffer = (char *)realloc(buffer, size);
  281. if (newbuffer == NULL) {
  282. free(buffer);
  283. lua_error(L, "not enough memory to read a file");
  284. }
  285. buffer = newbuffer;
  286. len += fread(buffer+len, sizeof(char), size-len, f);
  287. if (len < size) break; /* did not read all it could */
  288. size *= 2;
  289. }
  290. lua_pushlstring(L, buffer, len);
  291. free(buffer);
  292. }
  293. static int read_chars (lua_State *L, FILE *f, size_t n) {
  294. char *buffer;
  295. size_t n1;
  296. char statbuff[BUFSIZ];
  297. if (n <= BUFSIZ)
  298. buffer = statbuff;
  299. else {
  300. buffer = (char *)malloc(n);
  301. if (buffer == NULL)
  302. lua_error(L, "not enough memory to read a file");
  303. }
  304. n1 = fread(buffer, sizeof(char), n, f);
  305. lua_pushlstring(L, buffer, n1);
  306. if (buffer != statbuff) free(buffer);
  307. return (n1 > 0 || n == 0);
  308. }
  309. static int io_read (lua_State *L) {
  310. IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
  311. int lastarg = lua_gettop(L) - 1;
  312. int firstarg = 1;
  313. FILE *f = gethandle(L, ctrl, firstarg);
  314. int n;
  315. if (f) firstarg++;
  316. else f = getfilebyref(L, ctrl, INFILE); /* get _INPUT */
  317. lua_pop(L, 1);
  318. if (firstarg > lastarg) { /* no arguments? */
  319. lua_settop(L, 0); /* erase upvalue and other eventual garbage */
  320. firstarg = lastarg = 1; /* correct indices */
  321. lua_pushstring(L, "*l"); /* push default argument */
  322. }
  323. else /* ensure stack space for all results and for auxlib's buffer */
  324. luaL_checkstack(L, lastarg-firstarg+1+LUA_MINSTACK, "too many arguments");
  325. for (n = firstarg; n<=lastarg; n++) {
  326. int success;
  327. if (lua_isnumber(L, n))
  328. success = read_chars(L, f, (size_t)lua_tonumber(L, n));
  329. else {
  330. const char *p = luaL_check_string(L, n);
  331. if (p[0] != '*')
  332. success = read_pattern(L, f, p); /* deprecated! */
  333. else {
  334. switch (p[1]) {
  335. case 'n': /* number */
  336. if (!read_number(L, f)) goto endloop; /* read fails */
  337. continue; /* number is already pushed; avoid the "pushstring" */
  338. case 'l': /* line */
  339. success = read_line(L, f);
  340. break;
  341. case 'a': /* file */
  342. read_file(L, f);
  343. success = 1; /* always success */
  344. break;
  345. case 'w': /* word */
  346. success = read_word(L, f);
  347. break;
  348. default:
  349. luaL_argerror(L, n, "invalid format");
  350. success = 0; /* to avoid warnings */
  351. }
  352. }
  353. }
  354. if (!success) {
  355. lua_pop(L, 1); /* remove last result */
  356. break; /* read fails */
  357. }
  358. } endloop:
  359. return n - firstarg;
  360. }
  361. /* }====================================================== */
  362. static int io_write (lua_State *L) {
  363. int lastarg = lua_gettop(L) - 1;
  364. IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
  365. int arg = 1;
  366. int status = 1;
  367. FILE *f = gethandle(L, ctrl, arg);
  368. if (f) arg++;
  369. else f = getfilebyref(L, ctrl, OUTFILE); /* get _OUTPUT */
  370. for (; arg <= lastarg; arg++) {
  371. if (lua_type(L, arg) == LUA_TNUMBER) { /* LUA_NUMBER */
  372. /* optimization: could be done exactly as for strings */
  373. status = status && fprintf(f, "%.16g", lua_tonumber(L, arg)) > 0;
  374. }
  375. else {
  376. size_t l;
  377. const char *s = luaL_check_lstr(L, arg, &l);
  378. status = status && (fwrite(s, sizeof(char), l, f) == l);
  379. }
  380. }
  381. pushresult(L, status);
  382. return 1;
  383. }
  384. static int io_seek (lua_State *L) {
  385. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  386. static const char *const modenames[] = {"set", "cur", "end", NULL};
  387. IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
  388. FILE *f;
  389. int op;
  390. long offset;
  391. lua_pop(L, 1); /* remove upvalue */
  392. f = getnonullfile(L, ctrl, 1);
  393. op = luaL_findstring(luaL_opt_string(L, 2, "cur"), modenames);
  394. offset = luaL_opt_long(L, 3, 0);
  395. luaL_arg_check(L, op != -1, 2, "invalid mode");
  396. op = fseek(f, offset, mode[op]);
  397. if (op)
  398. return pushresult(L, 0); /* error */
  399. else {
  400. lua_pushnumber(L, ftell(f));
  401. return 1;
  402. }
  403. }
  404. static int io_flush (lua_State *L) {
  405. IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
  406. FILE *f;
  407. lua_pop(L, 1); /* remove upvalue */
  408. f = gethandle(L, ctrl, 1);
  409. luaL_arg_check(L, f || lua_isnull(L, 1), 1, "invalid file handle");
  410. return pushresult(L, fflush(f) == 0);
  411. }
  412. /* }====================================================== */
  413. /*
  414. ** {======================================================
  415. ** Other O.S. Operations
  416. ** =======================================================
  417. */
  418. static int io_execute (lua_State *L) {
  419. lua_pushnumber(L, system(luaL_check_string(L, 1)));
  420. return 1;
  421. }
  422. static int io_remove (lua_State *L) {
  423. return pushresult(L, remove(luaL_check_string(L, 1)) == 0);
  424. }
  425. static int io_rename (lua_State *L) {
  426. return pushresult(L, rename(luaL_check_string(L, 1),
  427. luaL_check_string(L, 2)) == 0);
  428. }
  429. static int io_tmpname (lua_State *L) {
  430. lua_pushstring(L, tmpnam(NULL));
  431. return 1;
  432. }
  433. static int io_getenv (lua_State *L) {
  434. lua_pushstring(L, getenv(luaL_check_string(L, 1))); /* if NULL push nil */
  435. return 1;
  436. }
  437. static int io_clock (lua_State *L) {
  438. lua_pushnumber(L, ((double)clock())/CLOCKS_PER_SEC);
  439. return 1;
  440. }
  441. static int io_date (lua_State *L) {
  442. char b[256];
  443. const char *s = luaL_opt_string(L, 1, "%c");
  444. struct tm *stm;
  445. time_t t;
  446. time(&t); stm = localtime(&t);
  447. if (strftime(b, sizeof(b), s, stm))
  448. lua_pushstring(L, b);
  449. else
  450. lua_error(L, "invalid `date' format");
  451. return 1;
  452. }
  453. static int setloc (lua_State *L) {
  454. static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
  455. LC_NUMERIC, LC_TIME};
  456. static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
  457. "numeric", "time", NULL};
  458. int op = luaL_findstring(luaL_opt_string(L, 2, "all"), catnames);
  459. luaL_arg_check(L, op != -1, 2, "invalid option");
  460. lua_pushstring(L, setlocale(cat[op], luaL_check_string(L, 1)));
  461. return 1;
  462. }
  463. static int io_exit (lua_State *L) {
  464. exit(luaL_opt_int(L, 1, EXIT_SUCCESS));
  465. return 0; /* to avoid warnings */
  466. }
  467. /* }====================================================== */
  468. static int io_debug (lua_State *L) {
  469. for (;;) {
  470. char buffer[250];
  471. fprintf(stderr, "lua_debug> ");
  472. if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
  473. strcmp(buffer, "cont\n") == 0)
  474. return 0;
  475. lua_dostring(L, buffer);
  476. lua_settop(L, 0); /* remove eventual returns */
  477. }
  478. }
  479. #define LEVELS1 12 /* size of the first part of the stack */
  480. #define LEVELS2 10 /* size of the second part of the stack */
  481. static int errorfb (lua_State *L) {
  482. int level = 1; /* skip level 0 (it's this function) */
  483. int firstpart = 1; /* still before eventual `...' */
  484. lua_Debug ar;
  485. luaL_Buffer b;
  486. luaL_buffinit(L, &b);
  487. luaL_addstring(&b, "error: ");
  488. luaL_addstring(&b, luaL_check_string(L, 1));
  489. luaL_addstring(&b, "\n");
  490. while (lua_getstack(L, level++, &ar)) {
  491. char buff[120]; /* enough to fit following `sprintf's */
  492. if (level == 2)
  493. luaL_addstring(&b, "stack traceback:\n");
  494. else if (level > LEVELS1 && firstpart) {
  495. /* no more than `LEVELS2' more levels? */
  496. if (!lua_getstack(L, level+LEVELS2, &ar))
  497. level--; /* keep going */
  498. else {
  499. luaL_addstring(&b, " ...\n"); /* too many levels */
  500. while (lua_getstack(L, level+LEVELS2, &ar)) /* find last levels */
  501. level++;
  502. }
  503. firstpart = 0;
  504. continue;
  505. }
  506. sprintf(buff, "%4d: ", level-1);
  507. luaL_addstring(&b, buff);
  508. lua_getinfo(L, "Snl", &ar);
  509. switch (*ar.namewhat) {
  510. case 'g': case 'l': /* global, local */
  511. sprintf(buff, "function `%.50s'", ar.name);
  512. break;
  513. case 'f': /* field */
  514. sprintf(buff, "method `%.50s'", ar.name);
  515. break;
  516. case 't': /* tag method */
  517. sprintf(buff, "`%.50s' tag method", ar.name);
  518. break;
  519. default: {
  520. if (*ar.what == 'm') /* main? */
  521. sprintf(buff, "main of %.70s", ar.short_src);
  522. else if (*ar.what == 'C') /* C function? */
  523. sprintf(buff, "%.70s", ar.short_src);
  524. else
  525. sprintf(buff, "function <%d:%.70s>", ar.linedefined, ar.short_src);
  526. ar.source = NULL; /* do not print source again */
  527. }
  528. }
  529. luaL_addstring(&b, buff);
  530. if (ar.currentline > 0) {
  531. sprintf(buff, " at line %d", ar.currentline);
  532. luaL_addstring(&b, buff);
  533. }
  534. if (ar.source) {
  535. sprintf(buff, " [%.70s]", ar.short_src);
  536. luaL_addstring(&b, buff);
  537. }
  538. luaL_addstring(&b, "\n");
  539. }
  540. luaL_pushresult(&b);
  541. lua_getglobal(L, LUA_ALERT);
  542. if (lua_isfunction(L, -1)) { /* avoid loop if _ALERT is not defined */
  543. lua_pushvalue(L, -2); /* error message */
  544. lua_rawcall(L, 1, 0);
  545. }
  546. return 0;
  547. }
  548. static const struct luaL_reg iolib[] = {
  549. {LUA_ERRORMESSAGE, errorfb},
  550. {"clock", io_clock},
  551. {"date", io_date},
  552. {"debug", io_debug},
  553. {"execute", io_execute},
  554. {"exit", io_exit},
  555. {"getenv", io_getenv},
  556. {"remove", io_remove},
  557. {"rename", io_rename},
  558. {"setlocale", setloc},
  559. {"tmpname", io_tmpname}
  560. };
  561. static const struct luaL_reg iolibtag[] = {
  562. {"appendto", io_appendto},
  563. {"closefile", io_close},
  564. {"flush", io_flush},
  565. {"openfile", io_open},
  566. {"read", io_read},
  567. {"readfrom", io_readfrom},
  568. {"seek", io_seek},
  569. {"write", io_write},
  570. {"writeto", io_writeto}
  571. };
  572. static void openwithcontrol (lua_State *L) {
  573. IOCtrl *ctrl = (IOCtrl *)lua_newuserdata(L, sizeof(IOCtrl));
  574. unsigned int i;
  575. ctrl->iotag = lua_newtag(L);
  576. ctrl->closedtag = lua_newtag(L);
  577. for (i=0; i<sizeof(iolibtag)/sizeof(iolibtag[0]); i++) {
  578. /* put `ctrl' as upvalue for these functions */
  579. lua_pushvalue(L, -1);
  580. lua_pushcclosure(L, iolibtag[i].func, 1);
  581. lua_setglobal(L, iolibtag[i].name);
  582. }
  583. /* create references to variable names */
  584. lua_pushstring(L, filenames[INFILE]);
  585. ctrl->ref[INFILE] = lua_ref(L, 1);
  586. lua_pushstring(L, filenames[OUTFILE]);
  587. ctrl->ref[OUTFILE] = lua_ref(L, 1);
  588. /* predefined file handles */
  589. setfile(L, ctrl, stdin, INFILE);
  590. setfile(L, ctrl, stdout, OUTFILE);
  591. setfilebyname(L, ctrl, stdin, "_STDIN");
  592. setfilebyname(L, ctrl, stdout, "_STDOUT");
  593. setfilebyname(L, ctrl, stderr, "_STDERR");
  594. /* close files when collected */
  595. lua_pushcclosure(L, file_collect, 1); /* pops `ctrl' from stack */
  596. lua_settagmethod(L, ctrl->iotag, "gc");
  597. }
  598. LUALIB_API void lua_iolibopen (lua_State *L) {
  599. luaL_openl(L, iolib);
  600. openwithcontrol(L);
  601. }