lua.c 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. /*
  2. ** $Id: lua.c,v 1.163 2006/09/18 14:03:18 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. static lua_State *globalL = NULL;
  15. static const char *progname = LUA_PROGNAME;
  16. static void lstop (lua_State *L, lua_Debug *ar) {
  17. (void)ar; /* unused arg. */
  18. lua_sethook(L, NULL, 0, 0);
  19. luaL_error(L, "interrupted!");
  20. }
  21. static void laction (int i) {
  22. signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
  23. terminate process (default action) */
  24. lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
  25. }
  26. static void print_usage (void) {
  27. fprintf(stderr,
  28. "usage: %s [options] [script [args]].\n"
  29. "Available options are:\n"
  30. " -e stat execute string " LUA_QL("stat") "\n"
  31. " -l name require library " LUA_QL("name") "\n"
  32. " -i enter interactive mode after executing " LUA_QL("script") "\n"
  33. " -v show version information\n"
  34. " -- stop handling options\n"
  35. " - execute stdin and stop handling options\n"
  36. ,
  37. progname);
  38. fflush(stderr);
  39. }
  40. static void l_message (const char *pname, const char *msg) {
  41. if (pname) fprintf(stderr, "%s: ", pname);
  42. fprintf(stderr, "%s\n", msg);
  43. fflush(stderr);
  44. }
  45. static int report (lua_State *L, int status) {
  46. if (status != LUA_OK && !lua_isnil(L, -1)) {
  47. const char *msg = lua_tostring(L, -1);
  48. if (msg == NULL) msg = "(error object is not a string)";
  49. l_message(progname, msg);
  50. lua_pop(L, 1);
  51. }
  52. return status;
  53. }
  54. static int traceback (lua_State *L) {
  55. lua_getfield(L, LUA_GLOBALSINDEX, "debug");
  56. if (!lua_istable(L, -1)) {
  57. lua_pop(L, 1);
  58. return 1;
  59. }
  60. lua_getfield(L, -1, "traceback");
  61. if (!lua_isfunction(L, -1)) {
  62. lua_pop(L, 2);
  63. return 1;
  64. }
  65. lua_pushvalue(L, 1); /* pass error message */
  66. lua_pushinteger(L, 2); /* skip this function and traceback */
  67. lua_call(L, 2, 1); /* call debug.traceback */
  68. return 1;
  69. }
  70. static int docall (lua_State *L, int narg, int clear) {
  71. int status;
  72. int base = lua_gettop(L) - narg; /* function index */
  73. lua_pushcfunction(L, traceback); /* push traceback function */
  74. lua_insert(L, base); /* put it under chunk and args */
  75. signal(SIGINT, laction);
  76. status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
  77. signal(SIGINT, SIG_DFL);
  78. lua_remove(L, base); /* remove traceback function */
  79. /* force a complete garbage collection in case of errors */
  80. if (status != LUA_OK) lua_gc(L, LUA_GCCOLLECT, 0);
  81. return status;
  82. }
  83. static void print_version (void) {
  84. l_message(NULL, LUA_RELEASE " " LUA_COPYRIGHT);
  85. }
  86. static int getargs (lua_State *L, char **argv, int n) {
  87. int narg;
  88. int i;
  89. int argc = 0;
  90. while (argv[argc]) argc++; /* count total number of arguments */
  91. narg = argc - (n + 1); /* number of arguments to the script */
  92. luaL_checkstack(L, narg + 3, "too many arguments to script");
  93. for (i=n+1; i < argc; i++)
  94. lua_pushstring(L, argv[i]);
  95. lua_createtable(L, narg, n + 1);
  96. for (i=0; i < argc; i++) {
  97. lua_pushstring(L, argv[i]);
  98. lua_rawseti(L, -2, i - n);
  99. }
  100. return narg;
  101. }
  102. static int dofile (lua_State *L, const char *name) {
  103. int status = luaL_loadfile(L, name);
  104. if (status == LUA_OK) status = docall(L, 0, 1);
  105. return report(L, status);
  106. }
  107. static int dostring (lua_State *L, const char *s, const char *name) {
  108. int status = luaL_loadbuffer(L, s, strlen(s), name);
  109. if (status == LUA_OK) status = docall(L, 0, 1);
  110. return report(L, status);
  111. }
  112. static int dolibrary (lua_State *L, const char *name) {
  113. lua_getglobal(L, "require");
  114. lua_pushstring(L, name);
  115. return report(L, lua_pcall(L, 1, 0, 0));
  116. }
  117. static const char *get_prompt (lua_State *L, int firstline) {
  118. const char *p;
  119. lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
  120. p = lua_tostring(L, -1);
  121. if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
  122. lua_pop(L, 1); /* remove global */
  123. return p;
  124. }
  125. /* mark in error messages for incomplete statements */
  126. #define mark LUA_QL("<eof>")
  127. #define marklen (sizeof(mark) - 1)
  128. static int incomplete (lua_State *L, int status) {
  129. if (status == LUA_ERRSYNTAX) {
  130. size_t lmsg;
  131. const char *msg = lua_tolstring(L, -1, &lmsg);
  132. if (lmsg >= marklen && strcmp(msg + lmsg - marklen, mark) == 0) {
  133. lua_pop(L, 1);
  134. return 1;
  135. }
  136. }
  137. return 0; /* else... */
  138. }
  139. static int pushline (lua_State *L, int firstline) {
  140. char buffer[LUA_MAXINPUT];
  141. char *b = buffer;
  142. size_t l;
  143. const char *prmt = get_prompt(L, firstline);
  144. if (lua_readline(L, b, prmt) == 0)
  145. return 0; /* no input */
  146. l = strlen(b);
  147. if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
  148. b[l-1] = '\0'; /* remove it */
  149. if (firstline && b[0] == '=') /* first line starts with `=' ? */
  150. lua_pushfstring(L, "return %s", b+1); /* change it to `return' */
  151. else
  152. lua_pushstring(L, b);
  153. lua_freeline(L, b);
  154. return 1;
  155. }
  156. static int loadline (lua_State *L) {
  157. int status;
  158. lua_settop(L, 0);
  159. if (!pushline(L, 1))
  160. return -1; /* no input */
  161. for (;;) { /* repeat until gets a complete line */
  162. status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_objlen(L, 1), "=stdin");
  163. if (!incomplete(L, status)) break; /* cannot try to add lines? */
  164. if (!pushline(L, 0)) /* no more input? */
  165. return -1;
  166. lua_pushliteral(L, "\n"); /* add a new line... */
  167. lua_insert(L, -2); /* ...between the two lines */
  168. lua_concat(L, 3); /* join them */
  169. }
  170. lua_saveline(L, 1);
  171. lua_remove(L, 1); /* remove line */
  172. return status;
  173. }
  174. static void dotty (lua_State *L) {
  175. int status;
  176. const char *oldprogname = progname;
  177. progname = NULL;
  178. while ((status = loadline(L)) != -1) {
  179. if (status == LUA_OK) status = docall(L, 0, 0);
  180. report(L, status);
  181. if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
  182. lua_getglobal(L, "print");
  183. lua_insert(L, 1);
  184. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != LUA_OK)
  185. l_message(progname, lua_pushfstring(L,
  186. "error calling " LUA_QL("print") " (%s)",
  187. lua_tostring(L, -1)));
  188. }
  189. }
  190. lua_settop(L, 0); /* clear stack */
  191. fputs("\n", stdout);
  192. fflush(stdout);
  193. progname = oldprogname;
  194. }
  195. static int handle_script (lua_State *L, char **argv, int n) {
  196. int status;
  197. const char *fname;
  198. int narg = getargs(L, argv, n); /* collect arguments */
  199. lua_setglobal(L, "arg");
  200. fname = argv[n];
  201. if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
  202. fname = NULL; /* stdin */
  203. status = luaL_loadfile(L, fname);
  204. lua_insert(L, -(narg+1));
  205. if (status == LUA_OK)
  206. status = docall(L, narg, 0);
  207. else
  208. lua_pop(L, narg);
  209. return report(L, status);
  210. }
  211. /* check that argument has no extra characters at the end */
  212. #define notail(x) {if ((x)[2] != '\0') return -1;}
  213. static int collectargs (char **argv, int *pi, int *pv, int *pe) {
  214. int i;
  215. for (i = 1; argv[i] != NULL; i++) {
  216. if (argv[i][0] != '-') /* not an option? */
  217. return i;
  218. switch (argv[i][1]) { /* option */
  219. case '-':
  220. notail(argv[i]);
  221. return (argv[i+1] != NULL ? i+1 : 0);
  222. case '\0':
  223. return i;
  224. case 'i':
  225. notail(argv[i]);
  226. *pi = 1; /* go through */
  227. case 'v':
  228. notail(argv[i]);
  229. *pv = 1;
  230. break;
  231. case 'e':
  232. *pe = 1; /* go through */
  233. case 'l':
  234. if (argv[i][2] == '\0') {
  235. i++;
  236. if (argv[i] == NULL) return -1;
  237. }
  238. break;
  239. default: return -1; /* invalid option */
  240. }
  241. }
  242. return 0;
  243. }
  244. static int runargs (lua_State *L, char **argv, int n) {
  245. int i;
  246. for (i = 1; i < n; i++) {
  247. if (argv[i] == NULL) continue;
  248. lua_assert(argv[i][0] == '-');
  249. switch (argv[i][1]) { /* option */
  250. case 'e': {
  251. const char *chunk = argv[i] + 2;
  252. if (*chunk == '\0') chunk = argv[++i];
  253. lua_assert(chunk != NULL);
  254. if (dostring(L, chunk, "=(command line)") != LUA_OK)
  255. return 0;
  256. break;
  257. }
  258. case 'l': {
  259. const char *filename = argv[i] + 2;
  260. if (*filename == '\0') filename = argv[++i];
  261. lua_assert(filename != NULL);
  262. if (dolibrary(L, filename) != LUA_OK)
  263. return 0; /* stop if file fails */
  264. break;
  265. }
  266. default: break;
  267. }
  268. }
  269. return 1;
  270. }
  271. static int handle_luainit (lua_State *L) {
  272. const char *init = getenv(LUA_INIT);
  273. if (init == NULL) return LUA_OK;
  274. else if (init[0] == '@')
  275. return dofile(L, init+1);
  276. else
  277. return dostring(L, init, "=" LUA_INIT);
  278. }
  279. struct Smain {
  280. int argc;
  281. char **argv;
  282. int ok;
  283. };
  284. static int pmain (lua_State *L) {
  285. struct Smain *s = (struct Smain *)lua_touserdata(L, 1);
  286. char **argv = s->argv;
  287. int script;
  288. int has_i = 0, has_v = 0, has_e = 0;
  289. globalL = L;
  290. if (argv[0] && argv[0][0]) progname = argv[0];
  291. lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
  292. luaL_openlibs(L); /* open libraries */
  293. lua_gc(L, LUA_GCRESTART, 0);
  294. s->ok = (handle_luainit(L) == LUA_OK);
  295. if (!s->ok) return 0;
  296. script = collectargs(argv, &has_i, &has_v, &has_e);
  297. if (script < 0) { /* invalid args? */
  298. print_usage();
  299. s->ok = 0;
  300. return 0;
  301. }
  302. if (has_v) print_version();
  303. s->ok = runargs(L, argv, (script > 0) ? script : s->argc);
  304. if (!s->ok) return 0;
  305. if (script)
  306. s->ok = (handle_script(L, argv, script) == LUA_OK);
  307. if (!s->ok) return 0;
  308. if (has_i)
  309. dotty(L);
  310. else if (script == 0 && !has_e && !has_v) {
  311. if (lua_stdin_is_tty()) {
  312. print_version();
  313. dotty(L);
  314. }
  315. else dofile(L, NULL); /* executes stdin as a file */
  316. }
  317. return 0;
  318. }
  319. int main (int argc, char **argv) {
  320. int status;
  321. struct Smain s;
  322. lua_State *L = lua_open(); /* create state */
  323. if (L == NULL) {
  324. l_message(argv[0], "cannot create state: not enough memory");
  325. return EXIT_FAILURE;
  326. }
  327. s.argc = argc;
  328. s.argv = argv;
  329. status = lua_cpcall(L, &pmain, &s);
  330. report(L, status);
  331. lua_close(L);
  332. return (s.ok && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
  333. }