lua-users home
lua-l archive

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


/* copy arguments from lo to end of stack into an argv array with an array
   of argument lengths. return argc, argv, and argl in the pointers provided */

void argv_from_lua(lua_State *L, int lo,
                   int *argc_r, char ***argv_r, size_t **argl_r)
  size_t  args_size, argv_size, argl_size, *argl, len;
  char **argv, *args, *arg;
  int argc, a;

  int hi = lua_gettop(L);

  /* calculate sizes of arrays */
  argc = hi - lo + 1;
  argl_size = argc * sizeof(size_t);
  argv_size = (argc + 1) * sizeof(char *);
  args_size = 0;
  for(a = 0; a < argc; a++) {
    luaL_checklstring(L, lo+a, &len);
    args_size += len + 1;
  }

  /* lay out all the arrays within a userdata object */
  /* allocation errors and freeing are handled by lua */
  args = lua_newuserdata(L, total);
  argv = (void *)(args + args_size);
  argl = (void *)(args + args_size + argv_size);

  /* copy the argument data into the arrays */
  for(a = 0; a < argc; a++) {
    arg = lua_tolstring(L, lo+a, &len);
    memcpy(args, arg, len + 1);
    argl[a] = len;
    argv[a] = args;
    args += len + 1;
  }
  argv[argc] = NULL;

  if(argc_r) *argc_r = argc;
  if(argv_r) *argv_r = argv;
  if(argl_r) *argl_r = argl;
}

Tony.
-- 
f.anthony.n.finch  <dot@dotat.at>  http://dotat.at/
Hebrides, Bailey: West veering northwest 4 or 5. Moderate, occasionally rough
in north. Occasional rain. Moderate or good.