lua-users home
lua-l archive

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


2013/4/16 Thomas Jericke <tjericke@indel.ch>:

> What would be great for me, is to ban globals as LHS values.
> One would have to write _ENV.print = function donotprint() end instead of
> print = function donotprint()
> but
>   print "hello"
> or
>   local x = print
> would still be allowed. I think that would be just fine because almost all
> mistakes with globals happen on the LHS. That means globals would be read
> only unless you access them via _ENV or _G.

You can do this already.

$ lua
Lua 5.2.2  Copyright (C) 1994-2013 Lua.org, PUC-Rio
> function assign(key,value) rawset(_G,key,value) end
> setmetatable(_ENV,{__newindex =
   function() error"Global LHS values are banned." end})
> x=1
stdin:2: Global LHS values are banned.
stack traceback:
	[C]: in function 'error'
	stdin:2: in function '__newindex'
	stdin:1: in main chunk
	[C]: in ?
> =x
nil
> assign('x',1)
> =x
1