Update
Code has been shortened and the bug mentioned by Flacko in this post has been fixed.
The purpose of this script is to make using cs2d's timers easier.
Can pass any number of arguments
Automatically frees itself when no longer needed
Call anonymous functions
All timers are given a unique identifier
I realized how terrible the timer function is when I was trying to delay a function call
1
2
3
4
5
2
3
4
5
addhook("drop", "drop") function drop(id, iid, type, ain, a) 	-- Won't work. CS2D will override it 	setammo(iid, ain, 0) end
I can't use CS2D's timer function because it only allows one parameter to be passed. I'd need a table to keep track of everything and then I'd need to free it... what a hassle.
With the timer function provided by this script all I need to do is
1
2
3
2
3
function drop(id, iid, type, ain, a) 	timer(1, 1, setammo, iid, ain, 0) end
That will call the setammo function one time after one millisecond and then free the timer for me!
And the timer function is compatible with any scripts that expect the original function
1
timer(1, "print", "hello", 3) -- uses cs2d's timer, as expected
Usage
The function is declared as
1
function timer(ms, count, tickfunc, ...)
count - How many times the timer will run before being freed
tickfunc - The function to call
Any other parameters given will be passed to `tickfunc` when it is called.
The function will return a unique identifier for the timer so that it can later be freed if necessary. This also means you can free timers that use the same function and parameter.
If you use CS2D's timer function
1
2
3
4
2
3
4
timer(1000, "msg", "hey", 0) timer(1000, "msg", "hey", 0) -- this will free BOTH timers. you can't free only one freetimer("msg", "hey")
Using this scripts timer function
1
2
3
4
2
3
4
id = timer(1000, 0, msg, "hey") id2 = timer(1000, 0, msg, "hey") freetimer(id) freetimer(id2)
If you need to keep track of variables between function calls then pass a table to it
1
timer(1000, 3, function (args) print(args.x); args.x = args.x + 1 end, {x = 1})
The only time you need to manually free a timer is when it runs indefinitely / forever or you need to end it prematurely.
1
2
3
4
5
2
3
4
5
-- 0 means run forever mytimer = timer(1000, 0, msg, "hello, world") -- somewhere else in the script freetimer(mytimer)
Copyright
You can freely use this script for any purpose.
edited 4×, last 07.10.17 11:55:20 pm
Approved by Yates
Download
777 b, 453 Downloads