Does lua have an “event handler” build in or does it have a lib available to do that?
So that, an example, when “a = 100” an event happens.
Something else rather than using:
while true do
if a == 100 then
[...]
break;
end
end
Or simply adding a sleep to it. The “while true do” is just an example but its a terrible one.
Lua operates in a single-thread, so any checking must be explicitly performed by your code.
The act of performing code immediately upon a variable changing is known as “watching”.
If you are programming in an environment where a set of code is run every frame (such as a game), you can check manually.
For example:
Upon the next frame, the callback code (the print) will be executed.
The disadvantage of this approach is that the callback code is not printed immediately after
WatchedVariables.ais set to-7, that is: the output will be:To prevent this potentially undesired behaviour, a setter function can be used, for example:
The output of this code shows that the callback runs immediately:
To make this more comfortable, Lua provides metatables that make such behaviour transparent to the programmer.
Example:
The output of this code will be the same as the previous example:
Here’s an implementation for your example case:
Why are the variables
__privatesand__private_callbackprefixed with two underscores? It is convention to prefix private members that should not be accessed in typical programming situations with two underscores. If you familiar with object-oriented methodology and it’s implementation in languages such as Java and C++, you will understand how it is similar to theprivateandprotectedkeywords.If you are familiar with the C# language, you may see how the
set_a/get_aand metatable implementations are similar to accessors (set/get).