9
3

liolib.c 21 KB

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