lua/lua.c

Go to the documentation of this file.
00001 /*
00002 ** $Id: lua.c,v 1.203 2011/12/12 16:34:03 roberto Exp $
00003 ** Lua stand-alone interpreter
00004 ** See Copyright Notice in lua.h
00005 */
00006 
00007 
00008 #include <signal.h>
00009 #include <stdio.h>
00010 #include <stdlib.h>
00011 #include <string.h>
00012 
00013 #define lua_c
00014 
00015 #include "lua.h"
00016 
00017 #include "lauxlib.h"
00018 #include "lualib.h"
00019 
00020 
00021 #if !defined(LUA_PROMPT)
00022 #define LUA_PROMPT      "> "
00023 #define LUA_PROMPT2     ">> "
00024 #endif
00025 
00026 #if !defined(LUA_PROGNAME)
00027 #define LUA_PROGNAME        "lua"
00028 #endif
00029 
00030 #if !defined(LUA_MAXINPUT)
00031 #define LUA_MAXINPUT        512
00032 #endif
00033 
00034 #if !defined(LUA_INIT)
00035 #define LUA_INIT        "LUA_INIT"
00036 #endif
00037 
00038 #define LUA_INITVERSION  \
00039     LUA_INIT "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
00040 
00041 
00042 /*
00043 ** lua_stdin_is_tty detects whether the standard input is a 'tty' (that
00044 ** is, whether we're running lua interactively).
00045 */
00046 #if defined(LUA_USE_ISATTY)
00047 #include <unistd.h>
00048 #define lua_stdin_is_tty()      isatty(0)
00049 #elif defined(LUA_WIN)
00050 #include <io.h>
00051 #include <stdio.h>
00052 #define lua_stdin_is_tty()      _isatty(_fileno(stdin))
00053 #else
00054 #define lua_stdin_is_tty()      1  /* assume stdin is a tty */
00055 #endif
00056 
00057 
00058 /*
00059 ** lua_readline defines how to show a prompt and then read a line from
00060 ** the standard input.
00061 ** lua_saveline defines how to "save" a read line in a "history".
00062 ** lua_freeline defines how to free a line read by lua_readline.
00063 */
00064 #if defined(LUA_USE_READLINE)
00065 
00066 #include <stdio.h>
00067 #include <readline/readline.h>
00068 #include <readline/history.h>
00069 #define lua_readline(L,b,p)     ((void)L, ((b)=readline(p)) != NULL)
00070 #define lua_saveline(L,idx) \
00071         if (lua_rawlen(L,idx) > 0)  /* non-empty line? */ \
00072           add_history(lua_tostring(L, idx));  /* add it to history */
00073 #define lua_freeline(L,b)       ((void)L, free(b))
00074 
00075 #elif !defined(lua_readline)
00076 
00077 #define lua_readline(L,b,p)     \
00078         ((void)L, fputs(p, stdout), fflush(stdout),  /* show prompt */ \
00079         fgets(b, LUA_MAXINPUT, stdin) != NULL)  /* get line */
00080 #define lua_saveline(L,idx)     { (void)L; (void)idx; }
00081 #define lua_freeline(L,b)       { (void)L; (void)b; }
00082 
00083 #endif
00084 
00085 
00086 
00087 
00088 static lua_State *globalL = NULL;
00089 
00090 static const char *progname = LUA_PROGNAME;
00091 
00092 
00093 
00094 static void lstop (lua_State *L, lua_Debug *ar) {
00095   (void)ar;  /* unused arg. */
00096   lua_sethook(L, NULL, 0, 0);
00097   luaL_error(L, "interrupted!");
00098 }
00099 
00100 
00101 static void laction (int i) {
00102   signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
00103                               terminate process (default action) */
00104   lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
00105 }
00106 
00107 
00108 static void print_usage (const char *badoption) {
00109   luai_writestringerror("%s: ", progname);
00110   if (badoption[1] == 'e' || badoption[1] == 'l')
00111     luai_writestringerror("'%s' needs argument\n", badoption);
00112   else
00113     luai_writestringerror("unrecognized option '%s'\n", badoption);
00114   luai_writestringerror(
00115   "usage: %s [options] [script [args]]\n"
00116   "Available options are:\n"
00117   "  -e stat  execute string " LUA_QL("stat") "\n"
00118   "  -i       enter interactive mode after executing " LUA_QL("script") "\n"
00119   "  -l name  require library " LUA_QL("name") "\n"
00120   "  -v       show version information\n"
00121   "  -E       ignore environment variables\n"
00122   "  --       stop handling options\n"
00123   "  -        stop handling options and execute stdin\n"
00124   ,
00125   progname);
00126 }
00127 
00128 
00129 static void l_message (const char *pname, const char *msg) {
00130   if (pname) luai_writestringerror("%s: ", pname);
00131   luai_writestringerror("%s\n", msg);
00132 }
00133 
00134 
00135 static int report (lua_State *L, int status) {
00136   if (status != LUA_OK && !lua_isnil(L, -1)) {
00137     const char *msg = lua_tostring(L, -1);
00138     if (msg == NULL) msg = "(error object is not a string)";
00139     l_message(progname, msg);
00140     lua_pop(L, 1);
00141     /* force a complete garbage collection in case of errors */
00142     lua_gc(L, LUA_GCCOLLECT, 0);
00143   }
00144   return status;
00145 }
00146 
00147 
00148 /* the next function is called unprotected, so it must avoid errors */
00149 static void finalreport (lua_State *L, int status) {
00150   if (status != LUA_OK) {
00151     const char *msg = (lua_type(L, -1) == LUA_TSTRING) ? lua_tostring(L, -1)
00152                                                        : NULL;
00153     if (msg == NULL) msg = "(error object is not a string)";
00154     l_message(progname, msg);
00155     lua_pop(L, 1);
00156   }
00157 }
00158 
00159 
00160 static int traceback (lua_State *L) {
00161   const char *msg = lua_tostring(L, 1);
00162   if (msg)
00163     luaL_traceback(L, L, msg, 1);
00164   else if (!lua_isnoneornil(L, 1)) {  /* is there an error object? */
00165     if (!luaL_callmeta(L, 1, "__tostring"))  /* try its 'tostring' metamethod */
00166       lua_pushliteral(L, "(no error message)");
00167   }
00168   return 1;
00169 }
00170 
00171 
00172 static int docall (lua_State *L, int narg, int nres) {
00173   int status;
00174   int base = lua_gettop(L) - narg;  /* function index */
00175   lua_pushcfunction(L, traceback);  /* push traceback function */
00176   lua_insert(L, base);  /* put it under chunk and args */
00177   globalL = L;  /* to be available to 'laction' */
00178   signal(SIGINT, laction);
00179   status = lua_pcall(L, narg, nres, base);
00180   signal(SIGINT, SIG_DFL);
00181   lua_remove(L, base);  /* remove traceback function */
00182   return status;
00183 }
00184 
00185 
00186 static void print_version (void) {
00187   luai_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
00188   luai_writeline();
00189 }
00190 
00191 
00192 static int getargs (lua_State *L, char **argv, int n) {
00193   int narg;
00194   int i;
00195   int argc = 0;
00196   while (argv[argc]) argc++;  /* count total number of arguments */
00197   narg = argc - (n + 1);  /* number of arguments to the script */
00198   luaL_checkstack(L, narg + 3, "too many arguments to script");
00199   for (i=n+1; i < argc; i++)
00200     lua_pushstring(L, argv[i]);
00201   lua_createtable(L, narg, n + 1);
00202   for (i=0; i < argc; i++) {
00203     lua_pushstring(L, argv[i]);
00204     lua_rawseti(L, -2, i - n);
00205   }
00206   return narg;
00207 }
00208 
00209 
00210 static int dofile (lua_State *L, const char *name) {
00211   int status = luaL_loadfile(L, name);
00212   if (status == LUA_OK) status = docall(L, 0, 0);
00213   return report(L, status);
00214 }
00215 
00216 
00217 static int dostring (lua_State *L, const char *s, const char *name) {
00218   int status = luaL_loadbuffer(L, s, strlen(s), name);
00219   if (status == LUA_OK) status = docall(L, 0, 0);
00220   return report(L, status);
00221 }
00222 
00223 
00224 static int dolibrary (lua_State *L, const char *name) {
00225   int status;
00226   lua_pushglobaltable(L);
00227   lua_getfield(L, -1, "require");
00228   lua_pushstring(L, name);
00229   status = docall(L, 1, 1);
00230   if (status == LUA_OK) {
00231     lua_setfield(L, -2, name);  /* global[name] = require return */
00232     lua_pop(L, 1);  /* remove global table */
00233   }
00234   else
00235     lua_remove(L, -2);  /* remove global table (below error msg.) */
00236   return report(L, status);
00237 }
00238 
00239 
00240 static const char *get_prompt (lua_State *L, int firstline) {
00241   const char *p;
00242   lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2");
00243   p = lua_tostring(L, -1);
00244   if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
00245   lua_pop(L, 1);  /* remove global */
00246   return p;
00247 }
00248 
00249 /* mark in error messages for incomplete statements */
00250 #define EOFMARK     "<eof>"
00251 #define marklen     (sizeof(EOFMARK)/sizeof(char) - 1)
00252 
00253 static int incomplete (lua_State *L, int status) {
00254   if (status == LUA_ERRSYNTAX) {
00255     size_t lmsg;
00256     const char *msg = lua_tolstring(L, -1, &lmsg);
00257     if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) {
00258       lua_pop(L, 1);
00259       return 1;
00260     }
00261   }
00262   return 0;  /* else... */
00263 }
00264 
00265 
00266 static int pushline (lua_State *L, int firstline) {
00267   char buffer[LUA_MAXINPUT];
00268   char *b = buffer;
00269   size_t l;
00270   const char *prmt = get_prompt(L, firstline);
00271   if (lua_readline(L, b, prmt) == 0)
00272     return 0;  /* no input */
00273   l = strlen(b);
00274   if (l > 0 && b[l-1] == '\n')  /* line ends with newline? */
00275     b[l-1] = '\0';  /* remove it */
00276   if (firstline && b[0] == '=')  /* first line starts with `=' ? */
00277     lua_pushfstring(L, "return %s", b+1);  /* change it to `return' */
00278   else
00279     lua_pushstring(L, b);
00280   lua_freeline(L, b);
00281   return 1;
00282 }
00283 
00284 
00285 static int loadline (lua_State *L) {
00286   int status;
00287   lua_settop(L, 0);
00288   if (!pushline(L, 1))
00289     return -1;  /* no input */
00290   for (;;) {  /* repeat until gets a complete line */
00291     size_t l;
00292     const char *line = lua_tolstring(L, 1, &l);
00293     status = luaL_loadbuffer(L, line, l, "=stdin");
00294     if (!incomplete(L, status)) break;  /* cannot try to add lines? */
00295     if (!pushline(L, 0))  /* no more input? */
00296       return -1;
00297     lua_pushliteral(L, "\n");  /* add a new line... */
00298     lua_insert(L, -2);  /* ...between the two lines */
00299     lua_concat(L, 3);  /* join them */
00300   }
00301   lua_saveline(L, 1);
00302   lua_remove(L, 1);  /* remove line */
00303   return status;
00304 }
00305 
00306 
00307 static void dotty (lua_State *L) {
00308   int status;
00309   const char *oldprogname = progname;
00310   progname = NULL;
00311   while ((status = loadline(L)) != -1) {
00312     if (status == LUA_OK) status = docall(L, 0, LUA_MULTRET);
00313     report(L, status);
00314     if (status == LUA_OK && lua_gettop(L) > 0) {  /* any result to print? */
00315       luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
00316       lua_getglobal(L, "print");
00317       lua_insert(L, 1);
00318       if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != LUA_OK)
00319         l_message(progname, lua_pushfstring(L,
00320                                "error calling " LUA_QL("print") " (%s)",
00321                                lua_tostring(L, -1)));
00322     }
00323   }
00324   lua_settop(L, 0);  /* clear stack */
00325   luai_writeline();
00326   progname = oldprogname;
00327 }
00328 
00329 
00330 static int handle_script (lua_State *L, char **argv, int n) {
00331   int status;
00332   const char *fname;
00333   int narg = getargs(L, argv, n);  /* collect arguments */
00334   lua_setglobal(L, "arg");
00335   fname = argv[n];
00336   if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
00337     fname = NULL;  /* stdin */
00338   status = luaL_loadfile(L, fname);
00339   lua_insert(L, -(narg+1));
00340   if (status == LUA_OK)
00341     status = docall(L, narg, LUA_MULTRET);
00342   else
00343     lua_pop(L, narg);
00344   return report(L, status);
00345 }
00346 
00347 
00348 /* check that argument has no extra characters at the end */
00349 #define noextrachars(x)     {if ((x)[2] != '\0') return -1;}
00350 
00351 
00352 /* indices of various argument indicators in array args */
00353 #define has_i       0   /* -i */
00354 #define has_v       1   /* -v */
00355 #define has_e       2   /* -e */
00356 #define has_E       3   /* -E */
00357 
00358 #define num_has     4   /* number of 'has_*' */
00359 
00360 
00361 static int collectargs (char **argv, int *args) {
00362   int i;
00363   for (i = 1; argv[i] != NULL; i++) {
00364     if (argv[i][0] != '-')  /* not an option? */
00365         return i;
00366     switch (argv[i][1]) {  /* option */
00367       case '-':
00368         noextrachars(argv[i]);
00369         return (argv[i+1] != NULL ? i+1 : 0);
00370       case '\0':
00371         return i;
00372       case 'E':
00373         args[has_E] = 1;
00374         break;
00375       case 'i':
00376         noextrachars(argv[i]);
00377         args[has_i] = 1;  /* go through */
00378       case 'v':
00379         noextrachars(argv[i]);
00380         args[has_v] = 1;
00381         break;
00382       case 'e':
00383         args[has_e] = 1;  /* go through */
00384       case 'l':  /* both options need an argument */
00385         if (argv[i][2] == '\0') {  /* no concatenated argument? */
00386           i++;  /* try next 'argv' */
00387           if (argv[i] == NULL || argv[i][0] == '-')
00388             return -(i - 1);  /* no next argument or it is another option */
00389         }
00390         break;
00391       default:  /* invalid option; return its index... */
00392         return -i;  /* ...as a negative value */
00393     }
00394   }
00395   return 0;
00396 }
00397 
00398 
00399 static int runargs (lua_State *L, char **argv, int n) {
00400   int i;
00401   for (i = 1; i < n; i++) {
00402     lua_assert(argv[i][0] == '-');
00403     switch (argv[i][1]) {  /* option */
00404       case 'e': {
00405         const char *chunk = argv[i] + 2;
00406         if (*chunk == '\0') chunk = argv[++i];
00407         lua_assert(chunk != NULL);
00408         if (dostring(L, chunk, "=(command line)") != LUA_OK)
00409           return 0;
00410         break;
00411       }
00412       case 'l': {
00413         const char *filename = argv[i] + 2;
00414         if (*filename == '\0') filename = argv[++i];
00415         lua_assert(filename != NULL);
00416         if (dolibrary(L, filename) != LUA_OK)
00417           return 0;  /* stop if file fails */
00418         break;
00419       }
00420       default: break;
00421     }
00422   }
00423   return 1;
00424 }
00425 
00426 
00427 static int handle_luainit (lua_State *L) {
00428   const char *name = "=" LUA_INITVERSION;
00429   const char *init = getenv(name + 1);
00430   if (init == NULL) {
00431     name = "=" LUA_INIT;
00432     init = getenv(name + 1);  /* try alternative name */
00433   }
00434   if (init == NULL) return LUA_OK;
00435   else if (init[0] == '@')
00436     return dofile(L, init+1);
00437   else
00438     return dostring(L, init, name);
00439 }
00440 
00441 
00442 static int pmain (lua_State *L) {
00443   int argc = (int)lua_tointeger(L, 1);
00444   char **argv = (char **)lua_touserdata(L, 2);
00445   int script;
00446   int args[num_has];
00447   args[has_i] = args[has_v] = args[has_e] = args[has_E] = 0;
00448   if (argv[0] && argv[0][0]) progname = argv[0];
00449   script = collectargs(argv, args);
00450   if (script < 0) {  /* invalid arg? */
00451     print_usage(argv[-script]);
00452     return 0;
00453   }
00454   if (args[has_v]) print_version();
00455   if (args[has_E]) {  /* option '-E'? */
00456     lua_pushboolean(L, 1);  /* signal for libraries to ignore env. vars. */
00457     lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
00458   }
00459   /* open standard libraries */
00460   luaL_checkversion(L);
00461   lua_gc(L, LUA_GCSTOP, 0);  /* stop collector during initialization */
00462   luaL_openlibs(L);  /* open libraries */
00463   lua_gc(L, LUA_GCRESTART, 0);
00464   if (!args[has_E] && handle_luainit(L) != LUA_OK)
00465     return 0;  /* error running LUA_INIT */
00466   /* execute arguments -e and -l */
00467   if (!runargs(L, argv, (script > 0) ? script : argc)) return 0;
00468   /* execute main script (if there is one) */
00469   if (script && handle_script(L, argv, script) != LUA_OK) return 0;
00470   if (args[has_i])  /* -i option? */
00471     dotty(L);
00472   else if (script == 0 && !args[has_e] && !args[has_v]) {  /* no arguments? */
00473     if (lua_stdin_is_tty()) {
00474       print_version();
00475       dotty(L);
00476     }
00477     else dofile(L, NULL);  /* executes stdin as a file */
00478   }
00479   lua_pushboolean(L, 1);  /* signal no errors */
00480   return 1;
00481 }
00482 
00483 
00484 int main (int argc, char **argv) {
00485   int status, result;
00486   lua_State *L = luaL_newstate();  /* create state */
00487   if (L == NULL) {
00488     l_message(argv[0], "cannot create state: not enough memory");
00489     return EXIT_FAILURE;
00490   }
00491   /* call 'pmain' in protected mode */
00492   lua_pushcfunction(L, &pmain);
00493   lua_pushinteger(L, argc);  /* 1st argument */
00494   lua_pushlightuserdata(L, argv); /* 2nd argument */
00495   status = lua_pcall(L, 2, 1, 0);
00496   result = lua_toboolean(L, -1);  /* get result */
00497   finalreport(L, status);
00498   lua_close(L);
00499   return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
00500 }
00501 
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines

Generated by doxygen 1.7.1 on Fri May 25 2012 01:03:04 for The Battle for Wesnoth
Gna! | Forum | Wiki | CIA | devdocs