lua-users home
lua-l archive

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

OK, I read the stuff people suggested on "sandbox" and environments, and 
I think I ALMOST understand it, but I've still got a couple of questions.

I've got a c program that embeds a lua interpreter that looks basically 
like this in the critical part:

	lua_dofile(L, "script1.lua");
	lua_dofile(L, "script2.lua");
	while (running)
		//retrieve function, which has to be packaged for script1
		lua_pushstring(L, "doSomething");
		lua_gettable (L, LUA_GLOBALSINDEX);
		//push argument
		lua_pushnumber(L, 23);
		//call function
		//retrieve return value
		lua_Number num = lua_tonumber(L, -1);
		//AND NOW I DO IT AGAIN FOR "doSomething" packaged for script2

and the lua scripts (both of them) essentially look like this:  

	somevar = 1

	function doSomething(num)
		mynum=mutate (num)
		return mynum
	function mutate (innum)
		--dosomething with innum and return a result

What I need is some way to create namespaces for the stuff in each lua 
script that is loaded in with lua_dofile so that C can lua_call 
script1.doSomething and it will correctly call script1.mutate and use
the correct local variables and such.  

If I understand the "Programming in Lua" book in section 15.4, the 
solution is to create a custom environment for each of the chunks
read in by lua_dofile, using this little bit:

	local P={} --create an empty list as the environment
	package = P --??
	local _G = _G --make a local copy of the global environment in case I need 
                      --anything from it
	setfenv(1,P) --set environment of this "function"

Right?  A couple of questions, though.

1) how is "local P={}; package=P" different from "local package = {}"?
2) WHERE do I put the packaging bit in the script files?  At the top, 
   ahead of the functions that get lua_called, or in the one that gets 
   lua_called?  If it goes in the function, any variables global to
   the script (like somevar) will in fact be global to L, right?
3) do I understand correctly that when I create an initial empty 
   environment I basically can't get to anything from the standard
   libraries and such, and therefore pretty much HAVE TO make
   local copies of everything I need before I setfenv?