liolib.c 18 KB

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