lua-users home
lua-l archive

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


My preferred form of an explicit global is:

global x
function read()
  return x
end
function write()
  x = 1
end

Note, this would also be equivalent (it produces the same byte code):

function read()
  global x
  return x
end
function write()
  global x
  x = 1
end

The semantics of global is that it is treated the same as local when code is translated to byte code, only with a flag pointing out that it's global instead. When a variable is used which isn't found in the lookup table, it is an error (at load time). Note, _ENV.x would stay the same, since _ENV is always a local.

This resolves the inconsistency of having reads and writes be different.

It is more verbose, exclusively, since no declarations can be removed, only added, but that's the benefit to me (or at least, if I used it in practice and found issues with verbosity, I'd just avoid trying to have explicit globals because changing the default given the way the rest of Lua works doesn't really make sense).

The make_counter example doesn't change, because it doesn't use any globals:

function make_counter()
  local x = 1
  return function() x = x + 1; return x; end
end
_______________________________________________
lua-l mailing list -- lua-l@lists.lua.org
To unsubscribe send an email to lua-l-leave@lists.lua.org