liolib.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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. errno = 0;
  179. return luaL_fileresult(L, (fclose(p->f) == 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. errno = 0;
  200. p->f = fopen(filename, mode);
  201. return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
  202. }
  203. /*
  204. ** function to close 'popen' files
  205. */
  206. static int io_pclose (lua_State *L) {
  207. LStream *p = tolstream(L);
  208. errno = 0;
  209. return luaL_execresult(L, l_pclose(L, p->f));
  210. }
  211. static int io_popen (lua_State *L) {
  212. const char *filename = luaL_checkstring(L, 1);
  213. const char *mode = luaL_optstring(L, 2, "r");
  214. LStream *p = newprefile(L);
  215. luaL_argcheck(L, l_checkmodep(mode), 2, "invalid mode");
  216. errno = 0;
  217. p->f = l_popen(L, filename, mode);
  218. p->closef = &io_pclose;
  219. return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
  220. }
  221. static int io_tmpfile (lua_State *L) {
  222. LStream *p = newfile(L);
  223. errno = 0;
  224. p->f = tmpfile();
  225. return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
  226. }
  227. static FILE *getiofile (lua_State *L, const char *findex) {
  228. LStream *p;
  229. lua_getfield(L, LUA_REGISTRYINDEX, findex);
  230. p = (LStream *)lua_touserdata(L, -1);
  231. if (l_unlikely(isclosed(p)))
  232. luaL_error(L, "default %s file is closed", findex + IOPREF_LEN);
  233. return p->f;
  234. }
  235. static int g_iofile (lua_State *L, const char *f, const char *mode) {
  236. if (!lua_isnoneornil(L, 1)) {
  237. const char *filename = lua_tostring(L, 1);
  238. if (filename)
  239. opencheck(L, filename, mode);
  240. else {
  241. tofile(L); /* check that it's a valid file handle */
  242. lua_pushvalue(L, 1);
  243. }
  244. lua_setfield(L, LUA_REGISTRYINDEX, f);
  245. }
  246. /* return current value */
  247. lua_getfield(L, LUA_REGISTRYINDEX, f);
  248. return 1;
  249. }
  250. static int io_input (lua_State *L) {
  251. return g_iofile(L, IO_INPUT, "r");
  252. }
  253. static int io_output (lua_State *L) {
  254. return g_iofile(L, IO_OUTPUT, "w");
  255. }
  256. static int io_readline (lua_State *L);
  257. /*
  258. ** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit
  259. ** in the limit for upvalues of a closure)
  260. */
  261. #define MAXARGLINE 250
  262. /*
  263. ** Auxiliary function to create the iteration function for 'lines'.
  264. ** The iteration function is a closure over 'io_readline', with
  265. ** the following upvalues:
  266. ** 1) The file being read (first value in the stack)
  267. ** 2) the number of arguments to read
  268. ** 3) a boolean, true iff file has to be closed when finished ('toclose')
  269. ** *) a variable number of format arguments (rest of the stack)
  270. */
  271. static void aux_lines (lua_State *L, int toclose) {
  272. int n = lua_gettop(L) - 1; /* number of arguments to read */
  273. luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments");
  274. lua_pushvalue(L, 1); /* file */
  275. lua_pushinteger(L, n); /* number of arguments to read */
  276. lua_pushboolean(L, toclose); /* close/not close file when finished */
  277. lua_rotate(L, 2, 3); /* move the three values to their positions */
  278. lua_pushcclosure(L, io_readline, 3 + n);
  279. }
  280. static int f_lines (lua_State *L) {
  281. tofile(L); /* check that it's a valid file handle */
  282. aux_lines(L, 0);
  283. return 1;
  284. }
  285. /*
  286. ** Return an iteration function for 'io.lines'. If file has to be
  287. ** closed, also returns the file itself as a second result (to be
  288. ** closed as the state at the exit of a generic for).
  289. */
  290. static int io_lines (lua_State *L) {
  291. int toclose;
  292. if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
  293. if (lua_isnil(L, 1)) { /* no file name? */
  294. lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */
  295. lua_replace(L, 1); /* put it at index 1 */
  296. tofile(L); /* check that it's a valid file handle */
  297. toclose = 0; /* do not close it after iteration */
  298. }
  299. else { /* open a new file */
  300. const char *filename = luaL_checkstring(L, 1);
  301. opencheck(L, filename, "r");
  302. lua_replace(L, 1); /* put file at index 1 */
  303. toclose = 1; /* close it after iteration */
  304. }
  305. aux_lines(L, toclose); /* push iteration function */
  306. if (toclose) {
  307. lua_pushnil(L); /* state */
  308. lua_pushnil(L); /* control */
  309. lua_pushvalue(L, 1); /* file is the to-be-closed variable (4th result) */
  310. return 4;
  311. }
  312. else
  313. return 1;
  314. }
  315. /*
  316. ** {======================================================
  317. ** READ
  318. ** =======================================================
  319. */
  320. /* maximum length of a numeral */
  321. #if !defined (L_MAXLENNUM)
  322. #define L_MAXLENNUM 200
  323. #endif
  324. /* auxiliary structure used by 'read_number' */
  325. typedef struct {
  326. FILE *f; /* file being read */
  327. int c; /* current character (look ahead) */
  328. int n; /* number of elements in buffer 'buff' */
  329. char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */
  330. } RN;
  331. /*
  332. ** Add current char to buffer (if not out of space) and read next one
  333. */
  334. static int nextc (RN *rn) {
  335. if (l_unlikely(rn->n >= L_MAXLENNUM)) { /* buffer overflow? */
  336. rn->buff[0] = '\0'; /* invalidate result */
  337. return 0; /* fail */
  338. }
  339. else {
  340. rn->buff[rn->n++] = rn->c; /* save current char */
  341. rn->c = l_getc(rn->f); /* read next one */
  342. return 1;
  343. }
  344. }
  345. /*
  346. ** Accept current char if it is in 'set' (of size 2)
  347. */
  348. static int test2 (RN *rn, const char *set) {
  349. if (rn->c == set[0] || rn->c == set[1])
  350. return nextc(rn);
  351. else return 0;
  352. }
  353. /*
  354. ** Read a sequence of (hex)digits
  355. */
  356. static int readdigits (RN *rn, int hex) {
  357. int count = 0;
  358. while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
  359. count++;
  360. return count;
  361. }
  362. /*
  363. ** Read a number: first reads a valid prefix of a numeral into a buffer.
  364. ** Then it calls 'lua_stringtonumber' to check whether the format is
  365. ** correct and to convert it to a Lua number.
  366. */
  367. static int read_number (lua_State *L, FILE *f) {
  368. RN rn;
  369. int count = 0;
  370. int hex = 0;
  371. char decp[2];
  372. rn.f = f; rn.n = 0;
  373. decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
  374. decp[1] = '.'; /* always accept a dot */
  375. l_lockfile(rn.f);
  376. do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */
  377. test2(&rn, "-+"); /* optional sign */
  378. if (test2(&rn, "00")) {
  379. if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */
  380. else count = 1; /* count initial '0' as a valid digit */
  381. }
  382. count += readdigits(&rn, hex); /* integral part */
  383. if (test2(&rn, decp)) /* decimal point? */
  384. count += readdigits(&rn, hex); /* fractional part */
  385. if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */
  386. test2(&rn, "-+"); /* exponent sign */
  387. readdigits(&rn, 0); /* exponent digits */
  388. }
  389. ungetc(rn.c, rn.f); /* unread look-ahead char */
  390. l_unlockfile(rn.f);
  391. rn.buff[rn.n] = '\0'; /* finish string */
  392. if (l_likely(lua_stringtonumber(L, rn.buff)))
  393. return 1; /* ok, it is a valid number */
  394. else { /* invalid format */
  395. lua_pushnil(L); /* "result" to be removed */
  396. return 0; /* read fails */
  397. }
  398. }
  399. static int test_eof (lua_State *L, FILE *f) {
  400. int c = getc(f);
  401. ungetc(c, f); /* no-op when c == EOF */
  402. lua_pushliteral(L, "");
  403. return (c != EOF);
  404. }
  405. static int read_line (lua_State *L, FILE *f, int chop) {
  406. luaL_Buffer b;
  407. int c;
  408. luaL_buffinit(L, &b);
  409. do { /* may need to read several chunks to get whole line */
  410. char *buff = luaL_prepbuffer(&b); /* preallocate buffer space */
  411. int i = 0;
  412. l_lockfile(f); /* no memory errors can happen inside the lock */
  413. while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
  414. buff[i++] = c; /* read up to end of line or buffer limit */
  415. l_unlockfile(f);
  416. luaL_addsize(&b, i);
  417. } while (c != EOF && c != '\n'); /* repeat until end of line */
  418. if (!chop && c == '\n') /* want a newline and have one? */
  419. luaL_addchar(&b, c); /* add ending newline to result */
  420. luaL_pushresult(&b); /* close buffer */
  421. /* return ok if read something (either a newline or something else) */
  422. return (c == '\n' || lua_rawlen(L, -1) > 0);
  423. }
  424. static void read_all (lua_State *L, FILE *f) {
  425. size_t nr;
  426. luaL_Buffer b;
  427. luaL_buffinit(L, &b);
  428. do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
  429. char *p = luaL_prepbuffer(&b);
  430. nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
  431. luaL_addsize(&b, nr);
  432. } while (nr == LUAL_BUFFERSIZE);
  433. luaL_pushresult(&b); /* close buffer */
  434. }
  435. static int read_chars (lua_State *L, FILE *f, size_t n) {
  436. size_t nr; /* number of chars actually read */
  437. char *p;
  438. luaL_Buffer b;
  439. luaL_buffinit(L, &b);
  440. p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
  441. nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
  442. luaL_addsize(&b, nr);
  443. luaL_pushresult(&b); /* close buffer */
  444. return (nr > 0); /* true iff read something */
  445. }
  446. static int g_read (lua_State *L, FILE *f, int first) {
  447. int nargs = lua_gettop(L) - 1;
  448. int n, success;
  449. clearerr(f);
  450. errno = 0;
  451. if (nargs == 0) { /* no arguments? */
  452. success = read_line(L, f, 1);
  453. n = first + 1; /* to return 1 result */
  454. }
  455. else {
  456. /* ensure stack space for all results and for auxlib's buffer */
  457. luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
  458. success = 1;
  459. for (n = first; nargs-- && success; n++) {
  460. if (lua_type(L, n) == LUA_TNUMBER) {
  461. size_t l = (size_t)luaL_checkinteger(L, n);
  462. success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
  463. }
  464. else {
  465. const char *p = luaL_checkstring(L, n);
  466. if (*p == '*') p++; /* skip optional '*' (for compatibility) */
  467. switch (*p) {
  468. case 'n': /* number */
  469. success = read_number(L, f);
  470. break;
  471. case 'l': /* line */
  472. success = read_line(L, f, 1);
  473. break;
  474. case 'L': /* line with end-of-line */
  475. success = read_line(L, f, 0);
  476. break;
  477. case 'a': /* file */
  478. read_all(L, f); /* read entire file */
  479. success = 1; /* always success */
  480. break;
  481. default:
  482. return luaL_argerror(L, n, "invalid format");
  483. }
  484. }
  485. }
  486. }
  487. if (ferror(f))
  488. return luaL_fileresult(L, 0, NULL);
  489. if (!success) {
  490. lua_pop(L, 1); /* remove last result */
  491. luaL_pushfail(L); /* push nil instead */
  492. }
  493. return n - first;
  494. }
  495. static int io_read (lua_State *L) {
  496. return g_read(L, getiofile(L, IO_INPUT), 1);
  497. }
  498. static int f_read (lua_State *L) {
  499. return g_read(L, tofile(L), 2);
  500. }
  501. /*
  502. ** Iteration function for 'lines'.
  503. */
  504. static int io_readline (lua_State *L) {
  505. LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
  506. int i;
  507. int n = (int)lua_tointeger(L, lua_upvalueindex(2));
  508. if (isclosed(p)) /* file is already closed? */
  509. return luaL_error(L, "file is already closed");
  510. lua_settop(L , 1);
  511. luaL_checkstack(L, n, "too many arguments");
  512. for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
  513. lua_pushvalue(L, lua_upvalueindex(3 + i));
  514. n = g_read(L, p->f, 2); /* 'n' is number of results */
  515. lua_assert(n > 0); /* should return at least a nil */
  516. if (lua_toboolean(L, -n)) /* read at least one value? */
  517. return n; /* return them */
  518. else { /* first result is false: EOF or error */
  519. if (n > 1) { /* is there error information? */
  520. /* 2nd result is error message */
  521. return luaL_error(L, "%s", lua_tostring(L, -n + 1));
  522. }
  523. if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
  524. lua_settop(L, 0); /* clear stack */
  525. lua_pushvalue(L, lua_upvalueindex(1)); /* push file at index 1 */
  526. aux_close(L); /* close it */
  527. }
  528. return 0;
  529. }
  530. }
  531. /* }====================================================== */
  532. static int g_write (lua_State *L, FILE *f, int arg) {
  533. int nargs = lua_gettop(L) - arg;
  534. int status = 1;
  535. errno = 0;
  536. for (; nargs--; arg++) {
  537. if (lua_type(L, arg) == LUA_TNUMBER) {
  538. /* optimization: could be done exactly as for strings */
  539. int len = lua_isinteger(L, arg)
  540. ? fprintf(f, LUA_INTEGER_FMT,
  541. (LUAI_UACINT)lua_tointeger(L, arg))
  542. : fprintf(f, LUA_NUMBER_FMT,
  543. (LUAI_UACNUMBER)lua_tonumber(L, arg));
  544. status = status && (len > 0);
  545. }
  546. else {
  547. size_t l;
  548. const char *s = luaL_checklstring(L, arg, &l);
  549. status = status && (fwrite(s, sizeof(char), l, f) == l);
  550. }
  551. }
  552. if (l_likely(status))
  553. return 1; /* file handle already on stack top */
  554. else
  555. return luaL_fileresult(L, status, NULL);
  556. }
  557. static int io_write (lua_State *L) {
  558. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  559. }
  560. static int f_write (lua_State *L) {
  561. FILE *f = tofile(L);
  562. lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
  563. return g_write(L, f, 2);
  564. }
  565. static int f_seek (lua_State *L) {
  566. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  567. static const char *const modenames[] = {"set", "cur", "end", NULL};
  568. FILE *f = tofile(L);
  569. int op = luaL_checkoption(L, 2, "cur", modenames);
  570. lua_Integer p3 = luaL_optinteger(L, 3, 0);
  571. l_seeknum offset = (l_seeknum)p3;
  572. luaL_argcheck(L, (lua_Integer)offset == p3, 3,
  573. "not an integer in proper range");
  574. errno = 0;
  575. op = l_fseek(f, offset, mode[op]);
  576. if (l_unlikely(op))
  577. return luaL_fileresult(L, 0, NULL); /* error */
  578. else {
  579. lua_pushinteger(L, (lua_Integer)l_ftell(f));
  580. return 1;
  581. }
  582. }
  583. static int f_setvbuf (lua_State *L) {
  584. static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
  585. static const char *const modenames[] = {"no", "full", "line", NULL};
  586. FILE *f = tofile(L);
  587. int op = luaL_checkoption(L, 2, NULL, modenames);
  588. lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
  589. int res;
  590. errno = 0;
  591. res = setvbuf(f, NULL, mode[op], (size_t)sz);
  592. return luaL_fileresult(L, res == 0, NULL);
  593. }
  594. static int io_flush (lua_State *L) {
  595. FILE *f = getiofile(L, IO_OUTPUT);
  596. errno = 0;
  597. return luaL_fileresult(L, fflush(f) == 0, NULL);
  598. }
  599. static int f_flush (lua_State *L) {
  600. FILE *f = tofile(L);
  601. errno = 0;
  602. return luaL_fileresult(L, fflush(f) == 0, NULL);
  603. }
  604. /*
  605. ** functions for 'io' library
  606. */
  607. static const luaL_Reg iolib[] = {
  608. {"close", io_close},
  609. {"flush", io_flush},
  610. {"input", io_input},
  611. {"lines", io_lines},
  612. {"open", io_open},
  613. {"output", io_output},
  614. {"popen", io_popen},
  615. {"read", io_read},
  616. {"tmpfile", io_tmpfile},
  617. {"type", io_type},
  618. {"write", io_write},
  619. {NULL, NULL}
  620. };
  621. /*
  622. ** methods for file handles
  623. */
  624. static const luaL_Reg meth[] = {
  625. {"read", f_read},
  626. {"write", f_write},
  627. {"lines", f_lines},
  628. {"flush", f_flush},
  629. {"seek", f_seek},
  630. {"close", f_close},
  631. {"setvbuf", f_setvbuf},
  632. {NULL, NULL}
  633. };
  634. /*
  635. ** metamethods for file handles
  636. */
  637. static const luaL_Reg metameth[] = {
  638. {"__index", NULL}, /* placeholder */
  639. {"__gc", f_gc},
  640. {"__close", f_gc},
  641. {"__tostring", f_tostring},
  642. {NULL, NULL}
  643. };
  644. static void createmeta (lua_State *L) {
  645. luaL_newmetatable(L, LUA_FILEHANDLE); /* metatable for file handles */
  646. luaL_setfuncs(L, metameth, 0); /* add metamethods to new metatable */
  647. luaL_newlibtable(L, meth); /* create method table */
  648. luaL_setfuncs(L, meth, 0); /* add file methods to method table */
  649. lua_setfield(L, -2, "__index"); /* metatable.__index = method table */
  650. lua_pop(L, 1); /* pop metatable */
  651. }
  652. /*
  653. ** function to (not) close the standard files stdin, stdout, and stderr
  654. */
  655. static int io_noclose (lua_State *L) {
  656. LStream *p = tolstream(L);
  657. p->closef = &io_noclose; /* keep file opened */
  658. luaL_pushfail(L);
  659. lua_pushliteral(L, "cannot close standard file");
  660. return 2;
  661. }
  662. static void createstdfile (lua_State *L, FILE *f, const char *k,
  663. const char *fname) {
  664. LStream *p = newprefile(L);
  665. p->f = f;
  666. p->closef = &io_noclose;
  667. if (k != NULL) {
  668. lua_pushvalue(L, -1);
  669. lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
  670. }
  671. lua_setfield(L, -2, fname); /* add file to module */
  672. }
  673. LUAMOD_API int luaopen_io (lua_State *L) {
  674. luaL_newlib(L, iolib); /* new module */
  675. createmeta(L);
  676. /* create (and set) default files */
  677. createstdfile(L, stdin, IO_INPUT, "stdin");
  678. createstdfile(L, stdout, IO_OUTPUT, "stdout");
  679. createstdfile(L, stderr, NULL, "stderr");
  680. return 1;
  681. }