iolib.c 12 KB

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