lua-users home
lua-l archive

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

On Wed, Mar 24, 2010 at 8:18 AM, Ricky Haggett <> wrote:
> I don't think having level.doSomething adds much to the readability. To give
> a more concrete (and made up :) example, say there's a level (defined in
> level1.xml and level1.lua) which contains a purple teapot. And the xml tag
> which describes the purple teapot might have an attribute
> luaClickedFunction="purpleTeapotClicked".  I don't see any benefit in having
> the designer prefix every level specific function they call with 'level1.' -
> this will just cause more confusion - it's obvious from the context of the
> functions and objectnames whether something is a global or level-specific..
> ideally the solution would be completely transparent at the level design
> level.
> Ricky

You could run the scripts marked in the XML files using the level
table as your execution environment, following Enrico's technique.
Something like this:

  local function inner_exec()
  function level_exec(leve)
    setfenv(inner_exec, level)
    return inner_exec()

level = {}

-- load the file
local func = assert(loadfile("lev1.lua"))
setfenv(func, level)
local r, err = pcall(func)
r = r or error('error reading level: ' .. err)

 -- do stuff in the context of the level

That's the basic idea, anyways... Notice how inner_exec calls
dosomething(), not level.dosomething(), because when it's its
environment is the same as the level file's. You could make that
function as simple or complex as you want, or use a closure per level
instead of sharing the same one, but that's the basic idea.