SetElementData

From Multi Theft Auto: Wiki
Revision as of 09:51, 12 August 2007 by AlienX (talk | contribs)
Jump to navigation Jump to search

This function stores data attached to an element. This data can be any primitive LUA type or MTA element (but not a text item or display).

Element data is a useful way to store data attached to players.

Syntax

bool setElementData ( element theElement, string key, var value ) 

Required Arguments

  • theElement: The element you wish to attach the data to
  • key: The key you wish to store the data under
  • value: The value you wish to store

Returns

Returns true if the data was set succesfully, false otherwise.

Example

This example stores the date at which the player joined the server in their element data, and allows them to view it by typing a command:

-- Make our 'joinTime' function be called when a player joins
addEventHandler ( "onPlayerJoin", getRootElement(), "joinTime" )
function joinTime ( )
    setElementData ( source, "joinTime", os.date() ) -- Store the current time in the player's data with the key 'joinTime'
end

-- Add a console command join_time, that takes an optional parameter of a player's name
addCommandHandler ( "join_time", "showJoinTime" )
function showJoinTime ( source, commandName, playerName )
    if ( playerName ) then -- see if a player was specified
        thePlayer = getPlayerFromNick ( playerName ) -- get the player element for the specified player
        if ( thePlayer ) then -- if one was found...
            outputChatBox ( getClientName ( thePlayer ) .. " joined " .. getElementData ( thePlayer, "joinTime" ), source ) -- output the player's join time
        else
            outputChatBox ( "Couldn't find '" .. playerName .. "'", source ) -- display an error
        end 
    else
        -- display when the player who used the function joined and inform how to see other people's join time
        outputChatBox ( "You joined " .. getElementData ( source, "joinTime" ), source )
        outputChatBox ( "Use 'join_time <player name>' to see other people's join time" )
    end
end

See Also