liolib.c 19 KB

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