iolib.c 12 KB

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