iolib.c 12 KB

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