GetElementData

From Multi Theft Auto: Wiki
Revision as of 16:27, 8 September 2006 by EAi (talk | contribs)
Jump to navigation Jump to search

Elements can contain data values. These are accessable via names, and their value can be retrieved using getElementData and set using setElementData. These values are also loaded from the attributes in the XML map files, and as such can provide a powerful way to store and retrieve data in XML for each element.

Syntax

var getElementData ( element theElement, string key )

Required Arguments

  • theElement: This is the element with data you want to retreive.
  • key: The name of the element data entry you want to retrieve.

Returns

This function returns a variable containing the requested element data, or false if the element data does not exist, or the element itself does not exist. Usually this is a string but it doesn't have to be.

Example

Example 1: This example stores the time a player joins and then allows players to see this using a console function 'join_time'.

-- 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

Example 2: This example will store the version of the map in the variable mapVersion. Generally this will be 2.0 in the final release.

map = getRootElement ( )
mapVersion = getElementData ( map, "version" )

See Also