lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Fri, Nov 6, 2009 at 3:20 PM, zweifel <zweifel@gmail.com> wrote:
> hey steve, that would be a better solution, but why my print(arg) returns
> nil? Ok, maybe I have not passed any arguments, but do I have to pass args
> in order to access the arg[0]??

Because it's only set by the Lua interpreter itself.  But you can
create your own args table, make it global and access that from your
script.

E.g. in lua.c:

  int narg = getargs(L, argv, n);  /* collect arguments */
  lua_setglobal(L, "arg");

where getargs() is

static int getargs (lua_State *L, char **argv, int n) {
  int narg;
  int i;
  int argc = 0;
  while (argv[argc]) argc++;  /* count total number of arguments */
  narg = argc - (n + 1);  /* number of arguments to the script */
  luaL_checkstack(L, narg + 3, "too many arguments to script");
  for (i=n+1; i < argc; i++)
    lua_pushstring(L, argv[i]);
  lua_createtable(L, narg, n + 1);
  for (i=0; i < argc; i++) {
    lua_pushstring(L, argv[i]);
    lua_rawseti(L, -2, i - n);
  }
  return narg;
}