[SNIPPET] Client Timers

Started by ysc3839, Apr 29, 2016, 03:11 PM

Previous topic - Next topic

ysc3839

Thanks SLC(http://forum.vc-mp.org/?topic=1487.0) and stormeus(CTimer.cpp and CTimer.h in 0.4 Squirrel). :)
Timer <- {
Timers = {}

function Create(environment, listener, interval, repeat, ...)
{
// Prepare the arguments pack
vargv.insert(0, environment);

// Store timer information into a table
local TimerInfo = {
Environment = environment,
Listener = listener,
Interval = interval,
Repeat = repeat,
Args = vargv,
LastCall = Script.GetTicks(),
CallCount = 0
};

local hash = split(TimerInfo.tostring(), ":")[1].slice(3, -1).tointeger(16);

// Store the timer information
Timers.rawset(hash, TimerInfo);

// Return the hash that identifies this timer
return hash;
}

function Destroy(hash)
{
// See if the specified timer exists
if (Timers.rawin(hash))
{
// Remove the timer information
Timers.rawdelete(hash);
}
}

function Exists(hash)
{
// See if the specified timer exists
return Timers.rawin(hash);
}

function Fetch(hash)
{
// Return the timer information
return Timers.rawget(hash);
}

function Clear()
{
// Clear existing timers
Timers.clear();
}

function Process()
{
local CurrTime = Script.GetTicks();
foreach (hash, tm in Timers)
{
if (tm != null)
{
if (CurrTime - tm.LastCall >= tm.Interval)
{
tm.CallCount++;
tm.LastCall = CurrTime;

tm.Listener.pacall(tm.Args);

if (tm.Repeat != 0 && tm.CallCount >= tm.Repeat)
Timers.rawdelete(hash);
}
}
}
}
};
Code also can be found here: https://bitbucket.org/snippets/ysc3839/My5kR

Add Timer.Process(); in Script::ScriptProcess.

Example:
function Script::ScriptLoad()
{
local hash = Timer.Create(this, function(text, int) {
Console.Print(text + int);
}, 1000, 0, "Timer Text ", 12345);
Console.Print(hash);
}