[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Call Lua functions without side effects
- From: "Alex Davies" <alex.mania@...>
- Date: Fri, 13 Jun 2008 02:55:34 +0800
Hey Peter,
Coming from other languages it's confusing, but in Lua function closures are
only created at runtime. Consider the following to see why this is
necessary:
eg:
local type = type; -- cache in an upvalue for speedier access
function foo(x)
print(type(x))
end
Without running the chunk, the upvalue is never set, the closure/function
never created and the global variable "foo" is not assigned.
So you're kind of asking to be able to assign global variables in a chunk,
solve for closure upvalues, and create closures, all whilst not causing any
side effects.
Pretty competing goals there. Furthermore in the above example, if the
global table has been assigned a metatable which defines __index or
__newindex virtually any kind of side effect is possible.
As others have said though, you can just run the script in a sandbox and
allow it to do anything it wants. But that solution is probably not ideal
either - as I imagine you want the "sub"functions to run with the standard
environment so that they can access your usual functions. Unfortunately it
is very challenging to change these environments for non-global functions
declared in the chunk.
One possible (and unportable between lua versions) solution would be to
quickly scan the main chunks code to ensure it doesn't perform any calls,
tailcalls or loops (to ensure it doesn't hang). That would be reasonable
safe, and allow most main chunks to be run without a problem. To make it
completely safe you could temporarily remove any metatables assigned to the
global table and any basic lua types (eg the string library). If this
solution appeals to you I could provide code, but you're better off finding
a more portable solution.
- Alex