PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/trunk/Examples/lua/lua.c

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