lua.c 10 KB

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