lua-users home
lua-l archive

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


Gunnar Zötl wrote:
> 
> PH> So how does one now protect (as Gunnar wanted) submodules against accessing
> PH> the standard globals? This sounds like a *big* change from Lua4.
> 
> currently I create the new environment by copying(*) the current global
> environment. This scheme would have to be extended to set the global
> tables for all functions copied to the new global table for the time
> protected function is active, and them reset them to their previous
> values afterwards. I think special care would need to be taken for
> functions who already have their own global table. This is tedious,
> and involves a lot of table traversing, but it should work.
> 
> (*)= copying instead of using __index also protects the methods stored
> in a table from changes
> 
> Gunnar

What also seems to work is to use loadfile()
in stead of require() like this:

function safeload(filename,
glob)                                               
local
act                                                                       
glob = glob or
getglobals()                                                     
act =
function()                                                                
   local f,
e                                                                   
   f, e =
loadfile(filename)                                                    
   if f then return f()
else                                                    
   return nil,
e                                                                
  
end                                                                          
end                                                                             
setglobals(act,
glob)                                                           
return
act()                                                                    
end      


You'll have to copy all the global variables that your 
package functions need to the table glob, and
you don't get the nicety of "require", you have to 
specify the exacxt filename. 

Personally, I think that require should take a second 
argument which is the global table to be used for 
the required() filename. Of course, such a require could 
be written in Lua based on loadfile() but it would be nice 
to have it by default.



-- 
"No one knows true heroes, for they speak not of their greatness." -- 
Daniel Remar.
Björn De Meyer 
bjorn.demeyer@pandora.be