[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: In praise of globals
- From: Dirk Laurie <dirk.laurie@...>
- Date: Mon, 15 Apr 2013 08:38:40 +0200
2013/4/15 Brian Kelley <brian.kelley@gmail.com>:
> I look forward to a future Lua that abandons globals completely in favor
> of manifest upvalues!
That remark comes from another thread, and it's maybe not fair to pick
on it, but it is an extreme example of something that has been bothering
me for a long time.
It's getting to be politically correct in the Lua community
to regard globals as bad.
The attitude (the term 'prejudice' almost sneaked out, but I bit it back)
is illustrated most clearly by the pejorative term "polluting the global
namespace".
You can tell the programs written by the supporters of this ideology.
They start out something like this:
local pairs, ipairs, print, tostring, getmetatable, setmetatable
= pairs, ipairs, print, tostring, getmetatable, setmetatable
There are also plenty of forward declarations of local functions.
Now, I don't want to knock this style of programming altogether. I've used
it myself. But to preach that is the One Correct Way is going too far.
If one is using Lua via the interactive interpreter (which I do a lot)
it is intensely annoying to cut-and-paste code written this way. Those
locals last only for the chunk in which they are defined, and the
interactive interpreter bites off the smallest chunks possible. I keep
forgetting to make extra `do`..`end` blocks all the time.
In Lua, it's a mistake, a Pythonic mistake, to think of local variables
as the usual thing. Local variables are special. You must declare them
explicitly. Their names don't survive compilation. You can have at
most 200 of them in one scope. They should be used with care, and only
for the purpose they were designed for, which is to be short-lived.
Globals, on the other hand, don't have to be declared, have long-lived
names, and you can have as many as you like.
You look at a `luac` listing of your compiled bytecode, the names are
there for all to see. They are just keys in a table.
Compare the following two programming assignments:
1. Write a function 'showglobal(str)' that prints out the value of the
global variable whose name is the given parameter.
2. Write a function 'showlocal(str)' that prints out the value of the
local variable whose name is the given parameter.
I've made myself two laws of for naming functions.
1. Don't make it local if you plan exporting it, but define it inside
its table to begin with.
2. Make it global if it is used so often that it almost feels
as if it is part of the language.
Look, if you are a global-hater, by all means don't use them. Assign
those from Lua's standard library that you can't do without to local
variables if you must. But don't insist that other people must do so too.