lua-users home
lua-l archive

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


Ricky Haggett escribió:

Hey folks,

 

I’m working on a game which uses lua extensively, on a platform where memory is limited, and loading is slow, so I’d like to minimise my memory footprint and load times..

 

When the game starts, I create a lua vm, and load a bunch of global scripts that I want to keep around for the duration of the game..

 

Then each level has a .lua script file containing the script just for that level – a whole bunch of functions and tables.

 

Ideally, I’d be able to isolate the level-specific functions from the global ones, and then between levels set the level-specific functions/tables to nil and do a lua garbage collect – so the memory for the level-specific scripts gets cleaned up but the global stuff stays around - I don’t want to destroy / recreate my lua vm between levels or set the whole of global to nil, because this hurts my load times.

 

Is there a way of doing this programmatically? I was thinking maybe I could compare the state of global before and after loading a level-script to figure out the level specific stuff? But maybe there’s an easier way?

 

Cheers,

 

Ricky

I usually use something like this, to provide a closed execution environment to user scripts and eliminate unnecesary scripts and data.
Good luck!!


function createScriptEnvironment(scriptName,available_functions)
    local file,script
    local proc,err
    local environment={}
    environment._G = environment
    for k,v in pairs(available_functions or {}) do
        environment[k]=v
    end
    file = io.open(scriptName,"rb")
    if file then
        script = file:read("*a");
        io.close(file);
        proc,err = loadstring(script)
        if err then
            error(err)
        end
   
        setfenv(proc,environment)
        local _,err = pcall(proc)
        if err then
            error(err)
        end
        return environment
    else
        error("Cant open script " .. scriptName);
    end
end
gamelevel = createScriptEnvironment("levelone.lua",{
    print=print;                                        -- api to be available into game level scripts
    io = io;
    string = string;
    table = table;
    -- etc etc etc
})
if gamelevel.start then
    gamelevel.start()
else
    error ("can't find entry point 'start' at current game level")
end
gamelevel = nil                                            -- dispose all script data
collectgarbage();


------- levelone.lua
-- level one test
a = {}
foo = {1,2,3,4,5}
function start()
    print("Level ONE")
end