Log In  
0

i have to count frames a lot because i'm using them to base the timing for the rhythm game and the clock. rather than having some global variable i increment every update (which would then require some kind of modulo operation to check, say, if we are on an even numbered frame) i decided to use the closure technique to make a counter that resets after a certain number of frames.

function frame_looper(frames)
 local f = 0
 return function()
         f += 1
         if (f>frames) f=1
         return f
        end
end

here i have a function FRAME_LOOPER that takes a number of frames. it creates a local variable f and then returns an anonymous function that when called returns that local variable f. we can now make a variable that uses a frame_looper as a counter.

beat_counter = frame_looper(10)

now in my _update function i can just call beat_counter() and i'll get back a number from 1-10 depending on how many times the function has been called. rather than having to declare some random variable and set and increment it every update, that local variable f that was enclosed in the anonymous function gets generated every update.

i'm still new to all of this, but i was able to use the technique for two other parts of my code that also work on a counter like this.

function drum_beater(accents)
 local i,s = 0,0
 return function ()
    i += 1
    if (i > #accents) i=1

    if accents[i] then
      s=0
    else s=1 end   
    sfx(s)
 end
end

accent1 = {true,false,false,false}
drum = drum_beater(accent1)

--[[ moonbeat:
used in _draw to flicker the
moon sprite]]--
function moonbeat(b)
 local moon = {x=80,y=40,
               r=8,col=10}
 return function()
         if b == beat_frame then
          moon.r = 10
         end
         return circfill(
           moon.x,moon.y,
           moon.r,moon.col)
        end            
end

moon = moonbeat(0)

i can now just call drum() and moon() during _update and get the behavior i want, based on the beat counter for the moon, and using the closure to loop over a table on the drum beat.

functional closure howto
P#31789 2016-10-26 00:22


:: More
X
About | Contact | Updates | Terms of Use
Follow Lexaloffle:        
Generated 2018-01-20 11:15 | 0.214s | 1572k | Q:9