lua-users home
lua-l archive

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

You can try something like that :

-- Start of Lua ----------------------------
with = function(context)
   local oldenv = getfenv(2)
   local newenv = {}
   setmetatable(newenv, {
      -- Save env to restore it later
      __oldenv = oldenv;
      -- Reads look at context first, then look at global
      __index = function(t, k)
         local v = context[k]
         -- if k exist in context use it
         if v~=nil then
            return v
         -- else return the global one
            return oldenv[k]
      -- Writes check if variable are globals, and if not found create/overwrite in context
      __newindex = function(t, k, v)
         -- if k exist in globals, replace it
         if context[k]==nil and oldenv[k]~=nil then
            oldenv[k] = v
         -- else put it in context
            context[k] = v
   setfenv(2, newenv)

endwith = function()
   local newenv = getfenv(2)
   local oldenv = getmetatable(newenv).__oldenv
   setfenv(2, oldenv)

-- You can then write
with (object) do

-- End of Lua ------------------------------

Globals can still be accessed directly if not overriden in object, or through _G inconditionnaly. Endwith is the only syntactic drawback, you have to explictly restore the environment. As the do/end is not necessary, you can just write:

with (object)

-----Message d'origine-----
De : [] De la part de Daniel Herkert
Envoyé : 15 septembre 2006 14:23
À :
Objet : Syntax addition: with ... do

I just found lua and tough I´m lovin it, something is still missing. I find myself writin lots of code similar to

Theres a quite a load of repeating 'object' there..
Could there be a new command introduced to handle

with object do

This would clean up code a lot and make it more readable imho.
As i understand similar behaviour could already be done with setting the enviroment as 'object', but with the downside of losing all the global functions etc.

I dont know if the idea im introducing has been discussed or if theres a smarter way, but do you have any toughts about this idea?

Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around