I thought I’d have a go at moving more things out of the Lua start up and into dedicated files on Vera. One area I can’t seem to get working is having a luup.variable_watch calling a function within a file. Is it possible to do ?
Because the callbacks are based by name and not as a function reference, the function has to be global. Your module functions will not work directly. You have to do something more like this:
mymodule = require "mymodule"
myModuleWatchHandler = mymodule.watch_handler -- the name of your module function that is the callback
luup.variable_watch( 'myModuleWatchHandler', ... )
Your module functions are in module scope, not global scope, so you use a temporary variable in global scope and assign it to the function reference of the module function. You pass the name of the temporary variable to the Luup function.
If they had used function references, this would have been much easier, and you could use closures (like lambdas in Python or anonymous functions in many other languages). Alas, they did not, so you have to jump through luups hoops to make it work.
Does a similar logic apply if you are using a luup.call_delay within the same function within the same module/file ?
By that I mean, I have a function called ‘checkLastTrip’ stored within that same module/file - that is called within the above luup.variable_watch ‘ mymodule.turn_remote_light_on_with_motion’ function?
… and it does not seem to be being found/called?
01 10/05/20 20:55:37.100 LuaInterface::CallFunction_Timer-5 function checkLastTrip failed attempt to call a nil value <0x726a6520>
Yes. Primitive types are passed by value, so the function is receiving the value from the variable. If the variable is garbage collected later because it’s out of scope, that’s no matter to the call; the work has been done (timer set up).
If dev isn’t in scope when the call to variable_watch() is made, it will be nil and so will not work. There’s no magic in the parentheses that make it go on a hunt for a variable with that name anywhere in the code. Every variable reference has to refer to something that’s in scope, or it’s nil.
One thing that may help is installing Lua on some system you can just play with, where the limits of where it logs and how you access it are less stringent than Vera’s. You can write all kinds of little programs and just use print statements to see what’s happening (without resorting to a full blown IDE with a debugger), and things often become very clear quickly when you’re not fighting the rest of system just trying to see what’s happening.