How can I detect when the Lua scripts access a global variable? -



How can I detect when the Lua scripts access a global variable? -

i started work c++/lua codebase mess, , when dump contents of _g in middle of application execution, there hundreds of variables sure initialized somewhere, not used anywhere else in code anymore. clean up, setup mechanism log whenever lua accesses global variable.

this thought of how accomplish – wanted setup proxy _g pass read , write accesses via __index , __newindex along own re-create of original _g. simple script doesn't work , outputs:

c:\programs\lua-5.1.5_win32_bin\lua5.1: error in error handling

gprox = { vars = _g } setmetatable(gprox, { __index = function (t, name) print("read> " .. name) homecoming t.vars[name] end, __newindex = function (t, name, val) print("write> " .. name .. ' = ' .. val) t.vars[name] = val end }) setfenv(0, gprox) = 1 --> expected print 'write> a' print(a) --> expected print 'read> print', 'read> a', , '1'

is approach or there improve way this? if valid line of thought, problem snippet?

try snippet instead, work reads , writes:

do -- utilize local variables local old_g, new_g = _g, {} -- re-create values if want quiet logging -- set fields (eg. predeclared globals). -- k, v in pairs(old_g) new_g[k] = v end setmetatable(new_g, { __index = function (t, key) print("read> " .. tostring(key)) homecoming old_g[key] end, __newindex = function (t, key, val) print("write> " .. tostring(key) .. ' = ' .. tostring(val)) old_g[key] = val end, }) -- set @ level 1 (top-level function) setfenv(1, new_g) end

here's rundown of changes:

a block used have local reference old _g. in proposed implementation, if global variable named vars set, override gprox.vars , break proxy. key , val should go through tostring before printing, since values (ie. tables) aren't implicitly converted strings. setting environment @ level 1 plenty , not mess lua's internal workings.

lua

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -