[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Implementing a simple sandbox -- another quirk
- From: Max Ischenko <max@...>
- Date: Tue, 24 Jun 2003 12:43:35 +0300
> > 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
return loadstring(string.format('return %s', spec))
> 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)
local retval = f()(unpack(arg))
SandBox['DATE'] = 20
SandBox['equals'] = equals
f = loadstring("return function() return equals() end")