iolib.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. /*
  2. ** iolib.c
  3. ** Input/output library to LUA
  4. */
  5. char *rcs_iolib="$Id: iolib.c,v 1.43 1996/04/30 21:13:55 roberto Exp roberto $";
  6. #include <stdio.h>
  7. #include <ctype.h>
  8. #include <string.h>
  9. #include <time.h>
  10. #include <stdlib.h>
  11. #include <errno.h>
  12. #include "lua.h"
  13. #include "luadebug.h"
  14. #include "lualib.h"
  15. static FILE *in=stdin, *out=stdout;
  16. #ifdef POPEN
  17. FILE *popen();
  18. int pclose();
  19. #else
  20. #define popen(x,y) NULL /* that is, popen always fails */
  21. #define pclose(x) (-1)
  22. #endif
  23. static void pushresult (int i)
  24. {
  25. if (i)
  26. lua_pushnumber (1);
  27. else
  28. lua_pushnil();
  29. }
  30. static void closeread (void)
  31. {
  32. if (in != stdin)
  33. {
  34. if (pclose(in) == -1)
  35. fclose(in);
  36. in = stdin;
  37. }
  38. }
  39. static void closewrite (void)
  40. {
  41. if (out != stdout)
  42. {
  43. if (pclose(out) == -1)
  44. fclose(out);
  45. out = stdout;
  46. }
  47. }
  48. /*
  49. ** Open a file to read.
  50. ** LUA interface:
  51. ** status = readfrom (filename)
  52. ** where:
  53. ** status = 1 -> success
  54. ** status = nil -> error
  55. */
  56. static void io_readfrom (void)
  57. {
  58. if (lua_getparam (1) == LUA_NOOBJECT)
  59. { /* restore standart input */
  60. closeread();
  61. lua_pushnumber (1);
  62. }
  63. else
  64. {
  65. char *s = lua_check_string(1, "readfrom");
  66. FILE *fp = (*s == '|') ? popen(s+1, "r") : fopen(s, "r");
  67. if (fp == NULL)
  68. lua_pushnil();
  69. else
  70. {
  71. closeread();
  72. in = fp;
  73. lua_pushnumber (1);
  74. }
  75. }
  76. }
  77. /*
  78. ** Open a file to write.
  79. ** LUA interface:
  80. ** status = writeto (filename)
  81. ** where:
  82. ** status = 1 -> success
  83. ** status = nil -> error
  84. */
  85. static void io_writeto (void)
  86. {
  87. if (lua_getparam (1) == LUA_NOOBJECT) /* restore standart output */
  88. {
  89. closewrite();
  90. lua_pushnumber (1);
  91. }
  92. else
  93. {
  94. char *s = lua_check_string(1, "writeto");
  95. FILE *fp = (*s == '|') ? popen(s+1,"w") : fopen(s,"w");
  96. if (fp == NULL)
  97. lua_pushnil();
  98. else
  99. {
  100. closewrite();
  101. out = fp;
  102. lua_pushnumber (1);
  103. }
  104. }
  105. }
  106. /*
  107. ** Open a file to write appended.
  108. ** LUA interface:
  109. ** status = appendto (filename)
  110. ** where:
  111. ** status = 1 -> success
  112. ** status = nil -> error
  113. */
  114. static void io_appendto (void)
  115. {
  116. char *s = lua_check_string(1, "appendto");
  117. FILE *fp = fopen (s, "a");
  118. if (fp == NULL)
  119. lua_pushnil();
  120. else
  121. {
  122. if (out != stdout) fclose (out);
  123. out = fp;
  124. lua_pushnumber(1);
  125. }
  126. }
  127. static char getformat (char *f, int *just, int *m, int *n)
  128. {
  129. int t;
  130. switch (*f++)
  131. {
  132. case 'q': case 'Q':
  133. case 's': case 'S':
  134. case 'i': case 'I':
  135. t = tolower(*(f-1));
  136. break;
  137. case 'f': case 'F': case 'g': case 'G': case 'e': case 'E':
  138. t = 'f';
  139. break;
  140. default:
  141. t = 0; /* to avoid compiler warnings */
  142. lua_arg_error("read/write (format)");
  143. }
  144. *just = (*f == '<' || *f == '>' || *f == '|') ? *f++ : '>';
  145. if (isdigit(*f))
  146. {
  147. *m = 0;
  148. while (isdigit(*f))
  149. *m = *m*10 + (*f++ - '0');
  150. }
  151. else
  152. *m = -1;
  153. if (*f == '.')
  154. {
  155. f++; /* skip point */
  156. *n = 0;
  157. while (isdigit(*f))
  158. *n = *n*10 + (*f++ - '0');
  159. }
  160. else
  161. *n = -1;
  162. return t;
  163. }
  164. /*
  165. ** Read a variable. On error put nil on stack.
  166. ** LUA interface:
  167. ** variable = read ([format])
  168. **
  169. ** O formato pode ter um dos seguintes especificadores:
  170. **
  171. ** s ou S -> para string
  172. ** f ou F, g ou G, e ou E -> para reais
  173. ** i ou I -> para inteiros
  174. **
  175. ** Estes especificadores podem vir seguidos de numero que representa
  176. ** o numero de campos a serem lidos.
  177. */
  178. static int read_until_char (int del)
  179. {
  180. int c;
  181. while((c = fgetc(in)) != EOF && c != del)
  182. luaI_addchar(c);
  183. return c;
  184. }
  185. static void read_until_blank (void)
  186. {
  187. int c;
  188. while((c = fgetc(in)) != EOF && !isspace(c))
  189. luaI_addchar(c);
  190. if (c != EOF) ungetc(c,in);
  191. }
  192. static void read_m (int m)
  193. {
  194. int c;
  195. while (m-- && (c = fgetc(in)) != EOF)
  196. luaI_addchar(c);
  197. }
  198. static void read_free (void)
  199. {
  200. int c;
  201. while (isspace(c=fgetc(in)))
  202. ;
  203. if (c == EOF)
  204. {
  205. lua_pushnil();
  206. return;
  207. }
  208. if (c == '\"' || c == '\'')
  209. { /* string */
  210. c = read_until_char(c);
  211. if (c == EOF)
  212. lua_pushnil();
  213. else
  214. lua_pushstring(luaI_addchar(0));
  215. }
  216. else
  217. {
  218. double d;
  219. char dummy;
  220. char *s;
  221. luaI_addchar(c);
  222. read_until_blank();
  223. s = luaI_addchar(0);
  224. if (sscanf(s, "%lf %c", &d, &dummy) == 1)
  225. lua_pushnumber(d);
  226. else
  227. lua_pushstring(s);
  228. }
  229. }
  230. static void io_read (void)
  231. {
  232. lua_Object o = lua_getparam (1);
  233. luaI_addchar(0); /* initialize buffer */
  234. if (o == LUA_NOOBJECT) /* free format */
  235. read_free();
  236. else /* formatted */
  237. {
  238. int m, dummy1, dummy2;
  239. switch (getformat(lua_check_string(1, "read"), &dummy1, &m, &dummy2))
  240. {
  241. case 's':
  242. {
  243. char *s;
  244. if (m < 0)
  245. read_until_blank();
  246. else
  247. read_m(m);
  248. s = luaI_addchar(0);
  249. if ((m >= 0 && strlen(s) == m) || (m < 0 && strlen(s) > 0))
  250. lua_pushstring(s);
  251. else
  252. lua_pushnil();
  253. break;
  254. }
  255. case 'i': /* can read as float, since it makes no difference to Lua */
  256. case 'f':
  257. {
  258. double d;
  259. int result;
  260. if (m < 0)
  261. result = fscanf(in, "%lf", &d);
  262. else
  263. {
  264. read_m(m);
  265. result = sscanf(luaI_addchar(0), "%lf", &d);
  266. }
  267. if (result == 1)
  268. lua_pushnumber(d);
  269. else
  270. lua_pushnil();
  271. break;
  272. }
  273. default:
  274. lua_arg_error("read (format)");
  275. }
  276. }
  277. }
  278. /*
  279. ** Read characters until a given one. The delimiter is not read.
  280. */
  281. static void io_readuntil (void)
  282. {
  283. int del, c;
  284. lua_Object p = lua_getparam(1);
  285. luaI_addchar(0); /* initialize buffer */
  286. if (p == LUA_NOOBJECT || lua_isnil(p))
  287. del = EOF;
  288. else
  289. del = *lua_check_string(1, "readuntil");
  290. c = read_until_char(del);
  291. if (c != EOF) ungetc(c,in);
  292. lua_pushstring(luaI_addchar(0));
  293. }
  294. /*
  295. ** Write a variable. On error put 0 on stack, otherwise put 1.
  296. ** LUA interface:
  297. ** status = write (variable [,format])
  298. **
  299. ** O formato pode ter um dos seguintes especificadores:
  300. **
  301. ** s ou S -> para string
  302. ** f ou F, g ou G, e ou E -> para reais
  303. ** i ou I -> para inteiros
  304. **
  305. ** Estes especificadores podem vir seguidos de:
  306. **
  307. ** [?][m][.n]
  308. **
  309. ** onde:
  310. ** ? -> indica justificacao
  311. ** < = esquerda
  312. ** | = centro
  313. ** > = direita (default)
  314. ** m -> numero maximo de campos (se exceder estoura)
  315. ** n -> indica precisao para
  316. ** reais -> numero de casas decimais
  317. ** inteiros -> numero minimo de digitos
  318. ** string -> nao se aplica
  319. */
  320. static int write_fill (int n, int c)
  321. {
  322. while (n--)
  323. if (fputc(c, out) == EOF)
  324. return 0;
  325. return 1;
  326. }
  327. static int write_string (char *s, int just, int m)
  328. {
  329. int status;
  330. int l = strlen(s);
  331. int pre; /* number of blanks before string */
  332. if (m < 0) m = l;
  333. else if (l > m)
  334. {
  335. write_fill(m, '*');
  336. return 0;
  337. }
  338. pre = (just == '<') ? 0 : (just == '>') ? m-l : (m-l)/2;
  339. status = write_fill(pre, ' ');
  340. status = status && fprintf(out, "%s", s) >= 0;
  341. status = status && write_fill(m-(l+pre), ' ');
  342. return status;
  343. }
  344. static int write_quoted (int just, int m)
  345. {
  346. luaI_addchar(0);
  347. luaI_addquoted(lua_check_string(1, "write"));
  348. return write_string(luaI_addchar(0), just, m);
  349. }
  350. static int write_float (int just, int m, int n)
  351. {
  352. char buffer[100];
  353. lua_Object p = lua_getparam(1);
  354. float number;
  355. if (!lua_isnumber(p)) return 0;
  356. number = lua_getnumber(p);
  357. if (n >= 0)
  358. sprintf(buffer, "%.*f", n, number);
  359. else
  360. sprintf(buffer, "%g", number);
  361. return write_string(buffer, just, m);
  362. }
  363. static int write_int (int just, int m, int n)
  364. {
  365. char buffer[100];
  366. lua_Object p = lua_getparam(1);
  367. int number;
  368. if (!lua_isnumber(p)) return 0;
  369. number = (int)lua_getnumber(p);
  370. if (n >= 0)
  371. sprintf(buffer, "%.*d", n, number);
  372. else
  373. sprintf(buffer, "%d", number);
  374. return write_string(buffer, just, m);
  375. }
  376. static void io_write (void)
  377. {
  378. int status = 0;
  379. if (lua_getparam (2) == LUA_NOOBJECT) /* free format */
  380. {
  381. lua_Object o1 = lua_getparam(1);
  382. int t = lua_type(o1);
  383. if (t == LUA_T_NUMBER)
  384. status = fprintf (out, "%g", lua_getnumber(o1)) >= 0;
  385. else if (t == LUA_T_STRING)
  386. status = fprintf (out, "%s", lua_getstring(o1)) >= 0;
  387. }
  388. else /* formated */
  389. {
  390. int just, m, n;
  391. switch (getformat(lua_check_string(2, "write"), &just, &m, &n))
  392. {
  393. case 's':
  394. {
  395. lua_Object p = lua_getparam(1);
  396. if (lua_isstring(p))
  397. status = write_string(lua_getstring(p), just, m);
  398. else
  399. status = 0;
  400. break;
  401. }
  402. case 'q':
  403. status = write_quoted(just, m);
  404. break;
  405. case 'f':
  406. status = write_float(just, m, n);
  407. break;
  408. case 'i':
  409. status = write_int(just, m, n);
  410. break;
  411. }
  412. }
  413. if (status)
  414. lua_pushnumber(status);
  415. else
  416. lua_pushnil();
  417. }
  418. /*
  419. ** Execute a executable program using "system".
  420. ** Return the result of execution.
  421. */
  422. static void io_execute (void)
  423. {
  424. lua_pushnumber(system(lua_check_string(1, "execute")));
  425. }
  426. /*
  427. ** Remove a file. On error return nil.
  428. */
  429. static void io_remove (void)
  430. {
  431. pushresult(remove(lua_check_string(1, "remove")) == 0);
  432. }
  433. static void io_rename (void)
  434. {
  435. char *f1 = lua_check_string(1, "rename");
  436. char *f2 = lua_check_string(2, "rename");
  437. pushresult(rename(f1, f2) == 0);
  438. }
  439. static void io_tmpname (void)
  440. {
  441. lua_pushstring(tmpnam(NULL));
  442. }
  443. static void io_errorno (void)
  444. {
  445. /* lua_pushstring(strerror(errno));*/
  446. }
  447. /*
  448. ** To get a environment variable
  449. */
  450. static void io_getenv (void)
  451. {
  452. char *env = getenv(lua_check_string(1, "getenv"));
  453. lua_pushstring(env); /* if NULL push nil */
  454. }
  455. /*
  456. ** Return user formatted time stamp
  457. */
  458. static void io_date (void)
  459. {
  460. time_t t;
  461. struct tm *tm;
  462. char *s;
  463. char b[BUFSIZ];
  464. if (lua_getparam(1) == LUA_NOOBJECT)
  465. s = "%c";
  466. else
  467. s = lua_check_string(1, "date");
  468. time(&t); tm = localtime(&t);
  469. if (strftime(b,sizeof(b),s,tm))
  470. lua_pushstring(b);
  471. else
  472. lua_error("invalid `date' format");
  473. }
  474. /*
  475. ** To exit
  476. */
  477. static void io_exit (void)
  478. {
  479. lua_Object o = lua_getparam(1);
  480. int code = lua_isnumber(o) ? (int)lua_getnumber(o) : 1;
  481. exit(code);
  482. }
  483. /*
  484. ** To debug a lua program. Start a dialog with the user, interpreting
  485. lua commands until an 'cont'.
  486. */
  487. static void io_debug (void)
  488. {
  489. while (1)
  490. {
  491. char buffer[250];
  492. fprintf(stderr, "lua_debug> ");
  493. if (fgets(buffer, sizeof(buffer), stdin) == 0) return;
  494. if (strcmp(buffer, "cont") == 0) return;
  495. lua_dostring(buffer);
  496. }
  497. }
  498. static void lua_printstack (FILE *f)
  499. {
  500. int level = 0;
  501. lua_Object func;
  502. fprintf(f, "Active Stack:\n");
  503. while ((func = lua_stackedfunction(level++)) != LUA_NOOBJECT)
  504. {
  505. char *name;
  506. int currentline;
  507. fprintf(f, "\t");
  508. switch (*lua_getobjname(func, &name))
  509. {
  510. case 'g':
  511. fprintf(f, "function %s", name);
  512. break;
  513. case 'f':
  514. fprintf(f, "`%s' fallback", name);
  515. break;
  516. default:
  517. {
  518. char *filename;
  519. int linedefined;
  520. lua_funcinfo(func, &filename, &linedefined);
  521. if (linedefined == 0)
  522. fprintf(f, "main of %s", filename);
  523. else if (linedefined < 0)
  524. fprintf(f, "%s", filename);
  525. else
  526. fprintf(f, "function (%s:%d)", filename, linedefined);
  527. }
  528. }
  529. if ((currentline = lua_currentline(func)) > 0)
  530. fprintf(f, " at line %d", currentline);
  531. fprintf(f, "\n");
  532. }
  533. }
  534. static void errorfb (void)
  535. {
  536. lua_Object o = lua_getparam(1);
  537. char *s = lua_isstring(o) ? lua_getstring(o) : "(no messsage)";
  538. fprintf(stderr, "lua: %s\n", s);
  539. lua_printstack(stderr);
  540. }
  541. static struct lua_reg iolib[] = {
  542. {"readfrom", io_readfrom},
  543. {"writeto", io_writeto},
  544. {"appendto", io_appendto},
  545. {"read", io_read},
  546. {"readuntil",io_readuntil},
  547. {"write", io_write},
  548. {"execute", io_execute},
  549. {"remove", io_remove},
  550. {"rename", io_rename},
  551. {"tmpname", io_tmpname},
  552. {"ioerror", io_errorno},
  553. {"getenv", io_getenv},
  554. {"date", io_date},
  555. {"exit", io_exit},
  556. {"debug", io_debug},
  557. {"print_stack", errorfb}
  558. };
  559. void iolib_open (void)
  560. {
  561. luaI_openlib(iolib, (sizeof(iolib)/sizeof(iolib[0])));
  562. lua_setfallback("error", errorfb);
  563. }