lua.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. /*
  2. ** $Id: lua.c $
  3. ** Lua stand-alone interpreter
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lua_c
  7. #include "lprefix.h"
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <signal.h>
  12. #include "lua.h"
  13. #include "lauxlib.h"
  14. #include "lualib.h"
  15. #include "llimits.h"
  16. #if !defined(LUA_PROGNAME)
  17. #define LUA_PROGNAME "lua"
  18. #endif
  19. #if !defined(LUA_INIT_VAR)
  20. #define LUA_INIT_VAR "LUA_INIT"
  21. #endif
  22. #define LUA_INITVARVERSION LUA_INIT_VAR LUA_VERSUFFIX
  23. static lua_State *globalL = NULL;
  24. static const char *progname = LUA_PROGNAME;
  25. #if defined(LUA_USE_POSIX) /* { */
  26. /*
  27. ** Use 'sigaction' when available.
  28. */
  29. static void setsignal (int sig, void (*handler)(int)) {
  30. struct sigaction sa;
  31. sa.sa_handler = handler;
  32. sa.sa_flags = 0;
  33. sigemptyset(&sa.sa_mask); /* do not mask any signal */
  34. sigaction(sig, &sa, NULL);
  35. }
  36. #else /* }{ */
  37. #define setsignal signal
  38. #endif /* } */
  39. /*
  40. ** Hook set by signal function to stop the interpreter.
  41. */
  42. static void lstop (lua_State *L, lua_Debug *ar) {
  43. (void)ar; /* unused arg. */
  44. lua_sethook(L, NULL, 0, 0); /* reset hook */
  45. luaL_error(L, "interrupted!");
  46. }
  47. /*
  48. ** Function to be called at a C signal. Because a C signal cannot
  49. ** just change a Lua state (as there is no proper synchronization),
  50. ** this function only sets a hook that, when called, will stop the
  51. ** interpreter.
  52. */
  53. static void laction (int i) {
  54. int flag = LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE | LUA_MASKCOUNT;
  55. setsignal(i, SIG_DFL); /* if another SIGINT happens, terminate process */
  56. lua_sethook(globalL, lstop, flag, 1);
  57. }
  58. static void print_usage (const char *badoption) {
  59. lua_writestringerror("%s: ", progname);
  60. if (badoption[1] == 'e' || badoption[1] == 'l')
  61. lua_writestringerror("'%s' needs argument\n", badoption);
  62. else
  63. lua_writestringerror("unrecognized option '%s'\n", badoption);
  64. lua_writestringerror(
  65. "usage: %s [options] [script [args]]\n"
  66. "Available options are:\n"
  67. " -e stat execute string 'stat'\n"
  68. " -i enter interactive mode after executing 'script'\n"
  69. " -l mod require library 'mod' into global 'mod'\n"
  70. " -l g=mod require library 'mod' into global 'g'\n"
  71. " -v show version information\n"
  72. " -E ignore environment variables\n"
  73. " -W turn warnings on\n"
  74. " -- stop handling options\n"
  75. " - stop handling options and execute stdin\n"
  76. ,
  77. progname);
  78. }
  79. /*
  80. ** Prints an error message, adding the program name in front of it
  81. ** (if present)
  82. */
  83. static void l_message (const char *pname, const char *msg) {
  84. if (pname) lua_writestringerror("%s: ", pname);
  85. lua_writestringerror("%s\n", msg);
  86. }
  87. /*
  88. ** Check whether 'status' is not OK and, if so, prints the error
  89. ** message on the top of the stack.
  90. */
  91. static int report (lua_State *L, int status) {
  92. if (status != LUA_OK) {
  93. const char *msg = lua_tostring(L, -1);
  94. if (msg == NULL)
  95. msg = "(error message not a string)";
  96. l_message(progname, msg);
  97. lua_pop(L, 1); /* remove message */
  98. }
  99. return status;
  100. }
  101. /*
  102. ** Message handler used to run all chunks
  103. */
  104. static int msghandler (lua_State *L) {
  105. const char *msg = lua_tostring(L, 1);
  106. if (msg == NULL) { /* is error object not a string? */
  107. if (luaL_callmeta(L, 1, "__tostring") && /* does it have a metamethod */
  108. lua_type(L, -1) == LUA_TSTRING) /* that produces a string? */
  109. return 1; /* that is the message */
  110. else
  111. msg = lua_pushfstring(L, "(error object is a %s value)",
  112. luaL_typename(L, 1));
  113. }
  114. luaL_traceback(L, L, msg, 1); /* append a standard traceback */
  115. return 1; /* return the traceback */
  116. }
  117. /*
  118. ** Interface to 'lua_pcall', which sets appropriate message function
  119. ** and C-signal handler. Used to run all chunks.
  120. */
  121. static int docall (lua_State *L, int narg, int nres) {
  122. int status;
  123. int base = lua_gettop(L) - narg; /* function index */
  124. lua_pushcfunction(L, msghandler); /* push message handler */
  125. lua_insert(L, base); /* put it under function and args */
  126. globalL = L; /* to be available to 'laction' */
  127. setsignal(SIGINT, laction); /* set C-signal handler */
  128. status = lua_pcall(L, narg, nres, base);
  129. setsignal(SIGINT, SIG_DFL); /* reset C-signal handler */
  130. lua_remove(L, base); /* remove message handler from the stack */
  131. return status;
  132. }
  133. static void print_version (void) {
  134. lua_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
  135. lua_writeline();
  136. }
  137. /*
  138. ** Create the 'arg' table, which stores all arguments from the
  139. ** command line ('argv'). It should be aligned so that, at index 0,
  140. ** it has 'argv[script]', which is the script name. The arguments
  141. ** to the script (everything after 'script') go to positive indices;
  142. ** other arguments (before the script name) go to negative indices.
  143. ** If there is no script name, assume interpreter's name as base.
  144. ** (If there is no interpreter's name either, 'script' is -1, so
  145. ** table sizes are zero.)
  146. */
  147. static void createargtable (lua_State *L, char **argv, int argc, int script) {
  148. int i, narg;
  149. narg = argc - (script + 1); /* number of positive indices */
  150. lua_createtable(L, narg, script + 1);
  151. for (i = 0; i < argc; i++) {
  152. lua_pushstring(L, argv[i]);
  153. lua_rawseti(L, -2, i - script);
  154. }
  155. lua_setglobal(L, "arg");
  156. }
  157. static int dochunk (lua_State *L, int status) {
  158. if (status == LUA_OK) status = docall(L, 0, 0);
  159. return report(L, status);
  160. }
  161. static int dofile (lua_State *L, const char *name) {
  162. return dochunk(L, luaL_loadfile(L, name));
  163. }
  164. static int dostring (lua_State *L, const char *s, const char *name) {
  165. return dochunk(L, luaL_loadbuffer(L, s, strlen(s), name));
  166. }
  167. /*
  168. ** Receives 'globname[=modname]' and runs 'globname = require(modname)'.
  169. ** If there is no explicit modname and globname contains a '-', cut
  170. ** the suffix after '-' (the "version") to make the global name.
  171. */
  172. static int dolibrary (lua_State *L, char *globname) {
  173. int status;
  174. char *suffix = NULL;
  175. char *modname = strchr(globname, '=');
  176. if (modname == NULL) { /* no explicit name? */
  177. modname = globname; /* module name is equal to global name */
  178. suffix = strchr(modname, *LUA_IGMARK); /* look for a suffix mark */
  179. }
  180. else {
  181. *modname = '\0'; /* global name ends here */
  182. modname++; /* module name starts after the '=' */
  183. }
  184. lua_getglobal(L, "require");
  185. lua_pushstring(L, modname);
  186. status = docall(L, 1, 1); /* call 'require(modname)' */
  187. if (status == LUA_OK) {
  188. if (suffix != NULL) /* is there a suffix mark? */
  189. *suffix = '\0'; /* remove suffix from global name */
  190. lua_setglobal(L, globname); /* globname = require(modname) */
  191. }
  192. return report(L, status);
  193. }
  194. /*
  195. ** Push on the stack the contents of table 'arg' from 1 to #arg
  196. */
  197. static int pushargs (lua_State *L) {
  198. int i, n;
  199. if (lua_getglobal(L, "arg") != LUA_TTABLE)
  200. luaL_error(L, "'arg' is not a table");
  201. n = (int)luaL_len(L, -1);
  202. luaL_checkstack(L, n + 3, "too many arguments to script");
  203. for (i = 1; i <= n; i++)
  204. lua_rawgeti(L, -i, i);
  205. lua_remove(L, -i); /* remove table from the stack */
  206. return n;
  207. }
  208. static int handle_script (lua_State *L, char **argv) {
  209. int status;
  210. const char *fname = argv[0];
  211. if (strcmp(fname, "-") == 0 && strcmp(argv[-1], "--") != 0)
  212. fname = NULL; /* stdin */
  213. status = luaL_loadfile(L, fname);
  214. if (status == LUA_OK) {
  215. int n = pushargs(L); /* push arguments to script */
  216. status = docall(L, n, LUA_MULTRET);
  217. }
  218. return report(L, status);
  219. }
  220. /* bits of various argument indicators in 'args' */
  221. #define has_error 1 /* bad option */
  222. #define has_i 2 /* -i */
  223. #define has_v 4 /* -v */
  224. #define has_e 8 /* -e */
  225. #define has_E 16 /* -E */
  226. /*
  227. ** Traverses all arguments from 'argv', returning a mask with those
  228. ** needed before running any Lua code or an error code if it finds any
  229. ** invalid argument. In case of error, 'first' is the index of the bad
  230. ** argument. Otherwise, 'first' is -1 if there is no program name,
  231. ** 0 if there is no script name, or the index of the script name.
  232. */
  233. static int collectargs (char **argv, int *first) {
  234. int args = 0;
  235. int i;
  236. if (argv[0] != NULL) { /* is there a program name? */
  237. if (argv[0][0]) /* not empty? */
  238. progname = argv[0]; /* save it */
  239. }
  240. else { /* no program name */
  241. *first = -1;
  242. return 0;
  243. }
  244. for (i = 1; argv[i] != NULL; i++) { /* handle arguments */
  245. *first = i;
  246. if (argv[i][0] != '-') /* not an option? */
  247. return args; /* stop handling options */
  248. switch (argv[i][1]) { /* else check option */
  249. case '-': /* '--' */
  250. if (argv[i][2] != '\0') /* extra characters after '--'? */
  251. return has_error; /* invalid option */
  252. *first = i + 1;
  253. return args;
  254. case '\0': /* '-' */
  255. return args; /* script "name" is '-' */
  256. case 'E':
  257. if (argv[i][2] != '\0') /* extra characters? */
  258. return has_error; /* invalid option */
  259. args |= has_E;
  260. break;
  261. case 'W':
  262. if (argv[i][2] != '\0') /* extra characters? */
  263. return has_error; /* invalid option */
  264. break;
  265. case 'i':
  266. args |= has_i; /* (-i implies -v) *//* FALLTHROUGH */
  267. case 'v':
  268. if (argv[i][2] != '\0') /* extra characters? */
  269. return has_error; /* invalid option */
  270. args |= has_v;
  271. break;
  272. case 'e':
  273. args |= has_e; /* FALLTHROUGH */
  274. case 'l': /* both options need an argument */
  275. if (argv[i][2] == '\0') { /* no concatenated argument? */
  276. i++; /* try next 'argv' */
  277. if (argv[i] == NULL || argv[i][0] == '-')
  278. return has_error; /* no next argument or it is another option */
  279. }
  280. break;
  281. default: /* invalid option */
  282. return has_error;
  283. }
  284. }
  285. *first = 0; /* no script name */
  286. return args;
  287. }
  288. /*
  289. ** Processes options 'e' and 'l', which involve running Lua code, and
  290. ** 'W', which also affects the state.
  291. ** Returns 0 if some code raises an error.
  292. */
  293. static int runargs (lua_State *L, char **argv, int n) {
  294. int i;
  295. for (i = 1; i < n; i++) {
  296. int option = argv[i][1];
  297. lua_assert(argv[i][0] == '-'); /* already checked */
  298. switch (option) {
  299. case 'e': case 'l': {
  300. int status;
  301. char *extra = argv[i] + 2; /* both options need an argument */
  302. if (*extra == '\0') extra = argv[++i];
  303. lua_assert(extra != NULL);
  304. status = (option == 'e')
  305. ? dostring(L, extra, "=(command line)")
  306. : dolibrary(L, extra);
  307. if (status != LUA_OK) return 0;
  308. break;
  309. }
  310. case 'W':
  311. lua_warning(L, "@on", 0); /* warnings on */
  312. break;
  313. }
  314. }
  315. return 1;
  316. }
  317. static int handle_luainit (lua_State *L) {
  318. const char *name = "=" LUA_INITVARVERSION;
  319. const char *init = getenv(name + 1);
  320. if (init == NULL) {
  321. name = "=" LUA_INIT_VAR;
  322. init = getenv(name + 1); /* try alternative name */
  323. }
  324. if (init == NULL) return LUA_OK;
  325. else if (init[0] == '@')
  326. return dofile(L, init+1);
  327. else
  328. return dostring(L, init, name);
  329. }
  330. /*
  331. ** {==================================================================
  332. ** Read-Eval-Print Loop (REPL)
  333. ** ===================================================================
  334. */
  335. #if !defined(LUA_PROMPT)
  336. #define LUA_PROMPT "> "
  337. #define LUA_PROMPT2 ">> "
  338. #endif
  339. #if !defined(LUA_MAXINPUT)
  340. #define LUA_MAXINPUT 512
  341. #endif
  342. /*
  343. ** lua_stdin_is_tty detects whether the standard input is a 'tty' (that
  344. ** is, whether we're running lua interactively).
  345. */
  346. #if !defined(lua_stdin_is_tty) /* { */
  347. #if defined(LUA_USE_POSIX) /* { */
  348. #include <unistd.h>
  349. #define lua_stdin_is_tty() isatty(0)
  350. #elif defined(LUA_USE_WINDOWS) /* }{ */
  351. #include <io.h>
  352. #include <windows.h>
  353. #define lua_stdin_is_tty() _isatty(_fileno(stdin))
  354. #else /* }{ */
  355. /* ISO C definition */
  356. #define lua_stdin_is_tty() 1 /* assume stdin is a tty */
  357. #endif /* } */
  358. #endif /* } */
  359. /*
  360. ** lua_readline defines how to show a prompt and then read a line from
  361. ** the standard input.
  362. ** lua_saveline defines how to "save" a read line in a "history".
  363. ** lua_freeline defines how to free a line read by lua_readline.
  364. */
  365. #if defined(LUA_USE_READLINE)
  366. #include <readline/readline.h>
  367. #include <readline/history.h>
  368. #define lua_initreadline(L) ((void)L, rl_readline_name="lua")
  369. #define lua_readline(b,p) ((void)b, readline(p))
  370. #define lua_saveline(line) add_history(line)
  371. #define lua_freeline(b) free(b)
  372. #endif
  373. #if !defined(lua_readline) /* { */
  374. /* pointer to dynamically loaded 'readline' function (if any) */
  375. typedef char *(*l_readline_t) (const char *prompt);
  376. static l_readline_t l_readline = NULL;
  377. static char *lua_readline (char *buff, const char *prompt) {
  378. if (l_readline != NULL) /* is there a dynamic 'readline'? */
  379. return (*l_readline)(prompt); /* use it */
  380. else { /* emulate 'readline' over 'buff' */
  381. fputs(prompt, stdout);
  382. fflush(stdout); /* show prompt */
  383. return fgets(buff, LUA_MAXINPUT, stdin); /* read line */
  384. }
  385. }
  386. /* pointer to dynamically loaded 'add_history' function (if any) */
  387. typedef void (*l_addhist_t) (const char *string);
  388. static l_addhist_t l_addhist = NULL;
  389. static void lua_saveline (const char *line) {
  390. if (l_addhist != NULL) /* is there a dynamic 'add_history'? */
  391. (*l_addhist)(line); /* use it */
  392. /* else nothing to be done */
  393. }
  394. static void lua_freeline (char *line) {
  395. if (l_readline != NULL) /* is there a dynamic 'readline'? */
  396. free(line); /* free line created by it */
  397. /* else 'lua_readline' used an automatic buffer; nothing to free */
  398. }
  399. #if !defined(LUA_USE_DLOPEN) || !defined(LUA_READLINELIB)
  400. #define lua_initreadline(L) ((void)L)
  401. #else /* { */
  402. #include <dlfcn.h>
  403. static void lua_initreadline (lua_State *L) {
  404. void *lib = dlopen(LUA_READLINELIB, RTLD_NOW | RTLD_LOCAL);
  405. if (lib == NULL)
  406. lua_warning(L, "library '" LUA_READLINELIB "'not found", 0);
  407. else {
  408. const char **name = cast(const char**, dlsym(lib, "rl_readline_name"));
  409. if (name != NULL)
  410. *name = "Lua";
  411. l_readline = cast(l_readline_t, cast_func(dlsym(lib, "readline")));
  412. if (l_readline == NULL)
  413. lua_warning(L, "unable to load 'readline'", 0);
  414. else
  415. l_addhist = cast(l_addhist_t, cast_func(dlsym(lib, "add_history")));
  416. }
  417. }
  418. #endif /* } */
  419. #endif /* } */
  420. /*
  421. ** Return the string to be used as a prompt by the interpreter. Leave
  422. ** the string (or nil, if using the default value) on the stack, to keep
  423. ** it anchored.
  424. */
  425. static const char *get_prompt (lua_State *L, int firstline) {
  426. if (lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2") == LUA_TNIL)
  427. return (firstline ? LUA_PROMPT : LUA_PROMPT2); /* use the default */
  428. else { /* apply 'tostring' over the value */
  429. const char *p = luaL_tolstring(L, -1, NULL);
  430. lua_remove(L, -2); /* remove original value */
  431. return p;
  432. }
  433. }
  434. /* mark in error messages for incomplete statements */
  435. #define EOFMARK "<eof>"
  436. #define marklen (sizeof(EOFMARK)/sizeof(char) - 1)
  437. /*
  438. ** Check whether 'status' signals a syntax error and the error
  439. ** message at the top of the stack ends with the above mark for
  440. ** incomplete statements.
  441. */
  442. static int incomplete (lua_State *L, int status) {
  443. if (status == LUA_ERRSYNTAX) {
  444. size_t lmsg;
  445. const char *msg = lua_tolstring(L, -1, &lmsg);
  446. if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0)
  447. return 1;
  448. }
  449. return 0; /* else... */
  450. }
  451. /*
  452. ** Prompt the user, read a line, and push it into the Lua stack.
  453. */
  454. static int pushline (lua_State *L, int firstline) {
  455. char buffer[LUA_MAXINPUT];
  456. size_t l;
  457. const char *prmt = get_prompt(L, firstline);
  458. char *b = lua_readline(buffer, prmt);
  459. lua_pop(L, 1); /* remove prompt */
  460. if (b == NULL)
  461. return 0; /* no input */
  462. l = strlen(b);
  463. if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
  464. b[--l] = '\0'; /* remove it */
  465. lua_pushlstring(L, b, l);
  466. lua_freeline(b);
  467. return 1;
  468. }
  469. /*
  470. ** Try to compile line on the stack as 'return <line>;'; on return, stack
  471. ** has either compiled chunk or original line (if compilation failed).
  472. */
  473. static int addreturn (lua_State *L) {
  474. const char *line = lua_tostring(L, -1); /* original line */
  475. const char *retline = lua_pushfstring(L, "return %s;", line);
  476. int status = luaL_loadbuffer(L, retline, strlen(retline), "=stdin");
  477. if (status == LUA_OK)
  478. lua_remove(L, -2); /* remove modified line */
  479. else
  480. lua_pop(L, 2); /* pop result from 'luaL_loadbuffer' and modified line */
  481. return status;
  482. }
  483. /*
  484. ** Read multiple lines until a complete Lua statement or an error not
  485. ** for an incomplete statement. Start with first line already read in
  486. ** the stack.
  487. */
  488. static int multiline (lua_State *L) {
  489. for (;;) { /* repeat until gets a complete statement */
  490. size_t len;
  491. const char *line = lua_tolstring(L, 1, &len); /* get what it has */
  492. int status = luaL_loadbuffer(L, line, len, "=stdin"); /* try it */
  493. if (!incomplete(L, status) || !pushline(L, 0))
  494. return status; /* should not or cannot try to add continuation line */
  495. lua_remove(L, -2); /* remove error message (from incomplete line) */
  496. lua_pushliteral(L, "\n"); /* add newline... */
  497. lua_insert(L, -2); /* ...between the two lines */
  498. lua_concat(L, 3); /* join them */
  499. }
  500. }
  501. /*
  502. ** Read a line and try to load (compile) it first as an expression (by
  503. ** adding "return " in front of it) and second as a statement. Return
  504. ** the final status of load/call with the resulting function (if any)
  505. ** in the top of the stack.
  506. */
  507. static int loadline (lua_State *L) {
  508. const char *line;
  509. int status;
  510. lua_settop(L, 0);
  511. if (!pushline(L, 1))
  512. return -1; /* no input */
  513. if ((status = addreturn(L)) != LUA_OK) /* 'return ...' did not work? */
  514. status = multiline(L); /* try as command, maybe with continuation lines */
  515. line = lua_tostring(L, 1);
  516. if (line[0] != '\0') /* non empty? */
  517. lua_saveline(line); /* keep history */
  518. lua_remove(L, 1); /* remove line from the stack */
  519. lua_assert(lua_gettop(L) == 1);
  520. return status;
  521. }
  522. /*
  523. ** Prints (calling the Lua 'print' function) any values on the stack
  524. */
  525. static void l_print (lua_State *L) {
  526. int n = lua_gettop(L);
  527. if (n > 0) { /* any result to be printed? */
  528. luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
  529. lua_getglobal(L, "print");
  530. lua_insert(L, 1);
  531. if (lua_pcall(L, n, 0, 0) != LUA_OK)
  532. l_message(progname, lua_pushfstring(L, "error calling 'print' (%s)",
  533. lua_tostring(L, -1)));
  534. }
  535. }
  536. /*
  537. ** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and
  538. ** print any results.
  539. */
  540. static void doREPL (lua_State *L) {
  541. int status;
  542. const char *oldprogname = progname;
  543. progname = NULL; /* no 'progname' on errors in interactive mode */
  544. lua_initreadline(L);
  545. while ((status = loadline(L)) != -1) {
  546. if (status == LUA_OK)
  547. status = docall(L, 0, LUA_MULTRET);
  548. if (status == LUA_OK) l_print(L);
  549. else report(L, status);
  550. }
  551. lua_settop(L, 0); /* clear stack */
  552. lua_writeline();
  553. progname = oldprogname;
  554. }
  555. /* }================================================================== */
  556. #if !defined(luai_openlibs)
  557. #define luai_openlibs(L) luaL_openselectedlibs(L, ~0, 0)
  558. #endif
  559. /*
  560. ** Main body of stand-alone interpreter (to be called in protected mode).
  561. ** Reads the options and handles them all.
  562. */
  563. static int pmain (lua_State *L) {
  564. int argc = (int)lua_tointeger(L, 1);
  565. char **argv = (char **)lua_touserdata(L, 2);
  566. int script;
  567. int args = collectargs(argv, &script);
  568. int optlim = (script > 0) ? script : argc; /* first argv not an option */
  569. luaL_checkversion(L); /* check that interpreter has correct version */
  570. if (args == has_error) { /* bad arg? */
  571. print_usage(argv[script]); /* 'script' has index of bad arg. */
  572. return 0;
  573. }
  574. if (args & has_v) /* option '-v'? */
  575. print_version();
  576. if (args & has_E) { /* option '-E'? */
  577. lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */
  578. lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
  579. }
  580. luai_openlibs(L); /* open standard libraries */
  581. createargtable(L, argv, argc, script); /* create table 'arg' */
  582. lua_gc(L, LUA_GCRESTART); /* start GC... */
  583. lua_gc(L, LUA_GCGEN); /* ...in generational mode */
  584. if (!(args & has_E)) { /* no option '-E'? */
  585. if (handle_luainit(L) != LUA_OK) /* run LUA_INIT */
  586. return 0; /* error running LUA_INIT */
  587. }
  588. if (!runargs(L, argv, optlim)) /* execute arguments -e and -l */
  589. return 0; /* something failed */
  590. if (script > 0) { /* execute main script (if there is one) */
  591. if (handle_script(L, argv + script) != LUA_OK)
  592. return 0; /* interrupt in case of error */
  593. }
  594. if (args & has_i) /* -i option? */
  595. doREPL(L); /* do read-eval-print loop */
  596. else if (script < 1 && !(args & (has_e | has_v))) { /* no active option? */
  597. if (lua_stdin_is_tty()) { /* running in interactive mode? */
  598. print_version();
  599. doREPL(L); /* do read-eval-print loop */
  600. }
  601. else dofile(L, NULL); /* executes stdin as a file */
  602. }
  603. lua_pushboolean(L, 1); /* signal no errors */
  604. return 1;
  605. }
  606. int main (int argc, char **argv) {
  607. int status, result;
  608. lua_State *L = luaL_newstate(); /* create state */
  609. if (L == NULL) {
  610. l_message(argv[0], "cannot create state: not enough memory");
  611. return EXIT_FAILURE;
  612. }
  613. lua_gc(L, LUA_GCSTOP); /* stop GC while building state */
  614. lua_pushcfunction(L, &pmain); /* to call 'pmain' in protected mode */
  615. lua_pushinteger(L, argc); /* 1st argument */
  616. lua_pushlightuserdata(L, argv); /* 2nd argument */
  617. status = lua_pcall(L, 2, 1, 0); /* do the call */
  618. result = lua_toboolean(L, -1); /* get result */
  619. report(L, status);
  620. lua_close(L);
  621. return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
  622. }