trace-globals.lua 728 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. -- trace assigments to global variables
  2. do
  3. -- a tostring that quotes strings. note the use of the original tostring.
  4. local _tostring=tostring
  5. local tostring=function(a)
  6. if type(a)=="string" then
  7. return string.format("%q",a)
  8. else
  9. return _tostring(a)
  10. end
  11. end
  12. local log=function (name,old,new)
  13. local t=debug.getinfo(3,"Sl")
  14. local line=t.currentline
  15. io.write(t.short_src)
  16. if line>=0 then io.write(":",line) end
  17. io.write(": ",name," is now ",tostring(new)," (was ",tostring(old),")","\n")
  18. end
  19. local g={}
  20. local set=function (t,name,value)
  21. log(name,g[name],value)
  22. g[name]=value
  23. end
  24. setmetatable(getfenv(),{__index=g,__newindex=set})
  25. end
  26. -- an example
  27. a=1
  28. b=2
  29. a=10
  30. b=20
  31. b=nil
  32. b=200
  33. print(a,b,c)