liolib.c 22 KB

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