问题
Is it possible to detect when the value of a variable has changed using the lua debug library. Something like A callback function which would give details like the function in which the value was changed, previous value, etc. Is such a thing possible?
I read about hooks, but I'm not sure hooks can be set to variables.
回答1:
If you don't mind using a debugger, then some debuggers allow you to set Watch expressions, which will be triggered when the condition in the expression is true. I'll show how this can be done in MobDebug (it is using lua debug library, but there is no direct way to detect a variable change as far as I know).
Let say we have a script start.lua
like the one below and want to detect where foo
gets value 2:
print("Start")
local foo = 0
for i = 1, 3 do
local function bar()
print("In bar")
end
foo = i
print("Loop")
bar()
end
print("End")
- Download mobdebug.lua and make it available to your scripts (the simplest way is to put it into the folder with your scripts).
- Start the server using
lua -e "require('mobdebug').listen()"
command. - Start the client using
lua -e "require('mobdebug').loop()"
command. - You will see the prompt in the server window: '>'. Type
load start.lua
to load the script. - Type
step
and thenstep
again. You will see "Paused at file start.lua line 3". - Let's see what the value of
foo
is. Typeeval foo
and you should see 0. - Now we can set up our watch. Type
setw foo == 2
. You can specify any Lua expression after setw command; the execution of your script will be stopped when the condition is evaluated as true. - Continue execution of the script using "run" command.
- The watch now fires, which will show you the message like: "Paused at file start.lua line 8 (watch expression 1: [foo == 2])". This means that the previous expression changed the value of
foo
to 2 and the execution is stopped at line 8. You can then inspect your script and the current values (you can use "eval" and "exec" commands to run any Lua code to be evaluated in your script environment) to find what triggered the change.
The benefit of this approach is that you are not limited to monitoring table values and can specify any expression. The main disadvantage is that your script runs under a debugger and the expression is evaluated after each step, which may get really slow.
回答2:
You can do this to a certain extent in Lua by using metatables and keeping a "proxy" table, and using the __newindex function call to detect attempts to add a variable.
This is covered here in the Programming in Lua book under the section "Tracking Table Accesses":
http://www.lua.org/pil/13.4.4.html
See Also
http://www.gammon.com.au/forum/?id=10887
来源:https://stackoverflow.com/questions/11941938/lua-debugging-detect-when-the-value-of-a-variable-changes