liolib.c 19 KB

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