您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

772 行
20 KiB

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