[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: detecting undefined variables--a new mixed approach
- From: David Manura <dm.lua@...>
- Date: Mon, 24 Mar 2008 22:34:22 +0000 (UTC)
I haven't been entirely satisfied with the existing approaches to detecting
undefined variables, as typified by etc/strict.lua (run-time) and
test/globals.lua (static analysis). My preference is static analysis in
conjunction with heavy use of lexical variables ("avoiding globals like the
plague"). However, test/globals.lua requires an external invocation of luac for
each chunk and piping the results. I don't think an interpreted language like
Lua should expect such a compile-time step from beginners. I think linters
(like LuaFish) have much promise but can only go so far without static
information decoration (e.g. pragmas) and/or resorting to run-time information.
Plus, I'm looking for a simple solution.
So, this lead to the "checkglobals module+patch" described in full on the newly
updated wiki page ( http://lua-users.org/wiki/DetectingUndefinedVariables ).
You can read it yourself, but it's summarized in these paragraphs:
...detection of global variable accesses (at least direct ones
not through _G or getfenv()) is best determined at compile
time, while determination of whether those global variables are
defined may best be determined at run-time (or possibly,
sufficiently so, at "load time", about when loadfile is done)...
A mixed approach is taken by the "checkglobals" module+patch
(see below for details), which provides a checkglobals(f, env)
function (implemented entirely in Lua). In short, checkglobals
validates that the function f (which is by default taken to be
the calling function) uses only global variables defined in
the table env (which by default is taken to be the environment
of f). checkglobals requires a small patch to add an additional
'g' option to the debug library's debug.getinfo / lua_getinfo
function to list the global variable accesses lexically inside
the function f.
checkglobals() -- always raises due to x
if math.random() > 0.5 then -- not always executed
stdin:1: accessed undefined variable "x" at line 3
So, can anyone tell me why this not better than the other approaches? and why
should the 'g' option (that checkglobals depends on) not go into Lua 5.2? If
you like, I'd be interested if you see any design implications in the way
checkglobals does things; there's multiple ways to use it.
Given the frequency that this topic comes up, maybe this topic should be
re-considered for 5.2. As far as I've seen the above looks like a suitable
solution to a common need. It modifies Lua only with the addition of a new 'g'
option to debug.getinfo/lua_getinfo to list the global variables accessed
lexically inside a function (or chunk). This option may have other uses as well
since global variables could be considered part of a function's interface, and
knowing them is potentially important for reflection purposes (maybe even