iolib.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. /*
  2. ** iolib.c
  3. ** Input/output library to LUA
  4. */
  5. char *rcs_iolib="$Id: iolib.c,v 1.36 1996/02/16 13:10:14 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;
  345. luaI_addchar(0);
  346. luaI_addchar('"');
  347. for (s = lua_check_string(1, "write"); *s; s++)
  348. {
  349. if (*s == '"' || *s == '\\' || *s == '\n')
  350. luaI_addchar('\\');
  351. luaI_addchar(*s);
  352. }
  353. luaI_addchar('"');
  354. return write_string(luaI_addchar(0), just, m);
  355. }
  356. static int write_float (int just, int m, int n)
  357. {
  358. char buffer[100];
  359. lua_Object p = lua_getparam(1);
  360. float number;
  361. if (!lua_isnumber(p)) return 0;
  362. number = lua_getnumber(p);
  363. if (n >= 0)
  364. sprintf(buffer, "%.*f", n, number);
  365. else
  366. sprintf(buffer, "%g", number);
  367. return write_string(buffer, just, m);
  368. }
  369. static int write_int (int just, int m, int n)
  370. {
  371. char buffer[100];
  372. lua_Object p = lua_getparam(1);
  373. int number;
  374. if (!lua_isnumber(p)) return 0;
  375. number = (int)lua_getnumber(p);
  376. if (n >= 0)
  377. sprintf(buffer, "%.*d", n, number);
  378. else
  379. sprintf(buffer, "%d", number);
  380. return write_string(buffer, just, m);
  381. }
  382. static void io_write (void)
  383. {
  384. int status = 0;
  385. if (lua_getparam (2) == LUA_NOOBJECT) /* free format */
  386. {
  387. lua_Object o1 = lua_getparam(1);
  388. if (lua_isnumber(o1))
  389. status = fprintf (out, "%g", lua_getnumber(o1)) >= 0;
  390. else if (lua_isstring(o1))
  391. status = fprintf (out, "%s", lua_getstring(o1)) >= 0;
  392. }
  393. else /* formated */
  394. {
  395. int just, m, n;
  396. switch (getformat(lua_check_string(2, "write"), &just, &m, &n))
  397. {
  398. case 's':
  399. {
  400. lua_Object p = lua_getparam(1);
  401. if (lua_isstring(p))
  402. status = write_string(lua_getstring(p), just, m);
  403. else
  404. status = 0;
  405. break;
  406. }
  407. case 'q':
  408. status = write_quoted(just, m);
  409. break;
  410. case 'f':
  411. status = write_float(just, m, n);
  412. break;
  413. case 'i':
  414. status = write_int(just, m, n);
  415. break;
  416. }
  417. }
  418. if (status)
  419. lua_pushnumber(status);
  420. else
  421. lua_pushnil();
  422. }
  423. /*
  424. ** Execute a executable program using "system".
  425. ** Return the result of execution.
  426. */
  427. static void io_execute (void)
  428. {
  429. lua_pushnumber(system(lua_check_string(1, "execute")));
  430. }
  431. /*
  432. ** Remove a file. On error return nil.
  433. */
  434. static void io_remove (void)
  435. {
  436. if (remove(lua_check_string(1, "remove")) == 0)
  437. lua_pushnumber (1);
  438. else
  439. lua_pushnil();
  440. }
  441. static void io_errorno (void)
  442. {
  443. /* lua_pushstring(strerror(errno));*/
  444. }
  445. /*
  446. ** To get a environment variable
  447. */
  448. static void io_getenv (void)
  449. {
  450. char *env = getenv(lua_check_string(1, "getenv"));
  451. if (env == NULL) lua_pushnil();
  452. else lua_pushstring(env);
  453. }
  454. /*
  455. ** Return user formatted time stamp
  456. */
  457. static void io_date (void)
  458. {
  459. time_t t;
  460. struct tm *tm;
  461. char *s;
  462. char b[BUFSIZ];
  463. if (lua_getparam(1) == LUA_NOOBJECT)
  464. s = "%c";
  465. else
  466. s = lua_check_string(1, "date");
  467. time(&t); tm = localtime(&t);
  468. if (strftime(b,sizeof(b),s,tm))
  469. lua_pushstring(b);
  470. else
  471. lua_error("invalid `date' format");
  472. }
  473. /*
  474. ** To exit
  475. */
  476. static void io_exit (void)
  477. {
  478. lua_Object o = lua_getparam(1);
  479. if (lua_isstring(o))
  480. fprintf(stderr, "%s\n", lua_getstring(o));
  481. exit(1);
  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 (gets(buffer) == 0) return;
  494. if (strcmp(buffer, "cont") == 0) return;
  495. lua_dostring(buffer);
  496. }
  497. }
  498. 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, "fallback %s", 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. /*
  542. ** Open io library
  543. */
  544. void iolib_open (void)
  545. {
  546. lua_register ("readfrom", io_readfrom);
  547. lua_register ("writeto", io_writeto);
  548. lua_register ("appendto", io_appendto);
  549. lua_register ("read", io_read);
  550. lua_register ("readuntil",io_readuntil);
  551. lua_register ("write", io_write);
  552. lua_register ("execute", io_execute);
  553. lua_register ("remove", io_remove);
  554. lua_register ("ioerror", io_errorno);
  555. lua_register ("getenv", io_getenv);
  556. lua_register ("date", io_date);
  557. lua_register ("exit", io_exit);
  558. lua_register ("debug", io_debug);
  559. lua_register ("print_stack", errorfb);
  560. lua_setfallback("error", errorfb);
  561. }
  562. /*
  563. ** Return user formatted time stamp
  564. *
  565. static void sys_localtime (void)
  566. {
  567. time_t t;
  568. struct tm *tm;
  569. lua_Object o = lua_getparam(1);
  570. time(&t); tm = localtime(&t);
  571. if (lua_isstring(o))
  572. {
  573. char b[BUFSIZ];
  574. if (strftime(b,sizeof(b),lua_getstring(o),tm)==0)
  575. lua_pushstring(ctime(&t));
  576. else
  577. lua_pushstring(b);
  578. }
  579. else
  580. lua_pushstring(ctime(&t));
  581. }
  582. */