Making an addon/command that can switch the server the player is on?

I recently got set up another server to go along with my already-existing DarkRP one (the new one is another gamemode), and I’m wondering how I could make it so a player could say something in chat to switch servers? I think I remember seeing it on a server before, but I’m wondering how I could do it myself…

I think I have an idea of how I’d do it, but I’m wondering what the command itself is…



local servers = {
    "server1" = "address1",
    "server2" = "address2"
}
function chatCommand( ply, text, public )
    if text:match'^!goto (.+)' then
        server=text:match'^!goto (.+)'
        if servers[server] then
            ply:switchServer(servers[server])
        end
    end
end
hook.Add( "PlayerSay", "chatCommand", chatCommand );


Use the OnPlayerChat hook instead of PlayerSay, so this can all be clientside. Also, your ply:switchServer(servers[server]) function should be replaced with ply:ConCommand("connect "…servers[server])

[editline]10th July 2014[/editline]

Also instead of matching the text for your command twice and making a global variable, just make a local variable like


local serv = text:match'^!goto (.+)'

Then compare it in one if statement. So your completed code would look something like this.


local servers = {
    "server1" = "address1",
    "server2" = "address2"
}
function chatCommand( ply, text, public )
	local server = text:match'^!goto (.+)'
    if (server && servers[server]) then
        ply:ConCommand("connect "..servers[server])
    end
end
hook.Add( "OnPlayerChat", "chatCommand", chatCommand );

ah ok, thanks. Also, so I don’t have to make another thread, say I wanted to add my own function to a player (like you can with entities), could I just add it in, say, a hook? Or would the function get lost when the hook is done running?


plymeta = FindMetaTable("Player")

function plymeta:YOURFUNCTION()
// use 'self' to access the player
end

Localize plymeta, no reason to make it global.