lua-users home
lua-l archive

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


Actually if you limit push_env_table and pop_env_table scope to a
function, it is better to set them as local. That prevent loaded
module from redefining pop_env_table.

Now that I see a concrete example, a question comes to my mind : does
a called function (in that case require) has any mean to access the
local variables of one of its caller ? I would say that no since the
local variables are not part of any environment. Is that right ?

2006/5/5, Daniel Collins <daniel.collins@internode.on.net>:

> This sounds potentially viable (the second idea), however I am still
pretty new to lua,
> could you explain in more detail how I would do it?

Jerome's post shows a neat way to set the environment before loading the
file. That way you don't need to modify the files at all. So you can
have them run in a shared environment if needed, or they can have their
own environment. I would probably put Jerome's solution in a function
(untested):

function requireNewEnv(file, env)

        function push_env_table(t)
                local g = getfenv(0)
                setmetatable(t, {__index=g})
                setfenv(0, t)
        end

        function pop_env_table()
                local t = getfenv(0)
                local g = getmetatable(t).__index
                setfenv(0, g)
        end

        newenv = env or {}
        push_env_table(newenv)
        require(file)
        pop_env_table()
end

I will be facing a similar situation to this in my project, but haven't
built my engine sufficiently to have needed a solution. I am tending
towards using a new lua state for each level. It is slightly more heavy
handed and requires me to load all my libraries again, but that really
doesn't take that long in the context of loading a game level. And since
my game is running on mobile phones, I really need to keep the memory
use in check. Also, once I have finished a level, I will not ever need
any of its functions again while another level is running, so there is
no reason to keep those functions in memory while the new level runs
with a new environment table.

- DC