PageRenderTime 50ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/rel-1.3.35/Examples/lua/lua.c

#
C | 439 lines | 339 code | 77 blank | 23 comment | 75 complexity | 19617bbbee4ded669d6f2e6ed8b50346 MD5 | raw file
Possible License(s): LGPL-2.1, Cube, GPL-3.0, 0BSD, GPL-2.0
  1. /*
  2. ** $Id: lua.c 7470 2005-09-20 19:35:23Z wsfulton $
  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. /*
  15. ** generic extra include file
  16. */
  17. #ifdef LUA_USERCONFIG
  18. #include LUA_USERCONFIG
  19. #endif
  20. /*
  21. ** definition of `isatty'
  22. */
  23. #ifdef _POSIX_C_SOURCE
  24. #include <unistd.h>
  25. #define stdin_is_tty() isatty(0)
  26. #else
  27. #define stdin_is_tty() 1 /* assume stdin is a tty */
  28. #endif
  29. #ifndef PROMPT
  30. #define PROMPT "> "
  31. #endif
  32. #ifndef PROMPT2
  33. #define PROMPT2 ">> "
  34. #endif
  35. #ifndef PROGNAME
  36. #define PROGNAME "lua"
  37. #endif
  38. #ifndef lua_userinit
  39. #define lua_userinit(L) openstdlibs(L)
  40. #endif
  41. #ifndef LUA_EXTRALIBS
  42. #define LUA_EXTRALIBS /* empty */
  43. #endif
  44. static lua_State *L = NULL;
  45. static const char *progname = PROGNAME;
  46. extern int Example_Init(lua_State* L);
  47. static const luaL_reg lualibs[] = {
  48. {"base", luaopen_base},
  49. {"table", luaopen_table},
  50. {"io", luaopen_io},
  51. {"string", luaopen_string},
  52. {"math", luaopen_math},
  53. {"debug", luaopen_debug},
  54. {"loadlib", luaopen_loadlib},
  55. /* add your libraries here */
  56. {"example", Example_Init},
  57. LUA_EXTRALIBS
  58. {NULL, NULL}
  59. };
  60. static void lstop (lua_State *l, lua_Debug *ar) {
  61. (void)ar; /* unused arg. */
  62. lua_sethook(l, NULL, 0, 0);
  63. luaL_error(l, "interrupted!");
  64. }
  65. static void laction (int i) {
  66. signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
  67. terminate process (default action) */
  68. lua_sethook(L, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
  69. }
  70. static void print_usage (void) {
  71. fprintf(stderr,
  72. "usage: %s [options] [script [args]].\n"
  73. "Available options are:\n"
  74. " - execute stdin as a file\n"
  75. " -e stat execute string `stat'\n"
  76. " -i enter interactive mode after executing `script'\n"
  77. " -l name load and run library `name'\n"
  78. " -v show version information\n"
  79. " -- stop handling options\n" ,
  80. progname);
  81. }
  82. static void l_message (const char *pname, const char *msg) {
  83. if (pname) fprintf(stderr, "%s: ", pname);
  84. fprintf(stderr, "%s\n", msg);
  85. }
  86. static int report (int status) {
  87. const char *msg;
  88. if (status) {
  89. msg = lua_tostring(L, -1);
  90. if (msg == NULL) msg = "(error with no message)";
  91. l_message(progname, msg);
  92. lua_pop(L, 1);
  93. }
  94. return status;
  95. }
  96. static int lcall (int narg, int clear) {
  97. int status;
  98. int base = lua_gettop(L) - narg; /* function index */
  99. lua_pushliteral(L, "_TRACEBACK");
  100. lua_rawget(L, LUA_GLOBALSINDEX); /* get traceback function */
  101. lua_insert(L, base); /* put it under chunk and args */
  102. signal(SIGINT, laction);
  103. status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
  104. signal(SIGINT, SIG_DFL);
  105. lua_remove(L, base); /* remove traceback function */
  106. return status;
  107. }
  108. static void print_version (void) {
  109. l_message(NULL, LUA_VERSION " " LUA_COPYRIGHT);
  110. }
  111. static void getargs (char *argv[], int n) {
  112. int i;
  113. lua_newtable(L);
  114. for (i=0; argv[i]; i++) {
  115. lua_pushnumber(L, i - n);
  116. lua_pushstring(L, argv[i]);
  117. lua_rawset(L, -3);
  118. }
  119. /* arg.n = maximum index in table `arg' */
  120. lua_pushliteral(L, "n");
  121. lua_pushnumber(L, i-n-1);
  122. lua_rawset(L, -3);
  123. }
  124. static int docall (int status) {
  125. if (status == 0) status = lcall(0, 1);
  126. return report(status);
  127. }
  128. static int file_input (const char *name) {
  129. return docall(luaL_loadfile(L, name));
  130. }
  131. static int dostring (const char *s, const char *name) {
  132. return docall(luaL_loadbuffer(L, s, strlen(s), name));
  133. }
  134. static int load_file (const char *name) {
  135. lua_pushliteral(L, "require");
  136. lua_rawget(L, LUA_GLOBALSINDEX);
  137. if (!lua_isfunction(L, -1)) { /* no `require' defined? */
  138. lua_pop(L, 1);
  139. return file_input(name);
  140. }
  141. else {
  142. lua_pushstring(L, name);
  143. return report(lcall(1, 1));
  144. }
  145. }
  146. /*
  147. ** this macro can be used by some `history' system to save lines
  148. ** read in manual input
  149. */
  150. #ifndef lua_saveline
  151. #define lua_saveline(L,line) /* empty */
  152. #endif
  153. /*
  154. ** this macro defines a function to show the prompt and reads the
  155. ** next line for manual input
  156. */
  157. #ifndef lua_readline
  158. #define lua_readline(L,prompt) readline(L,prompt)
  159. /* maximum length of an input line */
  160. #ifndef MAXINPUT
  161. #define MAXINPUT 512
  162. #endif
  163. static int readline (lua_State *l, const char *prompt) {
  164. static char buffer[MAXINPUT];
  165. if (prompt) {
  166. fputs(prompt, stdout);
  167. fflush(stdout);
  168. }
  169. if (fgets(buffer, sizeof(buffer), stdin) == NULL)
  170. return 0; /* read fails */
  171. else {
  172. lua_pushstring(l, buffer);
  173. return 1;
  174. }
  175. }
  176. #endif
  177. static const char *get_prompt (int firstline) {
  178. const char *p = NULL;
  179. lua_pushstring(L, firstline ? "_PROMPT" : "_PROMPT2");
  180. lua_rawget(L, LUA_GLOBALSINDEX);
  181. p = lua_tostring(L, -1);
  182. if (p == NULL) p = (firstline ? PROMPT : PROMPT2);
  183. lua_pop(L, 1); /* remove global */
  184. return p;
  185. }
  186. static int incomplete (int status) {
  187. if (status == LUA_ERRSYNTAX &&
  188. strstr(lua_tostring(L, -1), "near `<eof>'") != NULL) {
  189. lua_pop(L, 1);
  190. return 1;
  191. }
  192. else
  193. return 0;
  194. }
  195. static int load_string (void) {
  196. int status;
  197. lua_settop(L, 0);
  198. if (lua_readline(L, get_prompt(1)) == 0) /* no input? */
  199. return -1;
  200. if (lua_tostring(L, -1)[0] == '=') { /* line starts with `=' ? */
  201. lua_pushfstring(L, "return %s", lua_tostring(L, -1)+1);/* `=' -> `return' */
  202. lua_remove(L, -2); /* remove original line */
  203. }
  204. for (;;) { /* repeat until gets a complete line */
  205. status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
  206. if (!incomplete(status)) break; /* cannot try to add lines? */
  207. if (lua_readline(L, get_prompt(0)) == 0) /* no more input? */
  208. return -1;
  209. lua_concat(L, lua_gettop(L)); /* join lines */
  210. }
  211. lua_saveline(L, lua_tostring(L, 1));
  212. lua_remove(L, 1); /* remove line */
  213. return status;
  214. }
  215. static void manual_input (void) {
  216. int status;
  217. const char *oldprogname = progname;
  218. progname = NULL;
  219. while ((status = load_string()) != -1) {
  220. if (status == 0) status = lcall(0, 0);
  221. report(status);
  222. if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */
  223. lua_getglobal(L, "print");
  224. lua_insert(L, 1);
  225. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
  226. l_message(progname, lua_pushfstring(L, "error calling `print' (%s)",
  227. lua_tostring(L, -1)));
  228. }
  229. }
  230. lua_settop(L, 0); /* clear stack */
  231. fputs("\n", stdout);
  232. progname = oldprogname;
  233. }
  234. static int handle_argv (char *argv[], int *interactive) {
  235. if (argv[1] == NULL) { /* no more arguments? */
  236. if (stdin_is_tty()) {
  237. print_version();
  238. manual_input();
  239. }
  240. else
  241. file_input(NULL); /* executes stdin as a file */
  242. }
  243. else { /* other arguments; loop over them */
  244. int i;
  245. for (i = 1; argv[i] != NULL; i++) {
  246. if (argv[i][0] != '-') break; /* not an option? */
  247. switch (argv[i][1]) { /* option */
  248. case '-': { /* `--' */
  249. if (argv[i][2] != '\0') {
  250. print_usage();
  251. return 1;
  252. }
  253. i++; /* skip this argument */
  254. goto endloop; /* stop handling arguments */
  255. }
  256. case '\0': {
  257. file_input(NULL); /* executes stdin as a file */
  258. break;
  259. }
  260. case 'i': {
  261. *interactive = 1;
  262. break;
  263. }
  264. case 'v': {
  265. print_version();
  266. break;
  267. }
  268. case 'e': {
  269. const char *chunk = argv[i] + 2;
  270. if (*chunk == '\0') chunk = argv[++i];
  271. if (chunk == NULL) {
  272. print_usage();
  273. return 1;
  274. }
  275. if (dostring(chunk, "=<command line>") != 0)
  276. return 1;
  277. break;
  278. }
  279. case 'l': {
  280. const char *filename = argv[i] + 2;
  281. if (*filename == '\0') filename = argv[++i];
  282. if (filename == NULL) {
  283. print_usage();
  284. return 1;
  285. }
  286. if (load_file(filename))
  287. return 1; /* stop if file fails */
  288. break;
  289. }
  290. case 'c': {
  291. l_message(progname, "option `-c' is deprecated");
  292. break;
  293. }
  294. case 's': {
  295. l_message(progname, "option `-s' is deprecated");
  296. break;
  297. }
  298. default: {
  299. print_usage();
  300. return 1;
  301. }
  302. }
  303. } endloop:
  304. if (argv[i] != NULL) {
  305. const char *filename = argv[i];
  306. getargs(argv, i); /* collect arguments */
  307. lua_setglobal(L, "arg");
  308. return file_input(filename); /* stop scanning arguments */
  309. }
  310. }
  311. return 0;
  312. }
  313. static void openstdlibs (lua_State *l) {
  314. const luaL_reg *lib = lualibs;
  315. for (; lib->func; lib++) {
  316. lib->func(l); /* open library */
  317. lua_settop(l, 0); /* discard any results */
  318. }
  319. }
  320. static int handle_luainit (void) {
  321. const char *init = getenv("LUA_INIT");
  322. if (init == NULL) return 0; /* status OK */
  323. else if (init[0] == '@')
  324. return file_input(init+1);
  325. else
  326. return dostring(init, "=LUA_INIT");
  327. }
  328. struct Smain {
  329. int argc;
  330. char **argv;
  331. int status;
  332. };
  333. static int pmain (lua_State *l) {
  334. struct Smain *s = (struct Smain *)lua_touserdata(l, 1);
  335. int status;
  336. int interactive = 0;
  337. if (s->argv[0] && s->argv[0][0]) progname = s->argv[0];
  338. L = l;
  339. lua_userinit(l); /* open libraries */
  340. status = handle_luainit();
  341. if (status == 0) {
  342. status = handle_argv(s->argv, &interactive);
  343. if (status == 0 && interactive) manual_input();
  344. }
  345. s->status = status;
  346. return 0;
  347. }
  348. int main (int argc, char *argv[]) {
  349. int status;
  350. struct Smain s;
  351. lua_State *l = lua_open(); /* create state */
  352. if (l == NULL) {
  353. l_message(argv[0], "cannot create state: not enough memory");
  354. return EXIT_FAILURE;
  355. }
  356. s.argc = argc;
  357. s.argv = argv;
  358. status = lua_cpcall(l, &pmain, &s);
  359. report(status);
  360. lua_close(l);
  361. return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS;
  362. }