SetTimer: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
No edit summary
mNo edit summary
(42 intermediate revisions by 22 users not shown)
Line 1: Line 1:
Temporary Timer Explanation
__NOTOC__
{{Server client function}}
This function allows you to trigger a function after a number of milliseconds have elapsed. You can call one of your own functions or a built-in function. For example, you could set a timer to spawn a player after a number of seconds have elapsed.


[17:33] <Ransom> yes.. explain how ur damn settimers can work
Once a timer has finished repeating, it no longer exists.
[17:33] <Talidan> ransom wants to destroy a vehicle after a certain time of inactivity
 
[17:33] <ChrML_Laptop> setTimer ( "function", time in ms, arg1, arg2, argn... )
The minimum accepted interval is 50ms.
[17:34] <ChrML_Laptop> first argument is the name of the function to run in the given number of milliseconds
 
[17:34] <slush> heh
{{New feature/item|3.0157|1.5.6|16715|The minimum accepted interval is 0ms now.}}
[17:34] <Ransom> okay.. so it makes a function or it can be used as... a command
 
[17:34] <slush> i wonder how it would be to play gta with my xbox 360 control
'''Note: The speed at which a client side timer runs can be completely unreliable if a client is maliciously modifying their operating system speed, timers could run much faster or slower.'''
[17:34] <slush> since it does work with windows and all
 
[17:34] <Talidan> it doesnt make any functions
Multi Theft Auto guarantees that the timer will be triggered after ''at least'' the interval you specify. The resolution of the timer is tied to the frame rate (server side and client-side). All the overdue timers are triggered at a single point each frame. This means that if, for example, the player is running at 30 frames per second, then two timers specified to occur after 100ms and 110ms would more than likely occur during the same frame, as the difference in time between the two timers (10ms) is less than half the length of the frame (33ms). As with most timers provided by other languages, you shouldn't rely on the timer triggering at an exact point in the future.
[17:35] <Talidan> it launches a function
 
[17:35] <ChrML_Laptop> what's in the quote is simply the name of the function
==Syntax==
[17:35] <ChrML_Laptop> then there's a time argument
<syntaxhighlight lang="lua">
[17:35] <ChrML_Laptop> then there are N arguments that you'd normally put in the ()
timer setTimer ( function theFunction, int timeInterval, int timesToExecute, [ var arguments... ] )
[17:35] <ChrML_Laptop> setTimer ( "serverChat", 5000, "hi girls" )
</syntaxhighlight>
[17:35] <Talidan> chrml he understands that, its something else he isnt getting and i dont get what he means
{{OOP||[[Timer]]}}
[17:36] <Ransom>  onExitVehicle ( player, vehicle, int seat, jackingplayer )
===Required Arguments===
[17:36] <Ransom>       destroyvehicle = 1
*'''theFunction:''' The function you wish the timer to call.
[17:36] <Ransom>      SetTimer ( check, 10000 )
{{Note|The hidden global variable '''sourceTimer''' contains the currently executing timer userdata}}
[17:36] <Ransom>  end
*'''timeInterval:''' The number of milliseconds that should elapse before the function is called. (the minimum is 50 (0 on 1.5.6 r16715); 1000 milliseconds = 1 second)
[17:36] <Ransom> then
*'''timesToExecute:''' The number of times you want the timer to execute, or 0 for infinite repetitions.
[17:36] <Ransom>  function check ()
 
[17:36] <Ransom>      if destroyvehicle = 1
===Optional Arguments===
[17:36] <Ransom>          SetTimer ( setVehicleHealth, 10000, vehicle, 0 )
{{OptionalArg}}
[17:36] <Ransom> end
*'''arguments:''' Any arguments you wish to pass to the function can be listed after the ''timesToExecute'' argument. Note that any tables you want to pass will get cloned, whereas metatables and functions/function references in that passed table will get lost. Also changes you make in the original table before the function gets called won't get transferred.
[17:36] <Talidan> 'then' isnt part of the code
 
[17:36] <Ransom> he just created a function through a timer... then said onthatfunction, then  used another timer inside it as a countdown
===Returns===
[17:36] <Talidan> and its all ==
Returns a [[timer]] pointer if the timer was set successfully, ''false'' if the arguments are invalid or the timer could not be set.
[17:36] <ChrML_Laptop> that code looks syntax error
 
[17:36] <ChrML_Laptop> function onExitVehicle ( blablabl )
==Examples==
[17:37] <Talidan> i c/p chrml
This example will output some text after a small delay.
[17:37] <Talidan> trying to work out the logic though chrml
 
[17:37] <ChrML_Laptop> always == for comparison
<syntaxhighlight lang="lua">
[17:37] <Talidan> how would you destroy a vehicle after inactivity
-- define function to be called
[17:37] <ChrML_Laptop> if ( test = 5 ) then
function delayedChat ( text )
[17:37] <Ransom> so you can set timers to check made up function names right...
outputChatBox ( "Delayed text: " .. text )
[17:37] <ChrML_Laptop> will assign 5 to test, then check if it's >0
end
[17:37] <Ransom> thats what you are saying
 
[17:37] <ChrML_Laptop> atleast it will in C+
-- set a timer so the function is called after 1 second
[17:37] <ChrML_Laptop> ++
setTimer ( delayedChat, 1000, 1, "Hello, World!" )
[17:37] <Talidan> yeah ransom
</syntaxhighlight>
[17:37] <Talidan> functions you make up dont go in ""
 
[17:37] <Talidan> functions that are on the wiki do go in ""
1 second after the line above has been executed, the text ''Delayed text: Hello, World!'' will be displayed in the chat box.
[17:37] <Ransom> okay but yet they can also be used to perform functions at given countdowns
 
