I'm trying to optimise my LuaJIT code, and I'm wondering, if there is a debug tool, or if I can write one, to check how many times my script accessed global variables/tables/functions?
You can use a proxy table to store globals and divert any access to the global table to this proxy, embellished with tracing functionality.
local globals = {}
setmetatable(_G, {
__newindex = function (_, k, v)
print(debug.traceback("Setting global variable " .. k, 2))
rawset(globals, k, v)
end,
__index = function (_, k)
print(debug.traceback("Getting global variable " .. k, 2))
return rawget(globals, k)
end,
})
a = 1
a = 2
print(a)
Sample output:
Setting global variable a
stack traceback:
prog.lua:15: in main chunk
[C]: at 0x00404960
Setting global variable a
stack traceback:
prog.lua:16: in main chunk
[C]: at 0x00404960
Getting global variable a
stack traceback:
prog.lua:18: in main chunk
[C]: at 0x00404960
2