lua-users home
lua-l archive

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


On Mon, Jun 02, 2003 at 02:06:53PM +0100, Mike Spencer wrote:
> i've noticed quite a few of you execute lua scripts from a command line and
> are able to specify arguments,
> i would like to do the same from within my C code...

luaL_loadfile creates a function of the file, but unfortunately does not
seem to pass parameters to it. What I do in Ion is create a new environment
for the function with the arguments in the arg table of that environment
and the metatable's __index and __newindex pointing to the original
(global) environment.

The following code (taken from ion/luaextl/luaextl.c) expects the function
to be on top of stack when entering and leaves the (unfilled) arg table
at top. What you then have to do is fill the table with the arguments
(lua_rawseti) and call the function with zero arguments.

	lua_newtable(st); /* Create arg */
	lua_newtable(st); /* Create new environment */
	lua_pushstring(st, "arg");
	lua_pushvalue(st, -3);
	lua_settable(st, -3); /* Set arg in the new environment */
	/* Now there's fn, arg, newenv in stack */
	lua_newtable(st); /* Create metatable */
	lua_pushstring(st, "__index");
	lua_getfenv(st, -5); /* Get old environment */
	lua_settable(st, -3); /* Set metatable.__index */
	lua_pushstring(st, "__newindex");
	lua_getfenv(st, -5); /* Get old environment */
	lua_settable(st, -3); /* Set metatable.__newindex */
	/* Now there's fn, arg, newenv, meta in stack */
	lua_setmetatable(st, -2); /* Set metatable for new environment */
	lua_setfenv(st, -3);
	/* Now there should be just fn, arg in stack */

-- 
Tuomo