lua.c 20 KB

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