lua-users home
lua-l archive

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


I am trying to do all of this from C,
so that example doesn't really help me,
I especially don't know what __index is =/

as I understand it, i want to set my environment to a, 'temporary' one,
load the code, and then set it back (so i get all of my nice global variables and registred C functions and such)
is that right?  and if so how would I acomplish that in C?

thanks,

-Raymond

On 5/5/06, Daniel Collins <daniel.collins@internode.on.net> wrote:

> 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