lua-users home
lua-l archive

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


On Tue, May 12, 2020 at 4:30 PM Andrea <andrea.l.vitali@gmail.com> wrote:
2. Yes "local" makes scoping explicit, but from my programmer perspective "nonlocal" would do the same; but maybe I am missing something; can you elaborate more?

With nonlocal: The creation of a local scope is syntactically implicit: it's part of an assignment operation, which may or may not create a new scope. The nonlocal scopes contained within it are syntactically explicit because of the "nonlocal" keyword.

With local: The creation of a local scope is syntactically explicit. The nonlocal scopes contained within it are also syntactically explicit because of the syntax needed to create the scopes.

Bonus challenge: Consider the following code with a "nonlocal" syntax:

x = 1
if condition() then
  x = 2
end
print(x)

Does it output 1 or 2? Compare this to the following:

local x = 1
if condition() then
  x = 2
end
print(x)

x = 1
if condition() then
  local x = 2
end
print(x)

In other words, explicit nonlocal only makes sense if your syntactic scoping rules are a lot looser. Explicit local scopes can be created in any syntactic block. 
 
3. Unintentional shadowing: can you make some simple example? It seems to be that in both cases (explicit local or nonlocal) shadowing can happen and the programmer must know what he is doing. Also about static analysis: in which sense it is "easier" for the analysis tool? (sorry if this is a dumb question - I am learning by asking)

x = 1
function shadow()
  if condition() then
    x = 2
  end
  print(x) -- this is definitely 2...
end
shadow()
print(x) -- but is this 1 or 2?



On Tue, May 12, 2020 at 6:36 PM Ahmed Charles <acharles@outlook.com> wrote:
My preferred form of an explicit global is:

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

The problem with this syntax is that you still need a local keyword within functions in order to avoid namespace collisions. 

/s/ Adam
_______________________________________________
lua-l mailing list -- lua-l@lists.lua.org
To unsubscribe send an email to lua-l-leave@lists.lua.org