[17:37] <Ransom> ?
This example will nest a whole function within a timer. This is nice for things like setting variables without having to call a function outside of your code block.
[17:37] <Talidan> wait no
 
[17:37] <Talidan> iim wrong
<syntaxhighlight lang="lua">
[17:38] <Talidan> they all go in ""
function mainFunction()
[17:38] <ChrML_Laptop> yes
        outputChatBox ("Instant text!")
[17:38] <Ransom> and all those arg1, arg2 just depend on if you put a bigass function in there with lots arguments?
setTimer ( function()
[17:38] <Talidan> yeah
outputChatBox ( "5 second delay text!" )
[17:38] <Talidan> well ask chrml to write up the code anyway ransom
end, 5000, 1 )
[17:38] <Talidan> he'd have better logic
end
[17:39] <Ransom> well ill just paste this in the wiki for temporary reference :P
 
mainFunction() --call function
</syntaxhighlight>
 
This example outputs some random text to the chat every 300000 milliseconds (5 minutes).
<syntaxhighlight lang="lua">
setTimer(function()
    outputChatBox("Text " .. math.random(1,4))
end, 300000, 0)
</syntaxhighlight>
 
 
<section name="Yet another example" class="server" show="false">
This example should send a global message about the death of a player on a random time. I used [https://wiki.multitheftauto.com/wiki/Math.round math.round] in this example to give a nicer output.
<syntaxhighlight lang="lua">
function math.round(number, decimals, method) -- math.round, useful function taken from the wiki: https://wiki.multitheftauto.com/wiki/Math.round
    decimals = decimals or 0
    local factor = 10 ^ decimals
    if (method == "ceil" or method == "floor") then return math[method](number * factor) / factor
    else return tonumber(("%."..decimals.."f"):format(number)) end
end
 
function onWasted()
local delay = math.random(500, 5000) -- 0.5s to 5s of delay
setTimer(function(thePlayer) -- Starts the Timer
local whoDied = "Someone" -- In case the name can't be read, Someone will appear
if isElement(thePlayer) then -- This checks if thePlayer's element still exists (which means thePlayer hasnt disconnected yet)
whoDied = getPlayerName(thePlayer) -- Changes Someone to thePlayer's name
end
outputChatBox(whoDied.." #FFFFFFhas #FF0000died #FFFFFF"..math.round(delay/1000, 1).." seconds ago.", root, 255, 175, 0, true) -- This will output to everyone on the server that thePlayer (or Someone) died X seconds ago.
end
delay, 1, source) -- The source at the end is an argument for the function we made before, you can't use the source directly because it won't be readed
end
addEventHandler("onPlayerWasted", root, onWasted) -- Executed every time someone dies
</syntaxhighlight>
</section>
 
==See Also==
{{Utility functions}}

Revision as of 16:02, 2 May 2019

This function allows you to trigger a function after a number of milliseconds have elapsed. You can call one of your own functions or a built-in function. For example, you could set a timer to spawn a player after a number of seconds have elapsed.

Once a timer has finished repeating, it no longer exists.

The minimum accepted interval is 50ms.

The minimum accepted interval is 0ms now.

Note: The speed at which a client side timer runs can be completely unreliable if a client is maliciously modifying their operating system speed, timers could run much faster or slower.

Multi Theft Auto guarantees that the timer will be triggered after at least the interval you specify. The resolution of the timer is tied to the frame rate (server side and client-side). All the overdue timers are triggered at a single point each frame. This means that if, for example, the player is running at 30 frames per second, then two timers specified to occur after 100ms and 110ms would more than likely occur during the same frame, as the difference in time between the two timers (10ms) is less than half the length of the frame (33ms). As with most timers provided by other languages, you shouldn't rely on the timer triggering at an exact point in the future.

Syntax

timer setTimer ( function theFunction, int timeInterval, int timesToExecute, [ var arguments... ] )

OOP Syntax Help! I don't understand this!

Method: Timer(...)


Required Arguments

  • theFunction: The function you wish the timer to call.
[[{{{image}}}|link=|]] Note: The hidden global variable sourceTimer contains the currently executing timer userdata
  • timeInterval: The number of milliseconds that should elapse before the function is called. (the minimum is 50 (0 on 1.5.6 r16715); 1000 milliseconds = 1 second)
  • timesToExecute: The number of times you want the timer to execute, or 0 for infinite repetitions.

Optional Arguments

NOTE: When using optional arguments, you might need to supply all arguments before the one you wish to use. For more information on optional arguments, see optional arguments.

  • arguments: Any arguments you wish to pass to the function can be listed after the timesToExecute argument. Note that any tables you want to pass will get cloned, whereas metatables and functions/function references in that passed table will get lost. Also changes you make in the original table before the function gets called won't get transferred.

Returns

Returns a timer pointer if the timer was set successfully, false if the arguments are invalid or the timer could not be set.

Examples

This example will output some text after a small delay.

-- define function to be called
function delayedChat ( text )
	outputChatBox ( "Delayed text: " .. text )
end

-- set a timer so the function is called after 1 second
setTimer ( delayedChat, 1000, 1, "Hello, World!" )

1 second after the line above has been executed, the text Delayed text: Hello, World! will be displayed in the chat box.

This example will nest a whole function within a timer. This is nice for things like setting variables without having to call a function outside of your code block.

function mainFunction()
        outputChatBox ("Instant text!")
	setTimer ( function()
		outputChatBox ( "5 second delay text!" )
	end, 5000, 1 )
end

mainFunction() --call function

This example outputs some random text to the chat every 300000 milliseconds (5 minutes).

setTimer(function()
    outputChatBox("Text " .. math.random(1,4))
end, 300000, 0)


Click to expand [+]
Yet another example

See Also