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
         else
            return oldenv[k]
         end
      end;
      -- 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
         else
            context[k] = v
         end
      end;
   })
   setfenv(2, newenv)
end

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

-- You can then write
with (object) do
   name=parent.name..name
end
endwith()

-- 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)
   name=parent.name..name
   endwith()



-----Message d'origine-----
De : lua-bounces@bazar2.conectiva.com.br [mailto:lua-bounces@bazar2.conectiva.com.br] De la part de Daniel Herkert
Envoyé : 15 septembre 2006 14:23
À : lua@bazar2.conectiva.com.br
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

object.name=object.parent.name..object.name

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

with object do
   name=parent.name..name
   end

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 http://mail.yahoo.com