lua-users home
lua-l archive

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


Ricky Haggett wrote:
How would I go about loading the level script into a table?

Here is a simple example. This is your level:

-------------------------
-- this is "level1.lua"

function a()
    b()
end

function b()
    print("Ships: " .. ships)
end

ships = 5

-------------------------

and this is the level loader:

-------------------------
-- this is "loader.lua"

level = {} -- the table containing a level

-- read "lev1.lua" into level
local t = assert(loadfile("lev1.lua")) -- could use loadstring
setfenv(t, level)
local r, err = pcall(t) -- execute loaded chunk to define stuff
r = r or error('error reading level')

-- add global functions to level (just an example)
level.print = print

-- call function a() from outside the level table
level.a()

-------------------------

Also, if I used setfenv to change the environment, aren't I just moving the
problem? If I then have to add global functions to this same table, how will
I differentiate them from the level functions when I need to clean up?

No need to differentiate, just throw away the level table:

  level = nil

If you must access many global values/functions, a trick such as Steve suggested would be better than copying them to 'level'. The copy, on the other hand, allows fine control over global accesses (there are other, possibly better, intermediate solutions).

I am thinking maybe my solution is going to be (shallow) copying _G before
loading a level, then comparing the copy with _G after the level load. Any
objects which don't exist in the copy, but do exist in _G should be the
level-specific ones

Too much work, I prefer lazy solutions :-)

  Enrico