lua-users home
lua-l archive

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


Hi Jorge,

I'm not sure if there is a better way for doing so, but I solved the same problem that way:

1.) Call a handle_data function within the read() function of the socket:

	local s, error = client_socket:receive("*l")
	handle_data (s)

2.) Define your own environment within the handle function:
	
	local env = {}

    ... and bind the functions you want to be allowed ...
	
env.print = print -- print function in environment is the Lua builtin printing function
	...

3.) Call loadstring () and assign the resulting function to a variable. Don't execute directly. Instead, call a helping function try_call which sets the environment and calls pcall:
	
	result, error = loadstring (s)
   	if not error then
      	   try_call (result, env)
      	   return
   	end

	-----
	function try_call (result, env)
   	    setfenv (result, env)
   	    -- check if result() is a valid function
   	    if not pcall (result) then
		print ("Error!")
                return false
            end
            return true
	end

After setfenv () the function result knows *only* the functions and variables in env. The pcall () executes the function. This is what happens by

	loadstring(s)()

I hope that helps :-)

Cheers,
Eva


Jorge Visca wrote:
Hi to everyone.

My (lua) program gets a chunk trough the network, and loads it with
loadstring. I provide a set of functions for this piece of code, and i
want to  call some  functions  it declares. PiL recommends building a
protected environment for those cases. I guess it must be done using
scoping and redefining variables, and I was wondering what's the correct
method for that.
Is there a good example somewhere?

Thanks in advance,

Jorge