lua.c 19 KB

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