lua-users home
lua-l archive

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

I need to read up on environments as I don't really understand what
setfenv does.  Does your approach work with sharing data across

-----Original Message-----
[] On Behalf Of Nick Gammon
Sent: 11 August 2007 00:34
To: Lua list
Subject: Re: "Require" in a sandboxed environment

On 10/08/2007, at 6:13 PM, Tom Miles wrote:

> Therefore whenever I wanted to require a package, I did:
> utils = Require("utils")
> This would then always directly reference the table 
> package.loaded.utils
> However, this didn't work as I expected in some cases.

I'm not sure if this helps, but when writing an application recently I
found that if I did this:

a: require "b"
b: require "c"

(In other words, a indirectly acquires c)

.... that c didn't have b's context. I wrote this loader for loading the
submodules, which is a bit different to yours:

-- loader for modules to load sub-modules, in the module context
function my_loader (name)
   setfenv (assert (loadfile (
            string.format (MY_LUA_DIRECTORY .. "%s.lua", name))), _M) ()
end -- my_loader

my_loader "c"
my_loader "d"

This effectively lets me split my project into smaller pieces, however
sub-modules (like c and d) did not have the module function in them,
because they were really parts of module b, broken into smaller and more
manageable pieces.

Without the setfenv above, doing dofile did not load c into the b's
module context in the way I expected. Probably I should have researched
it more. :)

- Nick

This email is sent by The Creative Assembly Limited company No. 03425917, registered in England &Wales registered office 27 Great West Road, Middlesex, TW8 9BW, England. The contents of this e-mail and any attachments are confidential to the intended recipient and may also be legally privileged. Unless you are the named addressee (or authorised to receive for the addressee) of this email you may not copy, disclose or distribute it to anyone else. If you have received this email in error, please notify us immediately by e-mail on and then delete the email and any copies. The Creative Assembly Limited have made all reasonable efforts to ensure that this e-mail and any attached documents or software are free from software viruses, but it is the recipient's responsibility to confirm this.