lua.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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. /* if there is a script name, it comes after '--' */
  253. *first = (argv[i + 1] != NULL) ? i + 1 : 0;
  254. return args;
  255. case '\0': /* '-' */
  256. return args; /* script "name" is '-' */
  257. case 'E':
  258. if (argv[i][2] != '\0') /* extra characters? */
  259. return has_error; /* invalid option */
  260. args |= has_E;
  261. break;
  262. case 'W':
  263. if (argv[i][2] != '\0') /* extra characters? */
  264. return has_error; /* invalid option */
  265. break;
  266. case 'i':
  267. args |= has_i; /* (-i implies -v) *//* FALLTHROUGH */
  268. case 'v':
  269. if (argv[i][2] != '\0') /* extra characters? */
  270. return has_error; /* invalid option */
  271. args |= has_v;
  272. break;
  273. case 'e':
  274. args |= has_e; /* FALLTHROUGH */
  275. case 'l': /* both options need an argument */
  276. if (argv[i][2] == '\0') { /* no concatenated argument? */
  277. i++; /* try next 'argv' */
  278. if (argv[i] == NULL || argv[i][0] == '-')
  279. return has_error; /* no next argument or it is another option */
  280. }
  281. break;
  282. default: /* invalid option */
  283. return has_error;
  284. }
  285. }
  286. *first = 0; /* no script name */
  287. return args;
  288. }
  289. /*
  290. ** Processes options 'e' and 'l', which involve running Lua code, and
  291. ** 'W', which also affects the state.
  292. ** Returns 0 if some code raises an error.
  293. */
  294. static int runargs (lua_State *L, char **argv, int n) {
  295. int i;
  296. lua_warning(L, "@off", 0); /* by default, Lua stand-alone has warnings off */
  297. for (i = 1; i < n; i++) {
  298. int option = argv[i][1];
  299. lua_assert(argv[i][0] == '-'); /* already checked */
  300. switch (option) {
  301. case 'e': case 'l': {
  302. int status;
  303. char *extra = argv[i] + 2; /* both options need an argument */
  304. if (*extra == '\0') extra = argv[++i];
  305. lua_assert(extra != NULL);
  306. status = (option == 'e')
  307. ? dostring(L, extra, "=(command line)")
  308. : dolibrary(L, extra);
  309. if (status != LUA_OK) return 0;
  310. break;
  311. }
  312. case 'W':
  313. lua_warning(L, "@on", 0); /* warnings on */
  314. break;
  315. }
  316. }
  317. return 1;
  318. }
  319. static int handle_luainit (lua_State *L) {
  320. const char *name = "=" LUA_INITVARVERSION;
  321. const char *init = getenv(name + 1);
  322. if (init == NULL) {
  323. name = "=" LUA_INIT_VAR;
  324. init = getenv(name + 1); /* try alternative name */
  325. }
  326. if (init == NULL) return LUA_OK;
  327. else if (init[0] == '@')
  328. return dofile(L, init+1);
  329. else
  330. return dostring(L, init, name);
  331. }
  332. /*
  333. ** {==================================================================
  334. ** Read-Eval-Print Loop (REPL)
  335. ** ===================================================================
  336. */
  337. #if !defined(LUA_PROMPT)
  338. #define LUA_PROMPT "> "
  339. #define LUA_PROMPT2 ">> "
  340. #endif
  341. #if !defined(LUA_MAXINPUT)
  342. #define LUA_MAXINPUT 512
  343. #endif
  344. /*
  345. ** lua_stdin_is_tty detects whether the standard input is a 'tty' (that
  346. ** is, whether we're running lua interactively).
  347. */
  348. #if !defined(lua_stdin_is_tty) /* { */
  349. #if defined(LUA_USE_POSIX) /* { */
  350. #include <unistd.h>
  351. #define lua_stdin_is_tty() isatty(0)
  352. #elif defined(LUA_USE_WINDOWS) /* }{ */
  353. #include <io.h>
  354. #include <windows.h>
  355. #define lua_stdin_is_tty() _isatty(_fileno(stdin))
  356. #else /* }{ */
  357. /* ISO C definition */
  358. #define lua_stdin_is_tty() 1 /* assume stdin is a tty */
  359. #endif /* } */
  360. #endif /* } */
  361. /*
  362. ** * lua_initreadline initializes the readline system.
  363. ** * lua_readline defines how to show a prompt and then read a line from
  364. ** the standard input.
  365. ** * lua_saveline defines how to "save" a read line in a "history".
  366. ** * lua_freeline defines how to free a line read by lua_readline.
  367. */
  368. #if !defined(lua_readline) /* { */
  369. /* Otherwise, all previously listed functions should be defined. */
  370. #if defined(LUA_USE_READLINE) /* { */
  371. /* Lua will be linked with '-lreadline' */
  372. #include <readline/readline.h>
  373. #include <readline/history.h>
  374. #define lua_initreadline(L) ((void)L, rl_readline_name="lua")
  375. #define lua_readline(buff,prompt) ((void)buff, readline(prompt))
  376. #define lua_saveline(line) add_history(line)
  377. #define lua_freeline(line) free(line)
  378. #else /* }{ */
  379. /* use dynamically loaded readline (or nothing) */
  380. /* pointer to 'readline' function (if any) */
  381. typedef char *(*l_readlineT) (const char *prompt);
  382. static l_readlineT l_readline = NULL;
  383. /* pointer to 'add_history' function (if any) */
  384. typedef void (*l_addhistT) (const char *string);
  385. static l_addhistT l_addhist = NULL;
  386. static char *lua_readline (char *buff, const char *prompt) {
  387. if (l_readline != NULL) /* is there a 'readline'? */
  388. return (*l_readline)(prompt); /* use it */
  389. else { /* emulate 'readline' over 'buff' */
  390. fputs(prompt, stdout);
  391. fflush(stdout); /* show prompt */
  392. return fgets(buff, LUA_MAXINPUT, stdin); /* read line */
  393. }
  394. }
  395. static void lua_saveline (const char *line) {
  396. if (l_addhist != NULL) /* is there an 'add_history'? */
  397. (*l_addhist)(line); /* use it */
  398. /* else nothing to be done */
  399. }
  400. static void lua_freeline (char *line) {
  401. if (l_readline != NULL) /* is there a 'readline'? */
  402. free(line); /* free line created by it */
  403. /* else 'lua_readline' used an automatic buffer; nothing to free */
  404. }
  405. #if defined(LUA_USE_DLOPEN) && defined(LUA_READLINELIB) /* { */
  406. /* try to load 'readline' dynamically */
  407. #include <dlfcn.h>
  408. static void lua_initreadline (lua_State *L) {
  409. void *lib = dlopen(LUA_READLINELIB, RTLD_NOW | RTLD_LOCAL);
  410. if (lib == NULL)
  411. lua_warning(L, "library '" LUA_READLINELIB "' not found", 0);
  412. else {
  413. const char **name = cast(const char**, dlsym(lib, "rl_readline_name"));
  414. if (name != NULL)
  415. *name = "lua";
  416. l_readline = cast(l_readlineT, cast_func(dlsym(lib, "readline")));
  417. l_addhist = cast(l_addhistT, cast_func(dlsym(lib, "add_history")));
  418. if (l_readline == NULL)
  419. lua_warning(L, "unable to load 'readline'", 0);
  420. }
  421. }
  422. #else /* }{ */
  423. /* no dlopen or LUA_READLINELIB undefined */
  424. /* Leave pointers with NULL */
  425. #define lua_initreadline(L) ((void)L)
  426. #endif /* } */
  427. #endif /* } */
  428. #endif /* } */
  429. /*
  430. ** Return the string to be used as a prompt by the interpreter. Leave
  431. ** the string (or nil, if using the default value) on the stack, to keep
  432. ** it anchored.
  433. */
  434. static const char *get_prompt (lua_State *L, int firstline) {
  435. if (lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2") == LUA_TNIL)
  436. return (firstline ? LUA_PROMPT : LUA_PROMPT2); /* use the default */
  437. else { /* apply 'tostring' over the value */
  438. const char *p = luaL_tolstring(L, -1, NULL);
  439. lua_remove(L, -2); /* remove original value */
  440. return p;
  441. }
  442. }
  443. /* mark in error messages for incomplete statements */
  444. #define EOFMARK "<eof>"
  445. #define marklen (sizeof(EOFMARK)/sizeof(char) - 1)
  446. /*
  447. ** Check whether 'status' signals a syntax error and the error
  448. ** message at the top of the stack ends with the above mark for
  449. ** incomplete statements.
  450. */
  451. static int incomplete (lua_State *L, int status) {
  452. if (status == LUA_ERRSYNTAX) {
  453. size_t lmsg;
  454. const char *msg = lua_tolstring(L, -1, &lmsg);
  455. if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0)
  456. return 1;
  457. }
  458. return 0; /* else... */
  459. }
  460. /*
  461. ** Prompt the user, read a line, and push it into the Lua stack.
  462. */
  463. static int pushline (lua_State *L, int firstline) {
  464. char buffer[LUA_MAXINPUT];
  465. size_t l;
  466. const char *prmt = get_prompt(L, firstline);
  467. char *b = lua_readline(buffer, prmt);
  468. lua_pop(L, 1); /* remove prompt */
  469. if (b == NULL)
  470. return 0; /* no input */
  471. l = strlen(b);
  472. if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
  473. b[--l] = '\0'; /* remove it */
  474. lua_pushlstring(L, b, l);
  475. lua_freeline(b);
  476. return 1;
  477. }
  478. /*
  479. ** Try to compile line on the stack as 'return <line>;'; on return, stack
  480. ** has either compiled chunk or original line (if compilation failed).
  481. */
  482. static int addreturn (lua_State *L) {
  483. const char *line = lua_tostring(L, -1); /* original line */
  484. const char *retline = lua_pushfstring(L, "return %s;", line);
  485. int status = luaL_loadbuffer(L, retline, strlen(retline), "=stdin");
  486. if (status == LUA_OK)
  487. lua_remove(L, -2); /* remove modified line */
  488. else
  489. lua_pop(L, 2); /* pop result from 'luaL_loadbuffer' and modified line */
  490. return status;
  491. }
  492. static void checklocal (const char *line) {
  493. static const size_t szloc = sizeof("local") - 1;
  494. static const char space[] = " \t";
  495. line += strspn(line, space); /* skip spaces */
  496. if (strncmp(line, "local", szloc) == 0 && /* "local"? */
  497. strchr(space, *(line + szloc)) != NULL) { /* followed by a space? */
  498. lua_writestringerror("%s\n",
  499. "warning: locals do not survive across lines in interactive mode");
  500. }
  501. }
  502. /*
  503. ** Read multiple lines until a complete Lua statement or an error not
  504. ** for an incomplete statement. Start with first line already read in
  505. ** the stack.
  506. */
  507. static int multiline (lua_State *L) {
  508. size_t len;
  509. const char *line = lua_tolstring(L, 1, &len); /* get first line */
  510. checklocal(line);
  511. for (;;) { /* repeat until gets a complete statement */
  512. int status = luaL_loadbuffer(L, line, len, "=stdin"); /* try it */
  513. if (!incomplete(L, status) || !pushline(L, 0))
  514. return status; /* should not or cannot try to add continuation line */
  515. lua_remove(L, -2); /* remove error message (from incomplete line) */
  516. lua_pushliteral(L, "\n"); /* add newline... */
  517. lua_insert(L, -2); /* ...between the two lines */
  518. lua_concat(L, 3); /* join them */
  519. line = lua_tolstring(L, 1, &len); /* get what is has */
  520. }
  521. }
  522. /*
  523. ** Read a line and try to load (compile) it first as an expression (by
  524. ** adding "return " in front of it) and second as a statement. Return
  525. ** the final status of load/call with the resulting function (if any)
  526. ** in the top of the stack.
  527. */
  528. static int loadline (lua_State *L) {
  529. const char *line;
  530. int status;
  531. lua_settop(L, 0);
  532. if (!pushline(L, 1))
  533. return -1; /* no input */
  534. if ((status = addreturn(L)) != LUA_OK) /* 'return ...' did not work? */
  535. status = multiline(L); /* try as command, maybe with continuation lines */
  536. line = lua_tostring(L, 1);
  537. if (line[0] != '\0') /* non empty? */
  538. lua_saveline(line); /* keep history */
  539. lua_remove(L, 1); /* remove line from the stack */
  540. lua_assert(lua_gettop(L) == 1);
  541. return status;
  542. }
  543. /*
  544. ** Prints (calling the Lua 'print' function) any values on the stack
  545. */
  546. static void l_print (lua_State *L) {
  547. int n = lua_gettop(L);
  548. if (n > 0) { /* any result to be printed? */
  549. luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
  550. lua_getglobal(L, "print");
  551. lua_insert(L, 1);
  552. if (lua_pcall(L, n, 0, 0) != LUA_OK)
  553. l_message(progname, lua_pushfstring(L, "error calling 'print' (%s)",
  554. lua_tostring(L, -1)));
  555. }
  556. }
  557. /*
  558. ** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and
  559. ** print any results.
  560. */
  561. static void doREPL (lua_State *L) {
  562. int status;
  563. const char *oldprogname = progname;
  564. progname = NULL; /* no 'progname' on errors in interactive mode */
  565. lua_initreadline(L);
  566. while ((status = loadline(L)) != -1) {
  567. if (status == LUA_OK)
  568. status = docall(L, 0, LUA_MULTRET);
  569. if (status == LUA_OK) l_print(L);
  570. else report(L, status);
  571. }
  572. lua_settop(L, 0); /* clear stack */
  573. lua_writeline();
  574. progname = oldprogname;
  575. }
  576. /* }================================================================== */
  577. #if !defined(luai_openlibs)
  578. #define luai_openlibs(L) luaL_openselectedlibs(L, ~0, 0)
  579. #endif
  580. /*
  581. ** Main body of stand-alone interpreter (to be called in protected mode).
  582. ** Reads the options and handles them all.
  583. */
  584. static int pmain (lua_State *L) {
  585. int argc = (int)lua_tointeger(L, 1);
  586. char **argv = (char **)lua_touserdata(L, 2);
  587. int script;
  588. int args = collectargs(argv, &script);
  589. int optlim = (script > 0) ? script : argc; /* first argv not an option */
  590. luaL_checkversion(L); /* check that interpreter has correct version */
  591. if (args == has_error) { /* bad arg? */
  592. print_usage(argv[script]); /* 'script' has index of bad arg. */
  593. return 0;
  594. }
  595. if (args & has_v) /* option '-v'? */
  596. print_version();
  597. if (args & has_E) { /* option '-E'? */
  598. lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */
  599. lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
  600. }
  601. luai_openlibs(L); /* open standard libraries */
  602. createargtable(L, argv, argc, script); /* create table 'arg' */
  603. lua_gc(L, LUA_GCRESTART); /* start GC... */
  604. lua_gc(L, LUA_GCGEN); /* ...in generational mode */
  605. if (!(args & has_E)) { /* no option '-E'? */
  606. if (handle_luainit(L) != LUA_OK) /* run LUA_INIT */
  607. return 0; /* error running LUA_INIT */
  608. }
  609. if (!runargs(L, argv, optlim)) /* execute arguments -e, -l, and -W */
  610. return 0; /* something failed */
  611. if (script > 0) { /* execute main script (if there is one) */
  612. if (handle_script(L, argv + script) != LUA_OK)
  613. return 0; /* interrupt in case of error */
  614. }
  615. if (args & has_i) /* -i option? */
  616. doREPL(L); /* do read-eval-print loop */
  617. else if (script < 1 && !(args & (has_e | has_v))) { /* no active option? */
  618. if (lua_stdin_is_tty()) { /* running in interactive mode? */
  619. print_version();
  620. doREPL(L); /* do read-eval-print loop */
  621. }
  622. else dofile(L, NULL); /* executes stdin as a file */
  623. }
  624. lua_pushboolean(L, 1); /* signal no errors */
  625. return 1;
  626. }
  627. int main (int argc, char **argv) {
  628. int status, result;
  629. lua_State *L = luaL_newstate(); /* create state */
  630. if (L == NULL) {
  631. l_message(argv[0], "cannot create state: not enough memory");
  632. return EXIT_FAILURE;
  633. }
  634. lua_gc(L, LUA_GCSTOP); /* stop GC while building state */
  635. lua_pushcfunction(L, &pmain); /* to call 'pmain' in protected mode */
  636. lua_pushinteger(L, argc); /* 1st argument */
  637. lua_pushlightuserdata(L, argv); /* 2nd argument */
  638. status = lua_pcall(L, 2, 1, 0); /* do the call */
  639. result = lua_toboolean(L, -1); /* get result */
  640. report(L, status);
  641. lua_close(L);
  642. return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
  643. }