Jump to content

DoEvery() helper function


Rick
 Share

Recommended Posts

I was looking for a way to avoid having to make time variables manually and a more inline way when I wanted to do something on an interval. I came up with the function below. The idea is that it's something that's in an Update function so it's called every frame (normally what you would do anyway if you were tracking it manually).

 

First it's usage:

 

-- this will play an attack animation every 2 seconds. the false variable tells if it should call the function you are passing in right away the first time or wait until the interval is up for the first time only. after that it'll do it at the interval

 

DoEvery(2000, false, function()
  self.animMgr:SetAnimationSequence("Attack"..tostring(1 + task.actor.attackmode), 0.05, 300, 1, self, self.EndAttack)
end)

 

This should be slap in ready. Just copy it to your project and use away.

 

function DoEvery(interval, doRightAway, method)
  local info = debug.getinfo(method, "S")
  local id = info.linedefined..string.gsub(string.gsub(info.source, "/", "_"), ":", "")

  -- if this is the first time every calling this then create the global class that will hold all instances of  these
  if DoEveryInstances == nil then
     DoEveryInstances = {}
  end

  -- if this is the first time trying to do this specific function then create it's entry
  if DoEveryInstances[id] == nil then
     DoEveryInstances[id] = {}
     if doRightAway == true then
        DoEveryInstances[id].lastUpdateTime = interval * -1
     else
        DoEveryInstances[id].lastUpdateTime = Time:GetCurrent()
     end
  end

  -- handle the do every function for a specific instance
  if Time:GetCurrent() >= DoEveryInstances[id].lastUpdateTime + interval then
     DoEveryInstances[id].lastUpdateTime = Time:GetCurrent()
     method()
  end
end

  • Upvote 2
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...