liolib.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. /*
  2. ** $Id: liolib.c,v 1.81 2000/09/12 13:58:37 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. luaL_Buffer b;
  193. luaL_buffinit(L, &b);
  194. while (*p != '\0') {
  195. switch (*p) {
  196. case '{':
  197. inskip++;
  198. p++;
  199. continue;
  200. case '}':
  201. if (!inskip) lua_error(L, "unbalanced braces in read pattern");
  202. inskip--;
  203. p++;
  204. continue;
  205. default: {
  206. const char *ep = luaI_classend(L, p); /* get what is next */
  207. int m; /* match result */
  208. if (c == NEED_OTHER) c = getc(f);
  209. m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
  210. if (m) {
  211. if (!inskip) luaL_putchar(&b, c);
  212. c = NEED_OTHER;
  213. }
  214. switch (*ep) {
  215. case '+': /* repetition (1 or more) */
  216. if (!m) goto break_while; /* pattern fails? */
  217. /* else go through */
  218. case '*': /* repetition (0 or more) */
  219. while (m) { /* reads the same item until it fails */
  220. c = getc(f);
  221. m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
  222. if (m && !inskip) luaL_putchar(&b, c);
  223. }
  224. /* go through to continue reading the pattern */
  225. case '?': /* optional */
  226. p = ep+1; /* continues reading the pattern */
  227. continue;
  228. default:
  229. if (!m) goto break_while; /* pattern fails? */
  230. p = ep; /* else continues reading the pattern */
  231. }
  232. }
  233. }
  234. } break_while:
  235. if (c != NEED_OTHER) ungetc(c, f);
  236. luaL_pushresult(&b); /* close buffer */
  237. return (*p == '\0');
  238. }
  239. #else
  240. #define read_pattern(L, f, p) (lua_error(L, "read patterns are deprecated"), 0)
  241. #endif
  242. static int read_number (lua_State *L, FILE *f) {
  243. double d;
  244. if (fscanf(f, "%lf", &d) == 1) {
  245. lua_pushnumber(L, d);
  246. return 1;
  247. }
  248. else return 0; /* read fails */
  249. }
  250. static int read_word (lua_State *L, FILE *f) {
  251. int c;
  252. luaL_Buffer b;
  253. luaL_buffinit(L, &b);
  254. do { c = fgetc(f); } while (isspace(c)); /* skip spaces */
  255. while (c != EOF && !isspace(c)) {
  256. luaL_putchar(&b, c);
  257. c = fgetc(f);
  258. }
  259. ungetc(c, f);
  260. luaL_pushresult(&b); /* close buffer */
  261. return (lua_strlen(L, 1) > 0);
  262. }
  263. static int read_line (lua_State *L, FILE *f) {
  264. int n = 0;
  265. luaL_Buffer b;
  266. luaL_buffinit(L, &b);
  267. for (;;) {
  268. char *p = luaL_prepbuffer(&b);
  269. if (!fgets(p, LUAL_BUFFERSIZE, f)) /* read fails? */
  270. break;
  271. n = strlen(p);
  272. if (p[n-1] != '\n')
  273. luaL_addsize(&b, n);
  274. else {
  275. luaL_addsize(&b, n-1); /* do not add the `\n' */
  276. break;
  277. }
  278. }
  279. luaL_pushresult(&b); /* close buffer */
  280. return (n > 0); /* read something? */
  281. }
  282. static void read_file (lua_State *L, FILE *f) {
  283. size_t len = 0;
  284. size_t size = BUFSIZ;
  285. char *buffer = NULL;
  286. for (;;) {
  287. buffer = (char *)realloc(buffer, size);
  288. if (buffer == NULL)
  289. lua_error(L, "not enough memory to read a file");
  290. len += fread(buffer+len, sizeof(char), size-len, f);
  291. if (len < size) break; /* did not read all it could */
  292. size *= 2;
  293. }
  294. lua_pushlstring(L, buffer, len);
  295. free(buffer);
  296. }
  297. static int read_chars (lua_State *L, FILE *f, size_t n) {
  298. char *buffer;
  299. size_t n1;
  300. char statbuff[BUFSIZ];
  301. if (n <= BUFSIZ)
  302. buffer = statbuff;
  303. else {
  304. buffer = (char *)malloc(n);
  305. if (buffer == NULL)
  306. lua_error(L, "not enough memory to read a file");
  307. }
  308. n1 = fread(buffer, sizeof(char), n, f);
  309. lua_pushlstring(L, buffer, n1);
  310. if (buffer != statbuff) free(buffer);
  311. return (n1 > 0 || n == 0);
  312. }
  313. static int io_read (lua_State *L) {
  314. IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
  315. int lastarg = lua_gettop(L) - 1;
  316. int firstarg = 1;
  317. FILE *f = gethandle(L, ctrl, firstarg);
  318. int n;
  319. if (f) firstarg++;
  320. else f = getfilebyref(L, ctrl, INFILE); /* get _INPUT */
  321. lua_pop(L, 1);
  322. if (firstarg > lastarg) { /* no arguments? */
  323. lua_settop(L, 0); /* erase upvalue and other eventual garbage */
  324. firstarg = lastarg = 1; /* correct indices */
  325. lua_pushstring(L, "*l"); /* push default argument */
  326. }
  327. else /* ensure stack space for all results and for auxlib's buffer */
  328. luaL_checkstack(L, lastarg-firstarg+1+LUA_MINSTACK, "too many arguments");
  329. for (n = firstarg; n<=lastarg; n++) {
  330. int success;
  331. if (lua_isnumber(L, n))
  332. success = read_chars(L, f, (size_t)lua_tonumber(L, n));
  333. else {
  334. const char *p = luaL_check_string(L, n);
  335. if (p[0] != '*')
  336. success = read_pattern(L, f, p); /* deprecated! */
  337. else {
  338. switch (p[1]) {
  339. case 'n': /* number */
  340. if (!read_number(L, f)) goto endloop; /* read fails */
  341. continue; /* number is already pushed; avoid the "pushstring" */
  342. case 'l': /* line */
  343. success = read_line(L, f);
  344. break;
  345. case 'a': /* file */
  346. read_file(L, f);
  347. success = 1; /* always success */
  348. break;
  349. case 'w': /* word */
  350. success = read_word(L, f);
  351. break;
  352. default:
  353. luaL_argerror(L, n, "invalid format");
  354. success = 0; /* to avoid warnings */
  355. }
  356. }
  357. }
  358. if (!success) {
  359. lua_pop(L, 1); /* remove last result */
  360. break; /* read fails */
  361. }
  362. } endloop:
  363. return n - firstarg;
  364. }
  365. /* }====================================================== */
  366. static int io_write (lua_State *L) {
  367. int lastarg = lua_gettop(L) - 1;
  368. IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
  369. int arg = 1;
  370. int status = 1;
  371. FILE *f = gethandle(L, ctrl, arg);
  372. if (f) arg++;
  373. else f = getfilebyref(L, ctrl, OUTFILE); /* get _OUTPUT */
  374. for (; arg <= lastarg; arg++) {
  375. if (lua_type(L, arg)[2] == 'm') { /* nuMber? */ /* LUA_NUMBER */
  376. /* optimization: could be done exactly as for strings */
  377. status = status && fprintf(f, "%.16g", lua_tonumber(L, arg)) > 0;
  378. }
  379. else {
  380. size_t l;
  381. const char *s = luaL_check_lstr(L, arg, &l);
  382. status = status && (fwrite(s, sizeof(char), l, f) == l);
  383. }
  384. }
  385. pushresult(L, status);
  386. return 1;
  387. }
  388. static int io_seek (lua_State *L) {
  389. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  390. static const char *const modenames[] = {"set", "cur", "end", NULL};
  391. IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
  392. FILE *f;
  393. int op;
  394. long offset;
  395. lua_pop(L, 1); /* remove upvalue */
  396. f = getnonullfile(L, ctrl, 1);
  397. op = luaL_findstring(luaL_opt_string(L, 2, "cur"), modenames);
  398. offset = luaL_opt_long(L, 3, 0);
  399. luaL_arg_check(L, op != -1, 2, "invalid mode");
  400. op = fseek(f, offset, mode[op]);
  401. if (op)
  402. return pushresult(L, 0); /* error */
  403. else {
  404. lua_pushnumber(L, ftell(f));
  405. return 1;
  406. }
  407. }
  408. static int io_flush (lua_State *L) {
  409. IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
  410. FILE *f;
  411. lua_pop(L, 1); /* remove upvalue */
  412. f = gethandle(L, ctrl, 1);
  413. luaL_arg_check(L, f || lua_isnull(L, 1), 1, "invalid file handle");
  414. return pushresult(L, fflush(f) == 0);
  415. }
  416. /* }====================================================== */
  417. /*
  418. ** {======================================================
  419. ** Other O.S. Operations
  420. ** =======================================================
  421. */
  422. static int io_execute (lua_State *L) {
  423. lua_pushnumber(L, system(luaL_check_string(L, 1)));
  424. return 1;
  425. }
  426. static int io_remove (lua_State *L) {
  427. return pushresult(L, remove(luaL_check_string(L, 1)) == 0);
  428. }
  429. static int io_rename (lua_State *L) {
  430. return pushresult(L, rename(luaL_check_string(L, 1),
  431. luaL_check_string(L, 2)) == 0);
  432. }
  433. static int io_tmpname (lua_State *L) {
  434. lua_pushstring(L, tmpnam(NULL));
  435. return 1;
  436. }
  437. static int io_getenv (lua_State *L) {
  438. lua_pushstring(L, getenv(luaL_check_string(L, 1))); /* if NULL push nil */
  439. return 1;
  440. }
  441. static int io_clock (lua_State *L) {
  442. lua_pushnumber(L, ((double)clock())/CLOCKS_PER_SEC);
  443. return 1;
  444. }
  445. static int io_date (lua_State *L) {
  446. char b[256];
  447. const char *s = luaL_opt_string(L, 1, "%c");
  448. struct tm *stm;
  449. time_t t;
  450. time(&t); stm = localtime(&t);
  451. if (strftime(b, sizeof(b), s, stm))
  452. lua_pushstring(L, b);
  453. else
  454. lua_error(L, "invalid `date' format");
  455. return 1;
  456. }
  457. static int setloc (lua_State *L) {
  458. static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
  459. LC_NUMERIC, LC_TIME};
  460. static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
  461. "numeric", "time", NULL};
  462. int op = luaL_findstring(luaL_opt_string(L, 2, "all"), catnames);
  463. luaL_arg_check(L, op != -1, 2, "invalid option");
  464. lua_pushstring(L, setlocale(cat[op], luaL_check_string(L, 1)));
  465. return 1;
  466. }
  467. static int io_exit (lua_State *L) {
  468. exit(luaL_opt_int(L, 1, EXIT_SUCCESS));
  469. return 0; /* to avoid warnings */
  470. }
  471. /* }====================================================== */
  472. static int io_debug (lua_State *L) {
  473. for (;;) {
  474. char buffer[250];
  475. fprintf(stderr, "lua_debug> ");
  476. if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
  477. strcmp(buffer, "cont\n") == 0)
  478. return 0;
  479. lua_dostring(L, buffer);
  480. lua_settop(L, 0); /* remove eventual returns */
  481. }
  482. }
  483. #define LEVELS1 12 /* size of the first part of the stack */
  484. #define LEVELS2 10 /* size of the second part of the stack */
  485. static int errorfb (lua_State *L) {
  486. int level = 1; /* skip level 0 (it's this function) */
  487. int firstpart = 1; /* still before eventual `...' */
  488. lua_Debug ar;
  489. luaL_Buffer b;
  490. luaL_buffinit(L, &b);
  491. luaL_addstring(&b, "error: ");
  492. luaL_addstring(&b, luaL_check_string(L, 1));
  493. luaL_addstring(&b, "\n");
  494. while (lua_getstack(L, level++, &ar)) {
  495. char buff[120]; /* enough to fit following `sprintf's */
  496. if (level == 2)
  497. luaL_addstring(&b, "stack traceback:\n");
  498. else if (level > LEVELS1 && firstpart) {
  499. /* no more than `LEVELS2' more levels? */
  500. if (!lua_getstack(L, level+LEVELS2, &ar))
  501. level--; /* keep going */
  502. else {
  503. luaL_addstring(&b, " ...\n"); /* too many levels */
  504. while (lua_getstack(L, level+LEVELS2, &ar)) /* find last levels */
  505. level++;
  506. }
  507. firstpart = 0;
  508. continue;
  509. }
  510. sprintf(buff, "%4d: ", level-1);
  511. luaL_addstring(&b, buff);
  512. lua_getinfo(L, "Snl", &ar);
  513. switch (*ar.namewhat) {
  514. case 'g': case 'l': /* global, local */
  515. sprintf(buff, "function `%.50s'", ar.name);
  516. break;
  517. case 'f': /* field */
  518. sprintf(buff, "method `%.50s'", ar.name);
  519. break;
  520. case 't': /* tag method */
  521. sprintf(buff, "`%.50s' tag method", ar.name);
  522. break;
  523. default: {
  524. if (*ar.what == 'm') /* main? */
  525. sprintf(buff, "main of %.70s", ar.short_src);
  526. else if (*ar.what == 'C') /* C function? */
  527. sprintf(buff, "%.70s", ar.short_src);
  528. else
  529. sprintf(buff, "function <%d:%.70s>", ar.linedefined, ar.short_src);
  530. ar.source = NULL; /* do not print source again */
  531. }
  532. }
  533. luaL_addstring(&b, buff);
  534. if (ar.currentline > 0) {
  535. sprintf(buff, " at line %d", ar.currentline);
  536. luaL_addstring(&b, buff);
  537. }
  538. if (ar.source) {
  539. sprintf(buff, " [%.70s]", ar.short_src);
  540. luaL_addstring(&b, buff);
  541. }
  542. luaL_addstring(&b, "\n");
  543. }
  544. luaL_pushresult(&b);
  545. lua_getglobal(L, LUA_ALERT);
  546. if (lua_isfunction(L, -1)) { /* avoid loop if _ALERT is not defined */
  547. lua_pushvalue(L, -2); /* error message */
  548. lua_call(L, 1, 0);
  549. }
  550. return 0;
  551. }
  552. static const struct luaL_reg iolib[] = {
  553. {LUA_ERRORMESSAGE, errorfb},
  554. {"clock", io_clock},
  555. {"date", io_date},
  556. {"debug", io_debug},
  557. {"execute", io_execute},
  558. {"exit", io_exit},
  559. {"getenv", io_getenv},
  560. {"remove", io_remove},
  561. {"rename", io_rename},
  562. {"setlocale", setloc},
  563. {"tmpname", io_tmpname}
  564. };
  565. static const struct luaL_reg iolibtag[] = {
  566. {"appendto", io_appendto},
  567. {"closefile", io_close},
  568. {"flush", io_flush},
  569. {"openfile", io_open},
  570. {"read", io_read},
  571. {"readfrom", io_readfrom},
  572. {"seek", io_seek},
  573. {"write", io_write},
  574. {"writeto", io_writeto}
  575. };
  576. static void openwithcontrol (lua_State *L) {
  577. IOCtrl *ctrl = (IOCtrl *)malloc(sizeof(IOCtrl));
  578. unsigned int i;
  579. int ctrltag = lua_newtag(L);
  580. ctrl->iotag = lua_newtag(L);
  581. ctrl->closedtag = lua_newtag(L);
  582. for (i=0; i<sizeof(iolibtag)/sizeof(iolibtag[0]); i++) {
  583. /* put `ctrl' as upvalue for these functions */
  584. lua_pushusertag(L, ctrl, ctrltag);
  585. lua_pushcclosure(L, iolibtag[i].func, 1);
  586. lua_setglobal(L, iolibtag[i].name);
  587. }
  588. /* create references to variable names */
  589. lua_pushstring(L, filenames[INFILE]);
  590. ctrl->ref[INFILE] = lua_ref(L, 1);
  591. lua_pushstring(L, filenames[OUTFILE]);
  592. ctrl->ref[OUTFILE] = lua_ref(L, 1);
  593. /* predefined file handles */
  594. setfile(L, ctrl, stdin, INFILE);
  595. setfile(L, ctrl, stdout, OUTFILE);
  596. setfilebyname(L, ctrl, stdin, "_STDIN");
  597. setfilebyname(L, ctrl, stdout, "_STDOUT");
  598. setfilebyname(L, ctrl, stderr, "_STDERR");
  599. /* delete `ctrl' when collected */
  600. lua_pushusertag(L, ctrl, ctrltag);
  601. lua_pushcclosure(L, file_collect, 1);
  602. lua_settagmethod(L, ctrltag, "gc");
  603. /* close files when collected */
  604. lua_copytagmethods(L, ctrl->iotag, ctrltag);
  605. }
  606. void lua_iolibopen (lua_State *L) {
  607. luaL_openl(L, iolib);
  608. openwithcontrol(L);
  609. }