2
0

lua.c 22 KB

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