lua-users home
lua-l archive

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


Motivated by a thread in the chat room (#lua) last week, I wrote a quick
hack for doing static analysis of Lua programs and flagging the use of
undefined globals. See the attached script, globals.lua. Since this
script performs static analysis based on the bytecode, it cannot find
all uses of undefined globals. For a tool that does that at run time,
see etc/strict.lua in the distribution. Enjoy.
--lhf
-- find undefined global vars
-- typical usage: luac -p -l *.lua | lua globals.lua

local S={}
local G={}
local F

while true do
 local s=io.read()
 if s==nil then break end
 local ok,_,f=string.find(s,"^[mf].-<(.-):%d+,%d+>")
 if ok then F=f end
 local ok,_,l,op,g=string.find(s,"%[%-?(%d*)%]%s*([GS])ETGLOBAL.-;%s+(.*)$")
 if ok then
  if op=="S" then S[g]=true else G[g]=F..":"..l end
 end
end

for k,v in next,G do
 if not S[k] and not _G[k] then
  io.write(k," may be undefined in ",v,"\n")
 end
end