lua.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*
  2. ** $Id: lua.c,v 1.178 2009/12/17 12:26:09 roberto Exp roberto $
  3. ** Lua stand-alone interpreter
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <signal.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #define lua_c
  11. #include "lua.h"
  12. #include "lauxlib.h"
  13. #include "lualib.h"
  14. #if !defined(LUA_PROMPT)
  15. #define LUA_PROMPT "> "
  16. #define LUA_PROMPT2 ">> "
  17. #endif
  18. #if !defined(LUA_PROGNAME)
  19. #define LUA_PROGNAME "lua"
  20. #endif
  21. #if !defined(LUA_MAXINPUT)
  22. #define LUA_MAXINPUT 512
  23. #endif
  24. #if !defined(LUA_INIT_VAR)
  25. #define LUA_INIT_VAR "LUA_INIT"
  26. #endif
  27. /*
  28. ** lua_stdin_is_tty detects whether the standard input is a 'tty' (that
  29. ** is, whether we're running lua interactively).
  30. */
  31. #if defined(LUA_USE_ISATTY)
  32. #include <unistd.h>
  33. #define lua_stdin_is_tty() isatty(0)
  34. #elif defined(LUA_WIN)
  35. #include <io.h>
  36. #include <stdio.h>
  37. #define lua_stdin_is_tty() _isatty(_fileno(stdin))
  38. #else
  39. #define lua_stdin_is_tty() 1 /* assume stdin is a tty */
  40. #endif
  41. /*
  42. ** lua_readline defines how to show a prompt and then read a line from
  43. ** the standard input.
  44. ** lua_saveline defines how to "save" a read line in a "history".
  45. ** lua_freeline defines how to free a line read by lua_readline.
  46. */
  47. #if defined(LUA_USE_READLINE)
  48. #include <stdio.h>
  49. #include <readline/readline.h>
  50. #include <readline/history.h>
  51. #define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL)
  52. #define lua_saveline(L,idx) \
  53. if (lua_objlen(L,idx) > 0) /* non-empty line? */ \
  54. add_history(lua_tostring(L, idx)); /* add it to history */
  55. #define lua_freeline(L,b) ((void)L, free(b))
  56. #elif !defined(lua_readline)
  57. #define lua_readline(L,b,p) \
  58. ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \
  59. fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */
  60. #define lua_saveline(L,idx) { (void)L; (void)idx; }
  61. #define lua_freeline(L,b) { (void)L; (void)b; }
  62. #endif
  63. static lua_State *globalL = NULL;
  64. static const char *progname = LUA_PROGNAME;
  65. static void lstop (lua_State *L, lua_Debug *ar) {
  66. (void)ar; /* unused arg. */
  67. lua_sethook(L, NULL, 0, 0);
  68. luaL_error(L, "interrupted!");
  69. }
  70. static void laction (int i) {
  71. signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
  72. terminate process (default action) */
  73. lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
  74. }
  75. static void print_usage (void) {
  76. fprintf(stderr,
  77. "usage: %s [options] [script [args]]\n"
  78. "Available options are:\n"
  79. " -e stat execute string " LUA_QL("stat") "\n"
  80. " -l name require library " LUA_QL("name") "\n"
  81. " -i enter interactive mode after executing " LUA_QL("script") "\n"
  82. " -v show version information\n"
  83. " -- stop handling options\n"
  84. " - execute stdin and stop handling options\n"
  85. ,
  86. progname);
  87. fflush(stderr);
  88. }
  89. static void l_message (const char *pname, const char *msg) {
  90. if (pname) fprintf(stderr, "%s: ", pname);
  91. fprintf(stderr, "%s\n", msg);
  92. fflush(stderr);
  93. }
  94. static int report (lua_State *L, int status) {
  95. if (status != LUA_OK && !lua_isnil(L, -1)) {
  96. const char *msg = lua_tostring(L, -1);
  97. if (msg == NULL) msg = "(error object is not a string)";
  98. l_message(progname, msg);
  99. lua_pop(L, 1);
  100. /* force a complete garbage collection in case of errors */
  101. lua_gc(L, LUA_GCCOLLECT, 0);
  102. }
  103. return status;
  104. }
  105. /* the next function is called unprotected, so it must avoid errors */
  106. static void finalreport (lua_State *L, int status) {
  107. if (status != LUA_OK) {
  108. const char *msg = (lua_type(L, -1) == LUA_TSTRING) ? lua_tostring(L, -1)
  109. : NULL;
  110. if (msg == NULL) msg = "(error object is not a string)";
  111. l_message(progname, msg);
  112. lua_pop(L, 1);
  113. }
  114. }
  115. static int traceback (lua_State *L) {
  116. const char *msg = lua_tostring(L, 1);
  117. if (msg)
  118. luaL_traceback(L, L, msg, 1);
  119. else if (!lua_isnoneornil(L, 1)) { /* is there an error object? */
  120. if (!luaL_callmeta(L, 1, "__tostring")) /* try its 'tostring' metamethod */
  121. lua_pushliteral(L, "(no error message)");
  122. }
  123. return 1;
  124. }
  125. static int docall (lua_State *L, int narg, int clear) {
  126. int status;
  127. int base = lua_gettop(L) - narg; /* function index */
  128. lua_pushcfunction(L, traceback); /* push traceback function */
  129. lua_insert(L, base); /* put it under chunk and args */
  130. globalL = L; /* to be available to 'laction' */
  131. signal(SIGINT, laction);
  132. status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
  133. signal(SIGINT, SIG_DFL);
  134. lua_remove(L, base); /* remove traceback function */
  135. return status;
  136. }
  137. static void print_version (void) {
  138. printf("%s\n", LUA_COPYRIGHT);
  139. }
  140. static int getargs (lua_State *L, char **argv, int n) {
  141. int narg;
  142. int i;
  143. int argc = 0;
  144. while (argv[argc]) argc++; /* count total number of arguments */
  145. narg = argc - (n + 1); /* number of arguments to the script */
  146. luaL_checkstack(L, narg + 3, "too many arguments to script");
  147. for (i=n+1; i < argc; i++)
  148. lua_pushstring(L, argv[i]);
  149. lua_createtable(L, narg, n + 1);
  150. for (i=0; i < argc; i++) {
  151. lua_pushstring(L, argv[i]);
  152. lua_rawseti(L, -2, i - n);
  153. }
  154. return narg;
  155. }
  156. static int dofile (lua_State *L, const char *name) {
  157. int status = luaL_loadfile(L, name);
  158. if (status == LUA_OK) status = docall(L, 0, 1);
  159. return report(L, status);
  160. }
  161. static int dostring (lua_State *L, const char *s, const char *name) {
  162. int status = luaL_loadbuffer(L, s, strlen(s), name);
  163. if (status == LUA_OK) status = docall(L, 0, 1);
  164. return report(L, status);
  165. }
  166. static int dolibrary (lua_State *L, const char *name) {
  167. lua_getfield(L, LUA_GLOBALSINDEX, "require");
  168. lua_pushstring(L, name);
  169. return report(L, docall(L, 1, 1));
  170. }
  171. static const char *get_prompt (lua_State *L, int firstline) {
  172. const char *p;
  173. lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
  174. p = lua_tostring(L, -1);
  175. if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
  176. lua_pop(L, 1); /* remove global */
  177. return p;
  178. }
  179. /* mark in error messages for incomplete statements */
  180. #define mark "<eof>"
  181. #define marklen (sizeof(mark) - 1)
  182. static int incomplete (lua_State *L, int status) {
  183. if (status == LUA_ERRSYNTAX) {
  184. size_t lmsg;
  185. const char *msg = lua_tolstring(L, -1, &lmsg);
  186. if (lmsg >= marklen && strcmp(msg + lmsg - marklen, mark) == 0) {
  187. lua_pop(L, 1);
  188. return 1;
  189. }
  190. }
  191. return 0; /* else... */
  192. }
  193. static int pushline (lua_State *L, int firstline) {
  194. char buffer[LUA_MAXINPUT];
  195. char *b = buffer;
  196. size_t l;
  197. const char *prmt = get_prompt(L, firstline);
  198. if (lua_readline(L, b, prmt) == 0)
  199. return 0; /* no input */
  200. l = strlen(b);
  201. if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
  202. b[l-1] = '\0'; /* remove it */
  203. if (firstline && b[0] == '=') /* first line starts with `=' ? */
  204. lua_pushfstring(L, "return %s", b+1); /* change it to `return' */
  205. else
  206. lua_pushstring(L, b);
  207. lua_freeline(L, b);
  208. return 1;
  209. }
  210. static int loadline (lua_State *L) {
  211. int status;
  212. lua_settop(L, 0);
  213. if (!pushline(L, 1))
  214. return -1; /* no input */
  215. for (;;) { /* repeat until gets a complete line */
  216. status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_objlen(L, 1), "=stdin");
  217. if (!incomplete(L, status)) break; /* cannot try to add lines? */
  218. if (!pushline(L, 0)) /* no more input? */
  219. return -1;
  220. lua_pushliteral(L, "\n"); /* add a new line... */
  221. lua_insert(L, -2); /* ...between the two lines */
  222. lua_concat(L, 3); /* join them */
  223. }
  224. lua_saveline(L, 1);
  225. lua_remove(L, 1); /* remove line */
  226. return status;
  227. }
  228. static void dotty (lua_State *L) {
  229. int status;
  230. const char *oldprogname = progname;
  231. progname = NULL;
  232. while ((status = loadline(L)) != -1) {
  233. if (status == LUA_OK) status = docall(L, 0, 0);
  234. report(L, status);
  235. if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
  236. luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
  237. lua_getfield(L, LUA_GLOBALSINDEX, "print");
  238. lua_insert(L, 1);
  239. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != LUA_OK)
  240. l_message(progname, lua_pushfstring(L,
  241. "error calling " LUA_QL("print") " (%s)",
  242. lua_tostring(L, -1)));
  243. }
  244. }
  245. lua_settop(L, 0); /* clear stack */
  246. luai_writestring("\n", 1);
  247. fflush(stdout);
  248. progname = oldprogname;
  249. }
  250. static int handle_script (lua_State *L, char **argv, int n) {
  251. int status;
  252. const char *fname;
  253. int narg = getargs(L, argv, n); /* collect arguments */
  254. lua_setfield(L, LUA_GLOBALSINDEX, "arg");
  255. fname = argv[n];
  256. if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
  257. fname = NULL; /* stdin */
  258. status = luaL_loadfile(L, fname);
  259. lua_insert(L, -(narg+1));
  260. if (status == LUA_OK)
  261. status = docall(L, narg, 0);
  262. else
  263. lua_pop(L, narg);
  264. return report(L, status);
  265. }
  266. /* check that argument has no extra characters at the end */
  267. #define noextrachars(x) {if ((x)[2] != '\0') return -1;}
  268. static int collectargs (char **argv, int *pi, int *pv, int *pe) {
  269. int i;
  270. for (i = 1; argv[i] != NULL; i++) {
  271. if (argv[i][0] != '-') /* not an option? */
  272. return i;
  273. switch (argv[i][1]) { /* option */
  274. case '-':
  275. noextrachars(argv[i]);
  276. return (argv[i+1] != NULL ? i+1 : 0);
  277. case '\0':
  278. return i;
  279. case 'i':
  280. noextrachars(argv[i]);
  281. *pi = 1; /* go through */
  282. case 'v':
  283. noextrachars(argv[i]);
  284. *pv = 1;
  285. break;
  286. case 'e':
  287. *pe = 1; /* go through */
  288. case 'l':
  289. if (argv[i][2] == '\0') {
  290. i++;
  291. if (argv[i] == NULL) return -1;
  292. }
  293. break;
  294. default: return -1; /* invalid option */
  295. }
  296. }
  297. return 0;
  298. }
  299. static int runargs (lua_State *L, char **argv, int n) {
  300. int i;
  301. for (i = 1; i < n; i++) {
  302. if (argv[i] == NULL) continue;
  303. lua_assert(argv[i][0] == '-');
  304. switch (argv[i][1]) { /* option */
  305. case 'e': {
  306. const char *chunk = argv[i] + 2;
  307. if (*chunk == '\0') chunk = argv[++i];
  308. lua_assert(chunk != NULL);
  309. if (dostring(L, chunk, "=(command line)") != LUA_OK)
  310. return 0;
  311. break;
  312. }
  313. case 'l': {
  314. const char *filename = argv[i] + 2;
  315. if (*filename == '\0') filename = argv[++i];
  316. lua_assert(filename != NULL);
  317. if (dolibrary(L, filename) != LUA_OK)
  318. return 0; /* stop if file fails */
  319. break;
  320. }
  321. default: break;
  322. }
  323. }
  324. return 1;
  325. }
  326. static int handle_luainit (lua_State *L) {
  327. const char *init = getenv(LUA_INIT_VAR);
  328. if (init == NULL) return LUA_OK;
  329. else if (init[0] == '@')
  330. return dofile(L, init+1);
  331. else
  332. return dostring(L, init, "=" LUA_INIT_VAR);
  333. }
  334. struct Smain {
  335. int argc;
  336. char **argv;
  337. int ok;
  338. };
  339. static int pmain (lua_State *L) {
  340. struct Smain *s = (struct Smain *)lua_touserdata(L, 1);
  341. char **argv = s->argv;
  342. int script;
  343. int has_i = 0, has_v = 0, has_e = 0;
  344. if (argv[0] && argv[0][0]) progname = argv[0];
  345. lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
  346. luaL_openlibs(L); /* open libraries */
  347. lua_gc(L, LUA_GCRESTART, 0);
  348. luaL_checkversion(L);
  349. s->ok = (handle_luainit(L) == LUA_OK);
  350. if (!s->ok) return 0;
  351. script = collectargs(argv, &has_i, &has_v, &has_e);
  352. if (script < 0) { /* invalid args? */
  353. print_usage();
  354. s->ok = 0;
  355. return 0;
  356. }
  357. if (has_v) print_version();
  358. s->ok = runargs(L, argv, (script > 0) ? script : s->argc);
  359. if (!s->ok) return 0;
  360. if (script)
  361. s->ok = (handle_script(L, argv, script) == LUA_OK);
  362. if (!s->ok) return 0;
  363. if (has_i)
  364. dotty(L);
  365. else if (script == 0 && !has_e && !has_v) {
  366. if (lua_stdin_is_tty()) {
  367. print_version();
  368. dotty(L);
  369. }
  370. else dofile(L, NULL); /* executes stdin as a file */
  371. }
  372. return 0;
  373. }
  374. int main (int argc, char **argv) {
  375. int status;
  376. struct Smain s;
  377. lua_State *L = luaL_newstate(); /* create state */
  378. if (L == NULL) {
  379. l_message(argv[0], "cannot create state: not enough memory");
  380. return EXIT_FAILURE;
  381. }
  382. s.argc = argc;
  383. s.argv = argv;
  384. status = lua_cpcall(L, &pmain, &s);
  385. finalreport(L, status);
  386. lua_close(L);
  387. return (s.ok && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
  388. }