WoW:Using OnUpdate correctly: Difference between revisions

From AddOn Studio
Jump to navigation Jump to search
Line 25: Line 25:
   -- Functions Section
   -- Functions Section
   function MyAddon_OnUpdate(elapsed)
   function MyAddon_OnUpdate(elapsed)
     this.timeSinceLastUpdate = this.timeSinceLastUpdate + elapsed;
     this.TimeSinceLastUpdate = This.timeSinceLastUpdate + elapsed;
     if (this.timeSinceLastUpdate > MyAddon_updateInterval) then     
     if (this.TimeSinceLastUpdate > MyAddon_updateInterval) then     
       --
       --
       -- Insert your OnUpdate code here
       -- Insert your OnUpdate code here
       --
       --
       this.timeSinceLastUpdate = 0;
       this.TimeSinceLastUpdate = 0;
     end
     end
   end
   end

Revision as of 14:46, 14 January 2006

How often is it called

The game engine will call your OnUpdate function once each frame. This is (in most cases) extremely excessive.

When is it called

OnUpdate is not called on any hidden frames, only while they are shown on-screen. OnUpdate will also never be called on a virtual frame, but will be called on any frames that inherit from one.

Proper Use Example

your_xml_file.xml
 <Ui ...>
 <Frame name="MyAddon_MainFrame" parent="UIParent" hidden="false" toplevel="true">
   ...
   <Scripts>
     <OnUpdate> MyAddon_OnUpdate(arg1); </OnUpdate>      
   </Scripts>			
 </Frame>
 </Ui>

The important part for us is the "arg1" parameter that we're passing to our function. This is a variable that's being inherited from the WoW system telling us how long it's been since the last update call cycle.

your_lua_file.lua
 -- Globals Section
 MyAddon_updateInterval = 1; -- how often my OnUpdate code will run
 -- Functions Section
 function MyAddon_OnUpdate(elapsed)
   this.TimeSinceLastUpdate = This.timeSinceLastUpdate + elapsed; 	
   if (this.TimeSinceLastUpdate > MyAddon_updateInterval) then    
     --
     -- Insert your OnUpdate code here
     --
     this.TimeSinceLastUpdate = 0;
   end
 end

Insert your code at the '-- Insert your OnUpdate code here', and substitute the 'MyAddon_' with your addon's name. You might also want to tweak your 'MyAddon_updateInterval' global variable to reflect how often your addon needs the code run, the less the better. This solution also happens to be thread-safe, which is another issue when your code is being run every 0.1 seconds, finished or not.