iolib.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. /*
  2. ** iolib.c
  3. ** Input/output library to LUA
  4. */
  5. char *rcs_iolib="$Id: iolib.c,v 1.31 1996/01/22 17:46:55 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. /*
  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. }
  272. }
  273. }
  274. /*
  275. ** Read characters until a given one. The delimiter is not read.
  276. */
  277. static void io_readuntil (void)
  278. {
  279. int del, c;
  280. lua_Object p = lua_getparam(1);
  281. luaI_addchar(0); /* initialize buffer */
  282. if (p == LUA_NOOBJECT || lua_isnil(p))
  283. del = EOF;
  284. else
  285. del = *lua_check_string(1, "readuntil");
  286. c = read_until_char(del);
  287. if (c != EOF) ungetc(c,in);
  288. lua_pushstring(luaI_addchar(0));
  289. }
  290. /*
  291. ** Write a variable. On error put 0 on stack, otherwise put 1.
  292. ** LUA interface:
  293. ** status = write (variable [,format])
  294. **
  295. ** O formato pode ter um dos seguintes especificadores:
  296. **
  297. ** s ou S -> para string
  298. ** f ou F, g ou G, e ou E -> para reais
  299. ** i ou I -> para inteiros
  300. **
  301. ** Estes especificadores podem vir seguidos de:
  302. **
  303. ** [?][m][.n]
  304. **
  305. ** onde:
  306. ** ? -> indica justificacao
  307. ** < = esquerda
  308. ** | = centro
  309. ** > = direita (default)
  310. ** m -> numero maximo de campos (se exceder estoura)
  311. ** n -> indica precisao para
  312. ** reais -> numero de casas decimais
  313. ** inteiros -> numero minimo de digitos
  314. ** string -> nao se aplica
  315. */
  316. static int write_fill (int n, int c)
  317. {
  318. while (n--)
  319. if (fputc(c, out) == EOF)
  320. return 0;
  321. return 1;
  322. }
  323. static int write_string (char *s, int just, int m)
  324. {
  325. int status;
  326. int l = strlen(s);
  327. int pre; /* number of blanks before string */
  328. if (m < 0) m = l;
  329. else if (l > m)
  330. {
  331. write_fill(m, '*');
  332. return 0;
  333. }
  334. pre = (just == '<') ? 0 : (just == '>') ? m-l : (m-l)/2;
  335. status = write_fill(pre, ' ');
  336. status = status && fprintf(out, "%s", s) >= 0;
  337. status = status && write_fill(m-(l+pre), ' ');
  338. return status;
  339. }
  340. static int write_float (int just, int m, int n)
  341. {
  342. char buffer[100];
  343. lua_Object p = lua_getparam(1);
  344. float number;
  345. if (!lua_isnumber(p)) return 0;
  346. number = lua_getnumber(p);
  347. if (n >= 0)
  348. sprintf(buffer, "%.*f", n, number);
  349. else
  350. sprintf(buffer, "%g", number);
  351. return write_string(buffer, just, m);
  352. }
  353. static int write_int (int just, int m, int n)
  354. {
  355. char buffer[100];
  356. lua_Object p = lua_getparam(1);
  357. int number;
  358. if (!lua_isnumber(p)) return 0;
  359. number = (int)lua_getnumber(p);
  360. if (n >= 0)
  361. sprintf(buffer, "%.*d", n, number);
  362. else
  363. sprintf(buffer, "%d", number);
  364. return write_string(buffer, just, m);
  365. }
  366. static void io_write (void)
  367. {
  368. int status = 0;
  369. if (lua_getparam (2) == LUA_NOOBJECT) /* free format */
  370. {
  371. lua_Object o1 = lua_getparam(1);
  372. if (lua_isnumber(o1))
  373. status = fprintf (out, "%g", lua_getnumber(o1)) >= 0;
  374. else if (lua_isstring(o1))
  375. status = fprintf (out, "%s", lua_getstring(o1)) >= 0;
  376. }
  377. else /* formated */
  378. {
  379. int just, m, n;
  380. switch (getformat (lua_check_string(2, "write"), &just, &m, &n))
  381. {
  382. case 's':
  383. {
  384. lua_Object p = lua_getparam(1);
  385. if (lua_isstring(p))
  386. status = write_string(lua_getstring(p), just, m);
  387. else
  388. status = 0;
  389. break;
  390. }
  391. case 'f':
  392. status = write_float(just, m, n);
  393. break;
  394. case 'i':
  395. status = write_int(just, m, n);
  396. break;
  397. }
  398. }
  399. if (status)
  400. lua_pushnumber(status);
  401. else
  402. lua_pushnil();
  403. }
  404. /*
  405. ** Execute a executable program using "system".
  406. ** Return the result of execution.
  407. */
  408. static void io_execute (void)
  409. {
  410. lua_pushnumber(system(lua_check_string(1, "execute")));
  411. }
  412. /*
  413. ** Remove a file. On error return nil.
  414. */
  415. static void io_remove (void)
  416. {
  417. if (remove(lua_check_string(1, "remove")) == 0)
  418. lua_pushnumber (1);
  419. else
  420. lua_pushnil();
  421. }
  422. /*
  423. ** To get a environment variables
  424. */
  425. static void io_getenv (void)
  426. {
  427. char *env = getenv(lua_check_string(1, "getenv"));
  428. if (env == NULL) lua_pushnil();
  429. else lua_pushstring(env);
  430. }
  431. /*
  432. ** Return time: hour, min, sec
  433. */
  434. static void io_time (void)
  435. {
  436. time_t t;
  437. struct tm *s;
  438. time(&t);
  439. s = localtime(&t);
  440. lua_pushnumber(s->tm_hour);
  441. lua_pushnumber(s->tm_min);
  442. lua_pushnumber(s->tm_sec);
  443. }
  444. /*
  445. ** Return date: dd, mm, yyyy, weekday
  446. */
  447. static void io_date (void)
  448. {
  449. time_t t;
  450. struct tm *s;
  451. time(&t);
  452. s = localtime(&t);
  453. lua_pushnumber(s->tm_mday);
  454. lua_pushnumber(s->tm_mon+1);
  455. lua_pushnumber(s->tm_year+1900);
  456. lua_pushnumber(s->tm_wday+1);
  457. }
  458. /*
  459. ** Beep
  460. */
  461. static void io_beep (void)
  462. {
  463. printf("\a");
  464. }
  465. /*
  466. ** To exit
  467. */
  468. static void io_exit (void)
  469. {
  470. lua_Object o = lua_getparam(1);
  471. if (lua_isstring(o))
  472. fprintf(stderr, "%s\n", lua_getstring(o));
  473. exit(1);
  474. }
  475. /*
  476. ** To debug a lua program. Start a dialog with the user, interpreting
  477. lua commands until an 'cont'.
  478. */
  479. static void io_debug (void)
  480. {
  481. while (1)
  482. {
  483. char buffer[250];
  484. fprintf(stderr, "lua_debug> ");
  485. if (gets(buffer) == 0) return;
  486. if (strcmp(buffer, "cont") == 0) return;
  487. lua_dostring(buffer);
  488. }
  489. }
  490. void lua_printstack (FILE *f)
  491. {
  492. int level = 0;
  493. lua_Object func;
  494. fprintf(f, "Active Stack:\n");
  495. while ((func = lua_stackedfunction(level++)) != LUA_NOOBJECT)
  496. {
  497. char *name;
  498. int currentline;
  499. fprintf(f, "\t");
  500. switch (*lua_getobjname(func, &name))
  501. {
  502. case 'g':
  503. fprintf(f, "function %s", name);
  504. break;
  505. case 'f':
  506. fprintf(f, "fallback %s", name);
  507. break;
  508. default:
  509. {
  510. char *filename;
  511. int linedefined;
  512. lua_funcinfo(func, &filename, &linedefined);
  513. if (linedefined == 0)
  514. fprintf(f, "main of %s", filename);
  515. else if (linedefined < 0)
  516. fprintf(f, "%s", filename);
  517. else
  518. fprintf(f, "function (%s:%d)", filename, linedefined);
  519. }
  520. }
  521. if ((currentline = lua_currentline(func)) > 0)
  522. fprintf(f, " at line %d", currentline);
  523. fprintf(f, "\n");
  524. }
  525. }
  526. static void errorfb (void)
  527. {
  528. lua_Object o = lua_getparam(1);
  529. char *s = lua_isstring(o) ? lua_getstring(o) : "(no messsage)";
  530. fprintf(stderr, "lua: %s\n", s);
  531. lua_printstack(stderr);
  532. }
  533. /*
  534. ** Open io library
  535. */
  536. void iolib_open (void)
  537. {
  538. lua_register ("readfrom", io_readfrom);
  539. lua_register ("writeto", io_writeto);
  540. lua_register ("appendto", io_appendto);
  541. lua_register ("read", io_read);
  542. lua_register ("readuntil",io_readuntil);
  543. lua_register ("write", io_write);
  544. lua_register ("execute", io_execute);
  545. lua_register ("remove", io_remove);
  546. lua_register ("getenv", io_getenv);
  547. lua_register ("time", io_time);
  548. lua_register ("date", io_date);
  549. lua_register ("beep", io_beep);
  550. lua_register ("exit", io_exit);
  551. lua_register ("debug", io_debug);
  552. lua_register ("print_stack", errorfb);
  553. lua_setfallback("error", errorfb);
  554. }
  555. /*
  556. ** Return user formatted time stamp
  557. *
  558. static void sys_localtime (void)
  559. {
  560. time_t t;
  561. struct tm *tm;
  562. lua_Object o = lua_getparam(1);
  563. time(&t); tm = localtime(&t);
  564. if (lua_isstring(o))
  565. {
  566. char b[BUFSIZ];
  567. if (strftime(b,sizeof(b),lua_getstring(o),tm)==0)
  568. lua_pushstring(ctime(&t));
  569. else
  570. lua_pushstring(b);
  571. }
  572. else
  573. lua_pushstring(ctime(&t));
  574. }
  575. */