lua-users home
lua-l archive

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

2018-07-04 7:39 GMT+02:00 Steven K. <>:

> "global-by-default" is evil, no more to say.

I am nevertheless going to say something.

> I'm using Lua mostly embedded, just some globals to work and life with the environment. At this point if view, where are the benefits for me?

Global in Lua does not mean global in the sense other languages use
it. It means "if the block structure does not resolve the name, look
for it in _ENV."

It is a highly useful construct. For example:

local function myfunc(_ENV)
   -- equivalent of Pascal's 'with' statement
  x = 1
  y = 2

myfunc(t)  -- does t.x = 1, t.y = 2

If you really hate global-by-default, you can disable it easily.

local next, io, print = next, io, print
--  etc: first cache all the globals you need
local _ENV = setmetatable({},{__index=error, __newindex=error})

You now need to say rawset(_ENV,key,value) to define a global
variable, but once you have done it, normal indexing works as usual.

If you really want it to look nice,

local global = function(key)
  rawset(_ENV,key,value) = '[exists]'

allows the syntax global'var' to define a new global.