liolib.c 22 KB

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