Advertisement
C0BRA

Lua variable inspectation

Sep 21st, 2013
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.34 KB | None | 0 0
  1. #!/usr/bin/env lua
  2.  
  3. do
  4.     local outside = "abc"
  5.     function test()
  6.         local inside = "def"
  7.    
  8.         return tostring(outside .. inside)
  9.     end
  10. end
  11.  
  12. -- higher poll-every = less slowdown, but may miss changes, or the entire in scope var
  13. -- lower ppoll-every = more slowdown, but less likley to miss a variable change
  14. function inspect_inside(vars, poll_every, func, ...)
  15.     local variables = {}
  16.    
  17.     local hook = function()
  18.         local idx = 1
  19.         while true do
  20.             local ln, lv = debug.getlocal(2, idx)
  21.             if ln ~= nil then
  22.                 variables[ln] = lv
  23.             else
  24.                 break
  25.             end
  26.             idx = 1 + idx
  27.         end
  28.     end
  29.  
  30.     local oldhook = debug.gethook()
  31.     debug.sethook(hook, "", poll_every)
  32.         local func_rets = {func(...)}
  33.     debug.sethook(oldhook)
  34.    
  35.     local ret = {}
  36.     for k,v in ipairs(vars) do
  37.         ret[v] = variables[v]
  38.     end
  39.     return ret, unpack(func_rets)
  40. end
  41.  
  42. function inspect_outside(vars, func)
  43.     local upvals = {}
  44.  
  45.     local i = 1
  46.     while true do
  47.         local name, val = debug.getupvalue(func, i)
  48.         if not name then break end
  49.  
  50.         upvals[name] = val
  51.         i = i + 1
  52.     end
  53.  
  54.     local ret = {}
  55.     for k,v in ipairs(vars) do
  56.         ret[v] = upvals[v]
  57.     end
  58.     return ret
  59. end
  60.  
  61. -- WARNING, POLLEVERY = 1, SLOW AS HELL, INCREASE UNTIL IT'S STABLE!
  62. print(inspect_inside({"inside"}, 1, test).inside)
  63. -- try and cache the result from this
  64. print(inspect_outside({"outside"}, test).outside)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement