CallClientFunction: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
(new useful function: CallClientFunction)
 
mNo edit summary
Line 59: Line 59:


Author: NeonBlack
Author: NeonBlack
[[Category:Useful Functions]]

Revision as of 13:03, 14 May 2009


This function allows you to call any clientside function from the server's side. Of course only those which are available clientside. It doesn't matter if it's a MTA function, a Lua standard function or a custom function.

Numbers are automatically converted to a string and vice versa clientside to avoid data being lost. If you don't need this feature just delete it.

Syntax

nil CallClientFunction( element client, string funcname, [ var argument1, ... ] )

Required Arguments

  • client: The element of the player who should be affected.
  • funcname: The name of the function that should be called clientside. May also be a function from an array, e.g. "math.round".

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.

  • argument1, ...: The arguments that should be passed to the function.

Code

Click to collapse [-]
Serverside Script
local _root = getRootElement()
function CallClientFunction(client, funcname, ...)
    if (arg[1]) then
        for key, value in pairs(arg) do
            if (type(value) == "number") then arg[key] = tostring(value) end
        end
    end
    triggerClientEvent(client, "OnServerCallsClientFunction", _root, funcname, unpack(arg or {}))
end
Click to collapse [-]
Clientside Script
local _root = getRootElement()
function CallClientFunction(funcname, ...)
    for key, value in pairs(arg) do arg[key] = tonumber(value) or value end
    loadstring("return "..funcname)()(unpack(arg))
end
addEvent("OnServerCallsClientFunction", true)
addEventHandler("OnServerCallsClientFunction", _root, CallClientFunction)

Example

Click to collapse [-]
Server

This example sets the player's minute duration.

-- get the root element
local _root = getRootElement()
-- define the onPlayerJoin handler function
function OnPlayerJoin()
    -- set the minute duration
    CallClientFunction(source, "setMinuteDuration", 10000)
end
-- add the event handler
addEventHandler("onPlayerJoin", _root, OnPlayerJoin)

Author: NeonBlack