new mechanism to access argv from a script

This commit is contained in:
Roberto Ierusalimschy 1999-08-18 14:40:54 -03:00
parent 2a03170ebd
commit b2c89ed2d2

35
lua.c
View File

@ -1,5 +1,5 @@
/* /*
** $Id: lua.c,v 1.21 1999/07/02 18:22:38 roberto Exp roberto $ ** $Id: lua.c,v 1.22 1999/08/16 20:52:00 roberto Exp roberto $
** Lua stand-alone interpreter ** Lua stand-alone interpreter
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@ -69,8 +69,9 @@ static void print_message (void) {
" -e stat dostring `stat'\n" " -e stat dostring `stat'\n"
" -q interactive mode without prompt\n" " -q interactive mode without prompt\n"
" -i interactive mode with prompt\n" " -i interactive mode with prompt\n"
" - executes stdin as a file\n" " - execute stdin as a file\n"
" a=b sets global `a' with string `b'\n" " -- start arguments for table `arg'\n"
" a=b set global `a' with string `b'\n"
" name dofile `name'\n\n"); " name dofile `name'\n\n");
} }
@ -89,6 +90,27 @@ static void assign (char *arg) {
} }
static void getargs (int argc, char *argv[]) {
int i, j;
lua_Object args = lua_createtable();
lua_pushobject(args);
lua_setglobal("arg");
for (i=0; i<argc; i++)
if (strcmp(argv[i], "--") == 0) break;
for (j = 0; j<argc; j++) {
/* arg[j-i] = argv[j] */
lua_pushobject(args); lua_pushnumber(j-i);
lua_pushstring(argv[j]); lua_settable();
}
/* arg.n = maximum index in table `arg' */
lua_pushobject(args); lua_pushstring("n");
lua_pushnumber(argc-(i+1)); lua_settable();
/* arg.nn = minimum index in table `arg' */
lua_pushobject(args); lua_pushstring("nn");
lua_pushnumber(-i); lua_settable();
}
static void manual_input (int prompt) { static void manual_input (int prompt) {
int cont = 1; int cont = 1;
while (cont) { while (cont) {
@ -122,12 +144,12 @@ static void manual_input (int prompt) {
} }
int main (int argc, char *argv[]) int main (int argc, char *argv[]) {
{
int i; int i;
lua_open(); lua_open();
lua_pushstring("> "); lua_setglobal("_PROMPT"); lua_pushstring("> "); lua_setglobal("_PROMPT");
lua_userinit(); lua_userinit();
getargs(argc, argv);
if (argc < 2) { /* no arguments? */ if (argc < 2) { /* no arguments? */
if (isatty(0)) { if (isatty(0)) {
printf("%s %s\n", LUA_VERSION, LUA_COPYRIGHT); printf("%s %s\n", LUA_VERSION, LUA_COPYRIGHT);
@ -162,6 +184,9 @@ int main (int argc, char *argv[])
return 1; return 1;
} }
break; break;
case '-':
i = argc; /* end loop */
break;
default: default:
print_message(); print_message();
exit(1); exit(1);