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.
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.lualike the one below and want to detect wherefoogets value 2:lua -e "require('mobdebug').listen()"command.lua -e "require('mobdebug').loop()"command.load start.luato load the script.stepand thenstepagain. You will see “Paused at file start.lua line 3”.foois. Typeeval fooand you should see 0.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.footo 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.