PageRenderTime 62ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/game/lua.c

https://github.com/UberGames/RPG-X2
C | 477 lines | 389 code | 63 blank | 25 comment | 121 complexity | 7f99723d83d5273cb0425bb4ecc06817 MD5 | raw file
  1. /*
  2. ** $Id: lua.c,v 1.194 2010/10/25 19:01:37 roberto Exp $
  3. ** Lua stand-alone interpreter
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <signal.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #define lua_c
  11. #include "lua.h"
  12. #include "lauxlib.h"
  13. #include "lualib.h"
  14. #if !defined(LUA_PROMPT)
  15. #define LUA_PROMPT "> "
  16. #define LUA_PROMPT2 ">> "
  17. #endif
  18. #if !defined(LUA_PROGNAME)
  19. #define LUA_PROGNAME "lua"
  20. #endif
  21. #if !defined(LUA_MAXINPUT)
  22. #define LUA_MAXINPUT 512
  23. #endif
  24. #if !defined(LUA_INIT)
  25. #define LUA_INIT "LUA_INIT"
  26. #endif
  27. #define LUA_INITVERSION \
  28. LUA_INIT "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
  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_USE_ISATTY)
  34. #include <unistd.h>
  35. #define lua_stdin_is_tty() isatty(0)
  36. #elif defined(LUA_WIN)
  37. #include <io.h>
  38. #include <stdio.h>
  39. #define lua_stdin_is_tty() _isatty(_fileno(stdin))
  40. #else
  41. #define lua_stdin_is_tty() 1 /* assume stdin is a tty */
  42. #endif
  43. /*
  44. ** lua_readline defines how to show a prompt and then read a line from
  45. ** the standard input.
  46. ** lua_saveline defines how to "save" a read line in a "history".
  47. ** lua_freeline defines how to free a line read by lua_readline.
  48. */
  49. #if defined(LUA_USE_READLINE)
  50. #include <stdio.h>
  51. #include <readline/readline.h>
  52. #include <readline/history.h>
  53. #define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL)
  54. #define lua_saveline(L,idx) \
  55. if (lua_rawlen(L,idx) > 0) /* non-empty line? */ \
  56. add_history(lua_tostring(L, idx)); /* add it to history */
  57. #define lua_freeline(L,b) ((void)L, free(b))
  58. #elif !defined(lua_readline)
  59. #define lua_readline(L,b,p) \
  60. ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \
  61. fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */
  62. #define lua_saveline(L,idx) { (void)L; (void)idx; }
  63. #define lua_freeline(L,b) { (void)L; (void)b; }
  64. #endif
  65. #if LUA_STANDALONE
  66. static lua_State *globalL = NULL;
  67. static const char *progname = LUA_PROGNAME;
  68. static void lstop (lua_State *L, lua_Debug *ar) {
  69. (void)ar; /* unused arg. */
  70. lua_sethook(L, NULL, 0, 0);
  71. luaL_error(L, "interrupted!");
  72. }
  73. static void laction (int i) {
  74. signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
  75. terminate process (default action) */
  76. lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
  77. }
  78. static void print_usage (const char *badoption) {
  79. if (badoption[1] == 'e' || badoption[1] == 'l') {
  80. luai_writestringerror("%s: ", progname);
  81. luai_writestringerror("'%s' needs argument\n", badoption);
  82. } else {
  83. luai_writestringerror("%s: ", progname);
  84. luai_writestringerror("unrecognized option '%s'\n", badoption);
  85. }
  86. luai_writestringerror(
  87. "usage: %s [options] [script [args]]\n"
  88. "Available options are:\n"
  89. " -e stat execute string " LUA_QL("stat") "\n"
  90. " -i enter interactive mode after executing " LUA_QL("script") "\n"
  91. " -l name require library " LUA_QL("name") "\n"
  92. " -v show version information\n"
  93. " -- stop handling options\n"
  94. " - stop handling options and execute stdin\n"
  95. ,
  96. progname);
  97. }
  98. static void l_message (const char *pname, const char *msg) {
  99. if (pname) luai_writestringerror("%s: ", pname);
  100. luai_writestringerror("%s\n", msg);
  101. }
  102. static int report (lua_State *L, int status) {
  103. if (status != LUA_OK && !lua_isnil(L, -1)) {
  104. const char *msg = lua_tostring(L, -1);
  105. if (msg == NULL) msg = "(error object is not a string)";
  106. l_message(progname, msg);
  107. lua_pop(L, 1);
  108. /* force a complete garbage collection in case of errors */
  109. lua_gc(L, LUA_GCCOLLECT, 0);
  110. }
  111. return status;
  112. }
  113. /* the next function is called unprotected, so it must avoid errors */
  114. static void finalreport (lua_State *L, int status) {
  115. if (status != LUA_OK) {
  116. const char *msg = (lua_type(L, -1) == LUA_TSTRING) ? lua_tostring(L, -1)
  117. : NULL;
  118. if (msg == NULL) msg = "(error object is not a string)";
  119. l_message(progname, msg);
  120. lua_pop(L, 1);
  121. }
  122. }
  123. static int traceback (lua_State *L) {
  124. const char *msg = lua_tostring(L, 1);
  125. if (msg)
  126. luaL_traceback(L, L, msg, 1);
  127. else if (!lua_isnoneornil(L, 1)) { /* is there an error object? */
  128. if (!luaL_callmeta(L, 1, "__tostring")) /* try its 'tostring' metamethod */
  129. lua_pushliteral(L, "(no error message)");
  130. }
  131. return 1;
  132. }
  133. static int docall (lua_State *L, int narg, int nres) {
  134. int status;
  135. int base = lua_gettop(L) - narg; /* function index */
  136. lua_pushcfunction(L, traceback); /* push traceback function */
  137. lua_insert(L, base); /* put it under chunk and args */
  138. globalL = L; /* to be available to 'laction' */
  139. signal(SIGINT, laction);
  140. status = lua_pcall(L, narg, nres, base);
  141. signal(SIGINT, SIG_DFL);
  142. lua_remove(L, base); /* remove traceback function */
  143. return status;
  144. }
  145. static void print_version (void) {
  146. printf("%s\n", LUA_COPYRIGHT);
  147. }
  148. static int getargs (lua_State *L, char **argv, int n) {
  149. int narg;
  150. int i;
  151. int argc = 0;
  152. while (argv[argc]) argc++; /* count total number of arguments */
  153. narg = argc - (n + 1); /* number of arguments to the script */
  154. luaL_checkstack(L, narg + 3, "too many arguments to script");
  155. for (i=n+1; i < argc; i++)
  156. lua_pushstring(L, argv[i]);
  157. lua_createtable(L, narg, n + 1);
  158. for (i=0; i < argc; i++) {
  159. lua_pushstring(L, argv[i]);
  160. lua_rawseti(L, -2, i - n);
  161. }
  162. return narg;
  163. }
  164. static int dofile (lua_State *L, const char *name) {
  165. int status = luaL_loadfile(L, name);
  166. if (status == LUA_OK) status = docall(L, 0, 0);
  167. return report(L, status);
  168. }
  169. static int dostring (lua_State *L, const char *s, const char *name) {
  170. int status = luaL_loadbuffer(L, s, strlen(s), name);
  171. if (status == LUA_OK) status = docall(L, 0, 0);
  172. return report(L, status);
  173. }
  174. static int dolibrary (lua_State *L, const char *name) {
  175. int status;
  176. lua_pushglobaltable(L);
  177. lua_getfield(L, -1, "require");
  178. lua_pushstring(L, name);
  179. status = docall(L, 1, 1);
  180. if (status == LUA_OK) {
  181. lua_setfield(L, -2, name); /* global[name] = require return */
  182. lua_pop(L, 1); /* remove global table */
  183. }
  184. else
  185. lua_remove(L, -2); /* remove global table (below error msg.) */
  186. return report(L, status);
  187. }
  188. static const char *get_prompt (lua_State *L, int firstline) {
  189. const char *p;
  190. lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2");
  191. p = lua_tostring(L, -1);
  192. if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
  193. lua_pop(L, 1); /* remove global */
  194. return p;
  195. }
  196. #endif
  197. /* mark in error messages for incomplete statements */
  198. #define mark "<eof>"
  199. #define marklen (sizeof(mark) - 1)
  200. #if LUA_STANDALONE
  201. static int incomplete (lua_State *L, int status) {
  202. if (status == LUA_ERRSYNTAX) {
  203. size_t lmsg;
  204. const char *msg = lua_tolstring(L, -1, &lmsg);
  205. if (lmsg >= marklen && strcmp(msg + lmsg - marklen, mark) == 0) {
  206. lua_pop(L, 1);
  207. return 1;
  208. }
  209. }
  210. return 0; /* else... */
  211. }
  212. static int pushline (lua_State *L, int firstline) {
  213. char buffer[LUA_MAXINPUT];
  214. char *b = buffer;
  215. size_t l;
  216. const char *prmt = get_prompt(L, firstline);
  217. if (lua_readline(L, b, prmt) == 0)
  218. return 0; /* no input */
  219. l = strlen(b);
  220. if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
  221. b[l-1] = '\0'; /* remove it */
  222. if (firstline && b[0] == '=') /* first line starts with `=' ? */
  223. lua_pushfstring(L, "return %s", b+1); /* change it to `return' */
  224. else
  225. lua_pushstring(L, b);
  226. lua_freeline(L, b);
  227. return 1;
  228. }
  229. static int loadline (lua_State *L) {
  230. int status;
  231. lua_settop(L, 0);
  232. if (!pushline(L, 1))
  233. return -1; /* no input */
  234. for (;;) { /* repeat until gets a complete line */
  235. size_t l;
  236. const char *line = lua_tolstring(L, 1, &l);
  237. status = luaL_loadbuffer(L, line, l, "=stdin");
  238. if (!incomplete(L, status)) break; /* cannot try to add lines? */
  239. if (!pushline(L, 0)) /* no more input? */
  240. return -1;
  241. lua_pushliteral(L, "\n"); /* add a new line... */
  242. lua_insert(L, -2); /* ...between the two lines */
  243. lua_concat(L, 3); /* join them */
  244. }
  245. lua_saveline(L, 1);
  246. lua_remove(L, 1); /* remove line */
  247. return status;
  248. }
  249. static void dotty (lua_State *L) {
  250. int status;
  251. const char *oldprogname = progname;
  252. progname = NULL;
  253. while ((status = loadline(L)) != -1) {
  254. if (status == LUA_OK) status = docall(L, 0, LUA_MULTRET);
  255. report(L, status);
  256. if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
  257. luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
  258. lua_getglobal(L, "print");
  259. lua_insert(L, 1);
  260. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != LUA_OK)
  261. l_message(progname, lua_pushfstring(L,
  262. "error calling " LUA_QL("print") " (%s)",
  263. lua_tostring(L, -1)));
  264. }
  265. }
  266. lua_settop(L, 0); /* clear stack */
  267. luai_writestring("\n", 1);
  268. progname = oldprogname;
  269. }
  270. static int handle_script (lua_State *L, char **argv, int n) {
  271. int status;
  272. const char *fname;
  273. int narg = getargs(L, argv, n); /* collect arguments */
  274. lua_setglobal(L, "arg");
  275. fname = argv[n];
  276. if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
  277. fname = NULL; /* stdin */
  278. status = luaL_loadfile(L, fname);
  279. lua_insert(L, -(narg+1));
  280. if (status == LUA_OK)
  281. status = docall(L, narg, LUA_MULTRET);
  282. else
  283. lua_pop(L, narg);
  284. return report(L, status);
  285. }
  286. #endif
  287. /* check that argument has no extra characters at the end */
  288. #define noextrachars(x) {if ((x)[2] != '\0') return -1;}
  289. #if LUA_STANDALONE
  290. static int collectargs (char **argv, int *pi, int *pv, int *pe) {
  291. int i;
  292. for (i = 1; argv[i] != NULL; i++) {
  293. if (argv[i][0] != '-') /* not an option? */
  294. return i;
  295. switch (argv[i][1]) { /* option */
  296. case '-':
  297. noextrachars(argv[i]);
  298. return (argv[i+1] != NULL ? i+1 : 0);
  299. case '\0':
  300. return i;
  301. case 'i':
  302. noextrachars(argv[i]);
  303. *pi = 1; /* go through */
  304. case 'v':
  305. noextrachars(argv[i]);
  306. *pv = 1;
  307. break;
  308. case 'e':
  309. *pe = 1; /* go through */
  310. case 'l': /* both options need an argument */
  311. if (argv[i][2] == '\0') { /* no concatenated argument? */
  312. i++; /* try next 'argv' */
  313. if (argv[i] == NULL || argv[i][0] == '-')
  314. return -(i - 1); /* no next argument or it is another option */
  315. }
  316. break;
  317. default: /* invalid option; return its index... */
  318. return -i; /* ...as a negative value */
  319. }
  320. }
  321. return 0;
  322. }
  323. static int runargs (lua_State *L, char **argv, int n) {
  324. int i;
  325. for (i = 1; i < n; i++) {
  326. lua_assert(argv[i][0] == '-');
  327. switch (argv[i][1]) { /* option */
  328. case 'e': {
  329. const char *chunk = argv[i] + 2;
  330. if (*chunk == '\0') chunk = argv[++i];
  331. lua_assert(chunk != NULL);
  332. if (dostring(L, chunk, "=(command line)") != LUA_OK)
  333. return 0;
  334. break;
  335. }
  336. case 'l': {
  337. const char *filename = argv[i] + 2;
  338. if (*filename == '\0') filename = argv[++i];
  339. lua_assert(filename != NULL);
  340. if (dolibrary(L, filename) != LUA_OK)
  341. return 0; /* stop if file fails */
  342. break;
  343. }
  344. default: break;
  345. }
  346. }
  347. return 1;
  348. }
  349. static int handle_luainit (lua_State *L) {
  350. const char *name = "=" LUA_INITVERSION;
  351. const char *init = getenv(name + 1);
  352. if (init == NULL) {
  353. name = "=" LUA_INIT;
  354. init = getenv(name + 1); /* try alternative name */
  355. }
  356. if (init == NULL) return LUA_OK;
  357. else if (init[0] == '@')
  358. return dofile(L, init+1);
  359. else
  360. return dostring(L, init, name);
  361. }
  362. static int pmain (lua_State *L) {
  363. int argc = (int)lua_tointeger(L, 1);
  364. char **argv = (char **)lua_touserdata(L, 2);
  365. int script;
  366. int has_i = 0, has_v = 0, has_e = 0;
  367. if (argv[0] && argv[0][0]) progname = argv[0];
  368. script = collectargs(argv, &has_i, &has_v, &has_e);
  369. if (script < 0) { /* invalid arg? */
  370. print_usage(argv[-script]);
  371. return 0;
  372. }
  373. if (has_v) print_version();
  374. /* open standard libraries */
  375. luaL_checkversion(L);
  376. lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
  377. luaL_openlibs(L); /* open libraries */
  378. lua_gc(L, LUA_GCRESTART, 0);
  379. /* run LUA_INIT */
  380. if (handle_luainit(L) != LUA_OK) return 0;
  381. /* execute arguments -e and -l */
  382. if (!runargs(L, argv, (script > 0) ? script : argc)) return 0;
  383. /* execute main script (if there is one) */
  384. if (script && handle_script(L, argv, script) != LUA_OK) return 0;
  385. if (has_i) /* -i option? */
  386. dotty(L);
  387. else if (script == 0 && !has_e && !has_v) { /* no arguments? */
  388. if (lua_stdin_is_tty()) {
  389. print_version();
  390. dotty(L);
  391. }
  392. else dofile(L, NULL); /* executes stdin as a file */
  393. }
  394. lua_pushboolean(L, 1); /* signal no errors */
  395. return 1;
  396. }
  397. int main (int argc, char **argv) {
  398. int status, result;
  399. lua_State *L = luaL_newstate(); /* create state */
  400. if (L == NULL) {
  401. l_message(argv[0], "cannot create state: not enough memory");
  402. return EXIT_FAILURE;
  403. }
  404. /* call 'pmain' in protected mode */
  405. lua_pushcfunction(L, &pmain);
  406. lua_pushinteger(L, argc); /* 1st argument */
  407. lua_pushlightuserdata(L, argv); /* 2nd argument */
  408. status = lua_pcall(L, 2, 1, 0);
  409. result = lua_toboolean(L, -1); /* get result */
  410. finalreport(L, status);
  411. lua_close(L);
  412. return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
  413. }
  414. #endif