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 then step
again. You will see "Paused at file start.lua line 3".
- Let's see what the value of
foo
is. Type eval 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.