2
0

lua.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. /*
  2. ** $Id: lua.c,v 1.197 2011/03/14 15:39:42 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)
  25. #define LUA_INIT "LUA_INIT"
  26. #endif
  27. #define LUA_INITVERSION \
  28. LUA_INIT "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
  29. /*
  30. ** lua_stdin_is_tty detects whether the standard input is a 'tty' (that
  31. ** is, whether we're running lua interactively).
  32. */
  33. #if defined(LUA_USE_ISATTY)
  34. #include <unistd.h>
  35. #define lua_stdin_is_tty() isatty(0)
  36. #elif defined(LUA_WIN)
  37. #include <io.h>
  38. #include <stdio.h>
  39. #define lua_stdin_is_tty() _isatty(_fileno(stdin))
  40. #else
  41. #define lua_stdin_is_tty() 1 /* assume stdin is a tty */
  42. #endif
  43. /*
  44. ** lua_readline defines how to show a prompt and then read a line from
  45. ** the standard input.
  46. ** lua_saveline defines how to "save" a read line in a "history".
  47. ** lua_freeline defines how to free a line read by lua_readline.
  48. */
  49. #if defined(LUA_USE_READLINE)
  50. #include <stdio.h>
  51. #include <readline/readline.h>
  52. #include <readline/history.h>
  53. #define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL)
  54. #define lua_saveline(L,idx) \
  55. if (lua_rawlen(L,idx) > 0) /* non-empty line? */ \
  56. add_history(lua_tostring(L, idx)); /* add it to history */
  57. #define lua_freeline(L,b) ((void)L, free(b))
  58. #elif !defined(lua_readline)
  59. #define lua_readline(L,b,p) \
  60. ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \
  61. fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */
  62. #define lua_saveline(L,idx) { (void)L; (void)idx; }
  63. #define lua_freeline(L,b) { (void)L; (void)b; }
  64. #endif
  65. static lua_State *globalL = NULL;
  66. static const char *progname = LUA_PROGNAME;
  67. static void lstop (lua_State *L, lua_Debug *ar) {
  68. (void)ar; /* unused arg. */
  69. lua_sethook(L, NULL, 0, 0);
  70. luaL_error(L, "interrupted!");
  71. }
  72. static void laction (int i) {
  73. signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
  74. terminate process (default action) */
  75. lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
  76. }
  77. static void print_usage (const char *badoption) {
  78. luai_writestringerror("%s: ", progname);
  79. if (badoption[1] == 'e' || badoption[1] == 'l')
  80. luai_writestringerror("'%s' needs argument\n", badoption);
  81. else
  82. luai_writestringerror("unrecognized option '%s'\n", badoption);
  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 nres) {
  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, nres, 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. luai_writestring(LUA_COPYRIGHT "\n", sizeof(LUA_COPYRIGHT) + 1);
  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, 0);
  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, 0);
  169. return report(L, status);
  170. }
  171. static int dolibrary (lua_State *L, const char *name) {
  172. int status;
  173. lua_pushglobaltable(L);
  174. lua_getfield(L, -1, "require");
  175. lua_pushstring(L, name);
  176. status = docall(L, 1, 1);
  177. if (status == LUA_OK) {
  178. lua_setfield(L, -2, name); /* global[name] = require return */
  179. lua_pop(L, 1); /* remove global table */
  180. }
  181. else
  182. lua_remove(L, -2); /* remove global table (below error msg.) */
  183. return report(L, status);
  184. }
  185. static const char *get_prompt (lua_State *L, int firstline) {
  186. const char *p;
  187. lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2");
  188. p = lua_tostring(L, -1);
  189. if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
  190. lua_pop(L, 1); /* remove global */
  191. return p;
  192. }
  193. /* mark in error messages for incomplete statements */
  194. #define EOFMARK "<eof>"
  195. #define marklen (sizeof(EOFMARK)/sizeof(char) - 1)
  196. static int incomplete (lua_State *L, int status) {
  197. if (status == LUA_ERRSYNTAX) {
  198. size_t lmsg;
  199. const char *msg = lua_tolstring(L, -1, &lmsg);
  200. if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) {
  201. lua_pop(L, 1);
  202. return 1;
  203. }
  204. }
  205. return 0; /* else... */
  206. }
  207. static int pushline (lua_State *L, int firstline) {
  208. char buffer[LUA_MAXINPUT];
  209. char *b = buffer;
  210. size_t l;
  211. const char *prmt = get_prompt(L, firstline);
  212. if (lua_readline(L, b, prmt) == 0)
  213. return 0; /* no input */
  214. l = strlen(b);
  215. if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
  216. b[l-1] = '\0'; /* remove it */
  217. if (firstline && b[0] == '=') /* first line starts with `=' ? */
  218. lua_pushfstring(L, "return %s", b+1); /* change it to `return' */
  219. else
  220. lua_pushstring(L, b);
  221. lua_freeline(L, b);
  222. return 1;
  223. }
  224. static int loadline (lua_State *L) {
  225. int status;
  226. lua_settop(L, 0);
  227. if (!pushline(L, 1))
  228. return -1; /* no input */
  229. for (;;) { /* repeat until gets a complete line */
  230. size_t l;
  231. const char *line = lua_tolstring(L, 1, &l);
  232. status = luaL_loadbuffer(L, line, l, "=stdin");
  233. if (!incomplete(L, status)) break; /* cannot try to add lines? */
  234. if (!pushline(L, 0)) /* no more input? */
  235. return -1;
  236. lua_pushliteral(L, "\n"); /* add a new line... */
  237. lua_insert(L, -2); /* ...between the two lines */
  238. lua_concat(L, 3); /* join them */
  239. }
  240. lua_saveline(L, 1);
  241. lua_remove(L, 1); /* remove line */
  242. return status;
  243. }
  244. static void dotty (lua_State *L) {
  245. int status;
  246. const char *oldprogname = progname;
  247. progname = NULL;
  248. while ((status = loadline(L)) != -1) {
  249. if (status == LUA_OK) status = docall(L, 0, LUA_MULTRET);
  250. report(L, status);
  251. if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
  252. luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
  253. lua_getglobal(L, "print");
  254. lua_insert(L, 1);
  255. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != LUA_OK)
  256. l_message(progname, lua_pushfstring(L,
  257. "error calling " LUA_QL("print") " (%s)",
  258. lua_tostring(L, -1)));
  259. }
  260. }
  261. lua_settop(L, 0); /* clear stack */
  262. luai_writestring("\n", 1);
  263. progname = oldprogname;
  264. }
  265. static int handle_script (lua_State *L, char **argv, int n) {
  266. int status;
  267. const char *fname;
  268. int narg = getargs(L, argv, n); /* collect arguments */
  269. lua_setglobal(L, "arg");
  270. fname = argv[n];
  271. if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
  272. fname = NULL; /* stdin */
  273. status = luaL_loadfile(L, fname);
  274. lua_insert(L, -(narg+1));
  275. if (status == LUA_OK)
  276. status = docall(L, narg, LUA_MULTRET);
  277. else
  278. lua_pop(L, narg);
  279. return report(L, status);
  280. }
  281. /* check that argument has no extra characters at the end */
  282. #define noextrachars(x) {if ((x)[2] != '\0') return -1;}
  283. static int collectargs (char **argv, int *pi, int *pv, int *pe) {
  284. int i;
  285. for (i = 1; argv[i] != NULL; i++) {
  286. if (argv[i][0] != '-') /* not an option? */
  287. return i;
  288. switch (argv[i][1]) { /* option */
  289. case '-':
  290. noextrachars(argv[i]);
  291. return (argv[i+1] != NULL ? i+1 : 0);
  292. case '\0':
  293. return i;
  294. case 'i':
  295. noextrachars(argv[i]);
  296. *pi = 1; /* go through */
  297. case 'v':
  298. noextrachars(argv[i]);
  299. *pv = 1;
  300. break;
  301. case 'e':
  302. *pe = 1; /* go through */
  303. case 'l': /* both options need an argument */
  304. if (argv[i][2] == '\0') { /* no concatenated argument? */
  305. i++; /* try next 'argv' */
  306. if (argv[i] == NULL || argv[i][0] == '-')
  307. return -(i - 1); /* no next argument or it is another option */
  308. }
  309. break;
  310. default: /* invalid option; return its index... */
  311. return -i; /* ...as a negative value */
  312. }
  313. }
  314. return 0;
  315. }
  316. static int runargs (lua_State *L, char **argv, int n) {
  317. int i;
  318. for (i = 1; i < n; i++) {
  319. lua_assert(argv[i][0] == '-');
  320. switch (argv[i][1]) { /* option */
  321. case 'e': {
  322. const char *chunk = argv[i] + 2;
  323. if (*chunk == '\0') chunk = argv[++i];
  324. lua_assert(chunk != NULL);
  325. if (dostring(L, chunk, "=(command line)") != LUA_OK)
  326. return 0;
  327. break;
  328. }
  329. case 'l': {
  330. const char *filename = argv[i] + 2;
  331. if (*filename == '\0') filename = argv[++i];
  332. lua_assert(filename != NULL);
  333. if (dolibrary(L, filename) != LUA_OK)
  334. return 0; /* stop if file fails */
  335. break;
  336. }
  337. default: break;
  338. }
  339. }
  340. return 1;
  341. }
  342. static int handle_luainit (lua_State *L) {
  343. const char *name = "=" LUA_INITVERSION;
  344. const char *init = getenv(name + 1);
  345. if (init == NULL) {
  346. name = "=" LUA_INIT;
  347. init = getenv(name + 1); /* try alternative name */
  348. }
  349. if (init == NULL) return LUA_OK;
  350. else if (init[0] == '@')
  351. return dofile(L, init+1);
  352. else
  353. return dostring(L, init, name);
  354. }
  355. static int pmain (lua_State *L) {
  356. int argc = (int)lua_tointeger(L, 1);
  357. char **argv = (char **)lua_touserdata(L, 2);
  358. int script;
  359. int has_i = 0, has_v = 0, has_e = 0;
  360. if (argv[0] && argv[0][0]) progname = argv[0];
  361. script = collectargs(argv, &has_i, &has_v, &has_e);
  362. if (script < 0) { /* invalid arg? */
  363. print_usage(argv[-script]);
  364. return 0;
  365. }
  366. if (has_v) print_version();
  367. /* open standard libraries */
  368. luaL_checkversion(L);
  369. lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
  370. luaL_openlibs(L); /* open libraries */
  371. lua_gc(L, LUA_GCRESTART, 0);
  372. /* run LUA_INIT */
  373. if (handle_luainit(L) != LUA_OK) return 0;
  374. /* execute arguments -e and -l */
  375. if (!runargs(L, argv, (script > 0) ? script : argc)) return 0;
  376. /* execute main script (if there is one) */
  377. if (script && handle_script(L, argv, script) != LUA_OK) return 0;
  378. if (has_i) /* -i option? */
  379. dotty(L);
  380. else if (script == 0 && !has_e && !has_v) { /* no arguments? */
  381. if (lua_stdin_is_tty()) {
  382. print_version();
  383. dotty(L);
  384. }
  385. else dofile(L, NULL); /* executes stdin as a file */
  386. }
  387. lua_pushboolean(L, 1); /* signal no errors */
  388. return 1;
  389. }
  390. int main (int argc, char **argv) {
  391. int status, result;
  392. lua_State *L = luaL_newstate(); /* create state */
  393. if (L == NULL) {
  394. l_message(argv[0], "cannot create state: not enough memory");
  395. return EXIT_FAILURE;
  396. }
  397. /* call 'pmain' in protected mode */
  398. lua_pushcfunction(L, &pmain);
  399. lua_pushinteger(L, argc); /* 1st argument */
  400. lua_pushlightuserdata(L, argv); /* 2nd argument */
  401. status = lua_pcall(L, 2, 1, 0);
  402. result = lua_toboolean(L, -1); /* get result */
  403. finalreport(L, status);
  404. lua_close(L);
  405. return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
  406. }