liolib.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. /*
  2. ** $Id: liolib.c,v 2.124 2014/05/15 15:21:06 roberto Exp $
  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];
  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. return 0; /* fail */
  287. else {
  288. rn->buff[rn->n++] = rn->c; /* save current char */
  289. rn->c = l_getc(rn->f); /* read next one */
  290. return 1;
  291. }
  292. }
  293. /*
  294. ** Accept current char if it is in 'set' (of size 1 or 2)
  295. */
  296. static int test2 (RN *rn, const char *set) {
  297. if (rn->c == set[0] || (rn->c == set[1] && rn->c != '\0'))
  298. return nextc(rn);
  299. else return 0;
  300. }
  301. /*
  302. ** Read a sequence of (hexa)digits
  303. */
  304. static int readdigits (RN *rn, int hexa) {
  305. int count = 0;
  306. while ((hexa ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
  307. count++;
  308. return count;
  309. }
  310. /* access to locale "radix character" (decimal point) */
  311. #if !defined(getlocaledecpoint)
  312. #define getlocaledecpoint() (localeconv()->decimal_point[0])
  313. #endif
  314. /*
  315. ** Read a number: first reads a valid prefix of a numeral into a buffer.
  316. ** Then it calls 'lua_strtonum' to check whether the format is correct
  317. ** and to convert it to a Lua number
  318. */
  319. static int read_number (lua_State *L, FILE *f) {
  320. RN rn;
  321. int count = 0;
  322. int hexa = 0;
  323. char decp[2] = ".";
  324. rn.f = f; rn.n = 0;
  325. decp[0] = getlocaledecpoint(); /* get decimal point from locale */
  326. l_lockfile(rn.f);
  327. do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */
  328. test2(&rn, "-+"); /* optional signal */
  329. if (test2(&rn, "0")) {
  330. if (test2(&rn, "xX")) hexa = 1; /* numeral is hexadecimal */
  331. else count = 1; /* count initial '0' as a valid digit */
  332. }
  333. count += readdigits(&rn, hexa); /* integral part */
  334. if (test2(&rn, decp)) /* decimal point? */
  335. count += readdigits(&rn, hexa); /* fractionary part */
  336. if (count > 0 && test2(&rn, (hexa ? "pP" : "eE"))) { /* exponent mark? */
  337. test2(&rn, "-+"); /* exponent signal */
  338. readdigits(&rn, 0); /* exponent digits */
  339. }
  340. ungetc(rn.c, rn.f); /* unread look-ahead char */
  341. l_unlockfile(rn.f);
  342. rn.buff[rn.n] = '\0'; /* finish string */
  343. if (lua_strtonum(L, rn.buff)) /* is this a valid number? */
  344. return 1; /* ok */
  345. else { /* invalid format */
  346. lua_pushnil(L); /* "result" to be removed */
  347. return 0; /* read fails */
  348. }
  349. }
  350. static int test_eof (lua_State *L, FILE *f) {
  351. int c = getc(f);
  352. ungetc(c, f); /* no-op when c == EOF */
  353. lua_pushlstring(L, NULL, 0);
  354. return (c != EOF);
  355. }
  356. static int read_line (lua_State *L, FILE *f, int chop) {
  357. luaL_Buffer b;
  358. int c;
  359. luaL_buffinit(L, &b);
  360. l_lockfile(f);
  361. while ((c = l_getc(f)) != EOF && c != '\n')
  362. luaL_addchar(&b, c);
  363. l_unlockfile(f);
  364. if (!chop && c == '\n') luaL_addchar(&b, c);
  365. luaL_pushresult(&b); /* close buffer */
  366. return (c == '\n' || lua_rawlen(L, -1) > 0);
  367. }
  368. static void read_all (lua_State *L, FILE *f) {
  369. size_t nr;
  370. luaL_Buffer b;
  371. luaL_buffinit(L, &b);
  372. do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
  373. char *p = luaL_prepbuffsize(&b, LUAL_BUFFERSIZE);
  374. nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
  375. luaL_addsize(&b, nr);
  376. } while (nr == LUAL_BUFFERSIZE);
  377. luaL_pushresult(&b); /* close buffer */
  378. }
  379. static int read_chars (lua_State *L, FILE *f, size_t n) {
  380. size_t nr; /* number of chars actually read */
  381. char *p;
  382. luaL_Buffer b;
  383. luaL_buffinit(L, &b);
  384. p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
  385. nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
  386. luaL_addsize(&b, nr);
  387. luaL_pushresult(&b); /* close buffer */
  388. return (nr > 0); /* true iff read something */
  389. }
  390. static int g_read (lua_State *L, FILE *f, int first) {
  391. int nargs = lua_gettop(L) - 1;
  392. int success;
  393. int n;
  394. clearerr(f);
  395. if (nargs == 0) { /* no arguments? */
  396. success = read_line(L, f, 1);
  397. n = first+1; /* to return 1 result */
  398. }
  399. else { /* ensure stack space for all results and for auxlib's buffer */
  400. luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
  401. success = 1;
  402. for (n = first; nargs-- && success; n++) {
  403. if (lua_type(L, n) == LUA_TNUMBER) {
  404. size_t l = (size_t)lua_tointeger(L, n);
  405. success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
  406. }
  407. else {
  408. const char *p = luaL_checkstring(L, n);
  409. if (*p == '*') p++; /* skip optional '*' (for compatibility) */
  410. switch (*p) {
  411. case 'n': /* number */
  412. success = read_number(L, f);
  413. break;
  414. case 'l': /* line */
  415. success = read_line(L, f, 1);
  416. break;
  417. case 'L': /* line with end-of-line */
  418. success = read_line(L, f, 0);
  419. break;
  420. case 'a': /* file */
  421. read_all(L, f); /* read entire file */
  422. success = 1; /* always success */
  423. break;
  424. default:
  425. return luaL_argerror(L, n, "invalid format");
  426. }
  427. }
  428. }
  429. }
  430. if (ferror(f))
  431. return luaL_fileresult(L, 0, NULL);
  432. if (!success) {
  433. lua_pop(L, 1); /* remove last result */
  434. lua_pushnil(L); /* push nil instead */
  435. }
  436. return n - first;
  437. }
  438. static int io_read (lua_State *L) {
  439. return g_read(L, getiofile(L, IO_INPUT), 1);
  440. }
  441. static int f_read (lua_State *L) {
  442. return g_read(L, tofile(L), 2);
  443. }
  444. static int io_readline (lua_State *L) {
  445. LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
  446. int i;
  447. int n = (int)lua_tointeger(L, lua_upvalueindex(2));
  448. if (isclosed(p)) /* file is already closed? */
  449. return luaL_error(L, "file is already closed");
  450. lua_settop(L , 1);
  451. luaL_checkstack(L, n, "too many arguments");
  452. for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
  453. lua_pushvalue(L, lua_upvalueindex(3 + i));
  454. n = g_read(L, p->f, 2); /* 'n' is number of results */
  455. lua_assert(n > 0); /* should return at least a nil */
  456. if (!lua_isnil(L, -n)) /* read at least one value? */
  457. return n; /* return them */
  458. else { /* first result is nil: EOF or error */
  459. if (n > 1) { /* is there error information? */
  460. /* 2nd result is error message */
  461. return luaL_error(L, "%s", lua_tostring(L, -n + 1));
  462. }
  463. if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
  464. lua_settop(L, 0);
  465. lua_pushvalue(L, lua_upvalueindex(1));
  466. aux_close(L); /* close it */
  467. }
  468. return 0;
  469. }
  470. }
  471. /* }====================================================== */
  472. static int g_write (lua_State *L, FILE *f, int arg) {
  473. int nargs = lua_gettop(L) - arg;
  474. int status = 1;
  475. for (; nargs--; arg++) {
  476. if (lua_type(L, arg) == LUA_TNUMBER) {
  477. /* optimization: could be done exactly as for strings */
  478. int len = lua_isinteger(L, arg)
  479. ? fprintf(f, LUA_INTEGER_FMT, lua_tointeger(L, arg))
  480. : fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg));
  481. status = status && (len > 0);
  482. }
  483. else {
  484. size_t l;
  485. const char *s = luaL_checklstring(L, arg, &l);
  486. status = status && (fwrite(s, sizeof(char), l, f) == l);
  487. }
  488. }
  489. if (status) return 1; /* file handle already on stack top */
  490. else return luaL_fileresult(L, status, NULL);
  491. }
  492. static int io_write (lua_State *L) {
  493. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  494. }
  495. static int f_write (lua_State *L) {
  496. FILE *f = tofile(L);
  497. lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
  498. return g_write(L, f, 2);
  499. }
  500. static int f_seek (lua_State *L) {
  501. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  502. static const char *const modenames[] = {"set", "cur", "end", NULL};
  503. FILE *f = tofile(L);
  504. int op = luaL_checkoption(L, 2, "cur", modenames);
  505. lua_Integer p3 = luaL_optinteger(L, 3, 0);
  506. l_seeknum offset = (l_seeknum)p3;
  507. luaL_argcheck(L, (lua_Integer)offset == p3, 3,
  508. "not an integer in proper range");
  509. op = l_fseek(f, offset, mode[op]);
  510. if (op)
  511. return luaL_fileresult(L, 0, NULL); /* error */
  512. else {
  513. lua_pushinteger(L, (lua_Integer)l_ftell(f));
  514. return 1;
  515. }
  516. }
  517. static int f_setvbuf (lua_State *L) {
  518. static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
  519. static const char *const modenames[] = {"no", "full", "line", NULL};
  520. FILE *f = tofile(L);
  521. int op = luaL_checkoption(L, 2, NULL, modenames);
  522. lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
  523. int res = setvbuf(f, NULL, mode[op], sz);
  524. return luaL_fileresult(L, res == 0, NULL);
  525. }
  526. static int io_flush (lua_State *L) {
  527. return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
  528. }
  529. static int f_flush (lua_State *L) {
  530. return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
  531. }
  532. /*
  533. ** functions for 'io' library
  534. */
  535. static const luaL_Reg iolib[] = {
  536. {"close", io_close},
  537. {"flush", io_flush},
  538. {"input", io_input},
  539. {"lines", io_lines},
  540. {"open", io_open},
  541. {"output", io_output},
  542. {"popen", io_popen},
  543. {"read", io_read},
  544. {"tmpfile", io_tmpfile},
  545. {"type", io_type},
  546. {"write", io_write},
  547. {NULL, NULL}
  548. };
  549. /*
  550. ** methods for file handles
  551. */
  552. static const luaL_Reg flib[] = {
  553. {"close", io_close},
  554. {"flush", f_flush},
  555. {"lines", f_lines},
  556. {"read", f_read},
  557. {"seek", f_seek},
  558. {"setvbuf", f_setvbuf},
  559. {"write", f_write},
  560. {"__gc", f_gc},
  561. {"__tostring", f_tostring},
  562. {NULL, NULL}
  563. };
  564. static void createmeta (lua_State *L) {
  565. luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
  566. lua_pushvalue(L, -1); /* push metatable */
  567. lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
  568. luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */
  569. lua_pop(L, 1); /* pop new metatable */
  570. }
  571. /*
  572. ** function to (not) close the standard files stdin, stdout, and stderr
  573. */
  574. static int io_noclose (lua_State *L) {
  575. LStream *p = tolstream(L);
  576. p->closef = &io_noclose; /* keep file opened */
  577. lua_pushnil(L);
  578. lua_pushliteral(L, "cannot close standard file");
  579. return 2;
  580. }
  581. static void createstdfile (lua_State *L, FILE *f, const char *k,
  582. const char *fname) {
  583. LStream *p = newprefile(L);
  584. p->f = f;
  585. p->closef = &io_noclose;
  586. if (k != NULL) {
  587. lua_pushvalue(L, -1);
  588. lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
  589. }
  590. lua_setfield(L, -2, fname); /* add file to module */
  591. }
  592. LUAMOD_API int luaopen_io (lua_State *L) {
  593. luaL_newlib(L, iolib); /* new module */
  594. createmeta(L);
  595. /* create (and set) default files */
  596. createstdfile(L, stdin, IO_INPUT, "stdin");
  597. createstdfile(L, stdout, IO_OUTPUT, "stdout");
  598. createstdfile(L, stderr, NULL, "stderr");
  599. return 1;
  600. }