CallServerFunction: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
(new useful function: CallServerFunction)
 
m (removed category since it's now included in the template)
Line 60: Line 60:


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

Revision as of 13:30, 14 May 2009


This function allows you to call any serverside function from the client's side. Of course only those which are available serverside. 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 serverside to avoid data being lost. If you don't need this feature just delete it.

Syntax

nil CallServerFunction( string funcname, [ var argument1, ... ] )

Required Arguments

  • funcname: The name of the function that should be called serverside. May also be a function in a table, 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 [-]
Clientside Script
local _root = getRootElement()
function CallServerFunction(funcname, ...)
    if (arg[1]) then
        for key, value in pairs(arg) do
            if (type(value) == "number") then arg[key] = tostring(value) end
        end
    end
    triggerServerEvent("OnClientCallsServerFunction", _root, funcname, unpack(arg))
end
Click to collapse [-]
Serverside Script
local _root = getRootElement()
function CallServerFunction(funcname, ...)
    if (arg[1]) then
        for key, value in pairs(arg) do arg[key] = tonumber(value) or value end
    end
    loadstring("return "..funcname)()(unpack(arg))
end
addEvent("OnClientCallsServerFunction", true)
addEventHandler("OnClientCallsServerFunction", _root, CallServerFunction)

Example

Click to collapse [-]
Client

This example removes the player from his team.

-- get the local player element
local _local = getLocalPlayer()
-- define the leaveTeam command handler function
function CmdLeaveTeam()
    -- set the player's team to nil
    CallServerFunction("setPlayerTeam", _local)
end
-- add the command handler
addCommandHandler("leaveTeam", CmdLeaveTeam, false)

Author: NeonBlack