lua-users home
lua-l archive

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

2013/4/25 Steve Litt <>:
> On Wed, 24 Apr 2013 23:18:19 +0200
> Dirk Laurie <> wrote:
>> > Because Lua supports proper lexical scoping and nested closures so
>> > thoroughly (as opposed to, e.g., Python), default local would be
>> > untenable. The most sensible and simplest rule is what Lua uses,
>> > IMO.
>> I use a simple metatable modification to catch assignments to global
>> variables whose names match a certain pattern, currently "^%a%d?$".
>> I.e. names like `i` or `a1` will trigger a warning. Not foolproof of
>> course, but I try to follow the rule that anything I genuinely want
>> in `global` must have a nume that does not math that format.
> Dirk, this is outstanding news. I'd like my interpreter to croak on any
> global that doesn't begin with "glv". Given that I almost never
> use any globals on purpose (except for procedures), your mod will catch
> all my omissions of the word "local". Having to mark all my functions
> local would be a small price to pay for *knowing* I haven't
> accidentally used globals.
> Could you please post a link to your modification so I can use it?

It's runtime, not compile time, which I'm told is not good enough if you are
in the habit of loading dubious third-party modules dynamically. But this
is what I do: up at the top of the program, I have:

local _ENVmeta=getmetatable(_ENV)
setmetatable(_ENV,{__newindex = function (ENV,name,value)
   local w=where(2)
   if name:match"^%a%d?$" then
      print(w.."A global name like '""' is asking for trouble.")

'where` returns a string like "mymodule.lua:174:". I've implemented
it with some other stuff in a C module:

/* where() */
static int lua_where (lua_State *L) {
  return 1;