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