Skip to content

Instantly share code, notes, and snippets.

@catwell
Last active December 16, 2015 14:49
Show Gist options
  • Save catwell/5451173 to your computer and use it in GitHub Desktop.
Save catwell/5451173 to your computer and use it in GitHub Desktop.
Why not "local by default".

Why "local by default" is wrong?

One of the main criticisms of Lua is that the scope of a variable is global by default. This is not perfect, and people who have worked with me know I don't like useless globals.

That being said, I think the solution some people advocate ("Do like Python!!1") is "wrong". Global by default is clumsy but it makes sense because there is only one global scope. Local by default and a "global" keyword causes aliasing issues because there are other levels of scope besides "local" and "global".

Instead of a long explanation, let's take an example: you cannot do this in Python.

a = 1
do
  local a
  do a = 2 end
  do print(a) end
  print(a)
end
print(a)

Note: I would prefer nothing by default (i.e. make declaration of globals explicit via a language keyword, not declaring is an error) instead of the current situation (doing this with tricks like strict.lua). However that would make it harder to use Lua as a configuration language and things like that.

@craigbarnes
Copy link

Point well made. Explicit declaration makes much better sense than declaring exceptions to implicit rules (as in Python's nonlocal).

@catwell
Copy link
Author

catwell commented Apr 24, 2013

Oh, so Python 3 has a way to do this! When I use Python it is still 2.7, so I hadn't noticed it. I still prefer Lua's way though, but this is nice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment