-- timerEx by MikuAuahDark

-- Create table that store all of active timers
__timerArg={}
-- Create timerEx function
function timerEx(ms,func,count,...)
	-- Check 'count' variable is nil/false
	count=count or 1
	-- Check if it's 0
	if count==0 then count=-1 end
	-- Create variable that would used to create the timer
	local tmpfunc,id="",0
	-- Generate random string
	for i=1,8 do
		local rand=math.random(0,2)
		if rand==0 then
			tmpfunc=tmpfunc..string.char(math.random(65,90))
		elseif rand==1 then
			tmpfunc=tmpfunc..string.char(math.random(97,112))
		else
			tmpfunc=tmpfunc..math.random(0,9)
		end
	end
	-- Add data to table __timerArg
	table.insert(__timerArg,{type(func),tmpfunc,func,{...},count})
	-- Get timer ID
	for n,v in pairs(__timerArg) do
		if v[2]==tmpfunc then
			-- set 'id' variable to id of the timer
			id=n
			-- break, in order to prevent some lags
			break
		end
	end
	-- Create global function with name that generated with random string
	_G[tmpfunc]=function(id)
		-- Convert 'id' variable
		id=tonumber(id)
		-- Check if second parameter @ timerEx is a function address
		if __timerArg[id][1]=="function" then
			-- Call and return the value
			__timerArg[id].r=__timerArg[id][3](unpack(__timerArg[id][4]))
		-- Check if second parameter @ timerEx is a function name(string)
		elseif __timerArg[id][1]=="string" or __timerArg[id][1]=="number" then
			-- Call with loadstring and return the value
			__timerArg[id].r=loadstring("return "..__timerArg[id][3].."(unpack(__timerArg["..id.."][4]))")()
		end
		-- Decrease count
		__timerArg[id][5]=__timerArg[id][5]-1
		-- Check if count is zero
		if __timerArg[id][5]==0 then
			-- Delete timer data from __timerArg table
			_G[__timerArg[id][2]]=nil
			__timerArg[id]=nil
		end
	end
	-- Create the actual 'timer' that call the random function name
	timer(ms,tmpfunc,id,count)
	-- return timer id(if there is a error, it's 0)
	return id
end

-- Create freetimerEx function
function freetimerEx(id)
	-- Check if timer id is exist
	if __timerArg[id]~=nil then
		-- Free actual timer and delete timer data from table
		freetimer(__timerArg[id][2],id)
		_G[__timerArg[id][2]]=nil
		__timerArg[id]=nil
		-- Return true because it's success
		return true
	end
	-- Well, timer id is nil so return false because it's failture
	return false
end