lua-users home
lua-l archive

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


On Fri, Aug 7, 2009 at 7:59 AM, steve donovan wrote:
> We all know that global variables can be a pain [1] and should be
> avoided.

True.  Without the methods in [1], I think programming in Lua is error prone.

> It would be possible (using a suitable proxy table) to enforce dynamic
> type checking on field assignments, but of course this would incur a
> run-time cost.

There's also ways to do such things statically.  My concept of how
this might work is given in luanalyze [2]:

-- examples/ex1.lua
do
  --! typeimport('luaanalyze.library.standard')
  --! typematch('idx$', 'luaanalyze.type.number')
  --! checkglobals()
  --! checktypes()

  for my_idx=1,10 do
    local s = string
    local f = s.format
    --print(f(my_idx)) -- fails: got number expected string

    --print(myy_idx) -- fails: undefined global
  end
end

print(myy_idx) -- no error


The special "--!" comments are Lua statements to be executed by the
type checker within the context of the current lexical scope.
typeimport('luaanalyze.library.standard') loads predefined types for
the standard library (e.g. string).  typematch associates types to
variables whose name matches some pattern (thereby supporting
Hungarian like conventions).  checkglobals() check the AST to ensure
no unbound globals are used.  checktypes() evaluates the AST in a
special manner, propagating types, doing basically a very rudimentary
form of dataflow analysis that is extensible with metamethods.  The
dataflow analysis could be much improved by someone with more
experience in this area and willingness to devote the time.

A real example of its use is in the source code of lua2c [3], where,
for example, it checks that invalid fields aren't accessed from AST
node objects.

[1] http://lua-users.org/wiki/DetectingUndefinedVariables
[2] http://lua-users.org/wiki/LuaFish (bottom of page)
[3] http://github.com/davidm/lua2c/blob/6c1da4eb84cc52cccb57805b90e6e6f74a5ef199/lib/lua2c/ast2cast.lua