code for faking globals

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

code for faking globals

Luiz Henrique de Figueiredo
Here is the sort of code that I mentioned in my last message.
It has been tested and it works. :-)
Note how the use of upvalues protects the table G and the tag T.
They are not seen outside the do...end block and yet they remain accessible
to the tag methods.
Before upvalues, I'd have had to use a global var for G and T.
--lhf

-- shows how to redirect global variables to table fields

do
 local G={}				-- table to store all "globals"
 local T=newtag()			-- tag for "globals"
 local s=function (name,old,new)	-- setglobal tag method
	  %G[name]=settag({value=new},%T)
	 end
 local g=function(name,value)		-- getglobal tag method
	  return %G[name].value
	 end
 settagmethod(tag(nil),"setglobal",s)
 settagmethod(tag(nil),"getglobal",g)
 settagmethod(T,"setglobal",s)
 settagmethod(T,"getglobal",g)
end

x=1
print(x)
print(rawgetglobal"x")