on.varChange

From Inspired-Lua Wiki
Revision as of 12:19, 29 January 2012 by Adriweb (talk | contribs)
Jump to navigation Jump to search

This event gets fired when a monitored variable gets changed.
It has an argument it creates by itself (like 'gc' with on.paint), which is varlist, being a list of variable names whose values were changed.
This handler must return a value to indicate if it accepts the new value(s) or vetoes the change.

Syntax

on.varChange(varlist)

Return values

Valid return values are:

  • 0 Success. The script application accepts the change.
  • -1 Veto range. The new value is unsatisfactory because it is outside the acceptable range, i.e. too low or too high.
  • -2 Veto type. The new value is unsatisfactory because its type cannot be used by the script application.
  • -3 Veto existence. Another application deleted the variable and this application

Example

This example is about Highscore Saving.
More details here : http://www.inspired-lua.org/2011/08/save-a-high-score-without-cheating-possibility/

function on.create()
   if not var.recall("highscore") then
     highscore = 0
     var.store("highscore", highscore)
   end
   var.monitor("highscore")
 end

 function on.varChange(list)
   for k, v in pairs(list) do
     if k == "highscore" then
       if var.recall(k) ~= highscore then
         return 1 -- it is an external change, block modifications
       else
         return 0 -- it is an internal change, allow modifications
       end
     end
   end
   return 0 -- allow modifications of other monitored variables if any
 end