[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: How to pass arguments to argv function effectively in Lua C API
- From: Tony Finch <dot@...>
- Date: Thu, 24 Mar 2011 12:02:48 +0000
/* 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.