lua-users home
lua-l archive

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



On 13/06/2008, at 4:01 AM, Peter LaDow wrote:

How can I load a Lua script and call a function without any other side
effects (such as executed code)?  Perhaps more like a compile and
load, without the execution?

The trouble is, take this function for example:

function foo()
  print "foo"
end

What that really is, is an assignment statement that needs to be executed for it to create the function, namely:

foo = function () print "foo" end

Without executing it, you merely have code that is capable of creating the function foo.

However as others have noted the global "print" doesn't have to exist to create the function, it merely compiles that it eventually needs "print" when foo is called.

This code will effectively weed out side-effect function calls:

-----------
sandbox = {} -- where to put their stuff

-- load the file, get a function to execute local f = assert (loadfile ("foo.lua"))

-- want to load file into the sandbox table
setfenv (f, sandbox)

-- execute to create functions, fail if globals called
assert (pcall (f), "side-effects attempted")

-- put environment back
setfenv (f, _G)

-- re-execute now we know we have no side-effects
f ()

-- now we can call the functions when we want to
foo ()  --> print "foo"
------------

This example loads the file foo.lua, creating function f which, when executed, creates your functions foo and bar.

What I have done here is first execute in a sandbox which has no globals defined, and thus they can't do print or anything else, except basic arithmetic and assignment.

If that succeeds, we put the global environment back and re-execute, giving us functions that now do know about the global environment.

You don't ever have to give them back the global environment, you can give them a limited environment with only the functions you choose available in it.

- Nick