lua.c 13 KB

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