lua-users home
lua-l archive

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


> >     f = loadstring("return equals()")
> >     xxx(f)

> Remember that the function "equals" also has its own environment. The
> sandbox call will not modify that one (only the environment of f, not
> of any nested calls.)

Aha! Now I got it.

> (Any reason why you don't simply define f by f = function() return equals()
> end ??)

I can't do this because the actual string is specified by the user.

However, I could do 
f = loadstring("return function() return equals() end")()

Actually, this is how it was a week ago (using dostring) ;)
Then I had posted a question about difference between dostring and
loadstring and had changed the code to it's current form.

As David Jones said:
 dostring will compile _and_ execute the string.

 loadstring will compile it and return a function that when called has
 the same effect as executing the string.

 In Lua 4.0 this 'return function() return ... end' was a way to achieve
 the delayed execution that loadstring already does in Lua 5.  In Lua 5.0 use

 function compile(spec)
   return loadstring(string.format('return %s', spec))
 end


> It is hard (if not impossible) to place a bunch of functions in a sandbox
> _after_ they have been defined.  The reason being exactly your problem
> above.  (I called this the "factorization problem" in some very old posting
> about function environments.)

> If a script must run sandboxed then the best you can do is load the script
> directly into the sandbox.  This can be done by a setfenv call on the chunk
> that is loaded by loadfile.

Sorry, for being dumb, but the following still prints nil:
 

function sandbox(env, f, ...)
 local g = getfenv(f)
 setfenv(f, env)
 local retval = f()(unpack(arg))
 setfenv(f, g)
 return retval
end

function equals()
	return DATE
end

function xxx(f)
 SandBox={}
 SandBox['DATE'] = 20
 SandBox['equals'] = equals
 print(sandbox(SandBox, f))
end

f = loadstring("return function() return equals() end")
xxx(f)



-- 
Regards, max.