iolib.c 12 KB

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