You can do this a few ways.
A local variable would work, strangely enough. What happens there is that the event function becomes a closure over the local debounce. It refers to the debounce in that scope (which is unique for each iteration of the loop).
Here's a simple example that we can check this out with:
funs = {}
for i = 1, 3 do
local count = 0
funs[i] = function()
count = count + 1
print("This is the ", count, "th time you called function", i)
end
end
funs[1]()
funs[2]()
funs[1]()
funs[2]()
funs[1]()
funs[3]()
funs[1]()
This behavior sort of makes sense. You have access to, for example, v inside of the function to determine which one it is, and it doesn't get affected by the fact that there are more v inside of the loop.
An irrelevant aside: JavaScript, a language similar to Lua, does not quite have this behavior -- it will reuse the scope between iterations of the loop and end up sharing a single variable in all of the functions you make
So, you could just make a local debounce within the loop and you'll be set. (Note that it needs to be local, not specifying local will make it global and be shared. And specifying it local inside the function will cause it to ignore the value it's closed over!)
Another option is to use a table. For this particular case, the other option probably makes more sense, but maybe this is more intuitive. We just store a different debounce value for each v:
local debounces = {}
for i,v in .... do
debounces[v] = false
.... = function()
if not debounces[v] then
debounces[v] = true
....
debounces[v] = false
end
end
end
Though, this is clearly exploiting the fact that the function is closed over v. The case where that would not happen is if the object you had the debounce over was passed as a parameter. Sadly, no ROBLOX events do this (which is why, for example, the Chatted event is almost always connected to an anonymous function)
2 comments
Someone answer this, I want to know.
I posted this on ROBLOX forums, not many people know how to do this... So I guess we have to wait.