Skip to content

Instantly share code, notes, and snippets.

@nicklozon
Created January 28, 2018 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicklozon/2b40e26709b9cd58087400108c415b00 to your computer and use it in GitHub Desktop.
Save nicklozon/2b40e26709b9cd58087400108c415b00 to your computer and use it in GitHub Desktop.
--[[
Each time sequencer is called it counts up from 1 to the upper bound, wrapping back to 1 upon reaching the maximum
--]]
function sequencer(maximum)
local i=0
return function() -- the function is returned and not executed here, so whatever operation that receives it will need to invoke it at some point for this code to execute
if i==maximum then
i=0
end
i=i+1
return i
end
-- overall, this design of returning an object or function from a function is called a "factory function"
-- the concept here is that the local variables and state are not exposed, thus the function or object that is exposed is the only thing that can be manipulated from an outside caller
-- in this specific example, you don't want anyone manipulating the i counter, it should only ever be modifiable by the invoking the anonymous function
-- this idea of hiding a variable is called "closure", also known as lexical scoping: https://www.lua.org/pil/6.1.html
-- I use this pattern repeatedly in my old WoW addon EPGP Waitlist with the exception that the lexical scope is greater than just the immediate function, it is the immediate function and everything above it. so in the following example, I use do/end blocks to create lexical scope to a group of functions and only expose the ones I want by returning an object: https://github.com/nicklozon/EPGPWaitlist/blob/master/Guildlist.lua#L62
end
--[[
This bad boy is just a test
--]]
z = sequencer(4) -- z variable contains the anonymous function returned from the sequencer function
for i=0,10 do
print (z()) -- z variable is a function and the parentheses can be interpreted as an "invocation" operator, so this says "execute z as a function", thus executing the code from the anonymous function returned from the sequence function
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment