luacommandgarrys-mod

GMod | Want to make a simple command that prints a colored message in the senders chatbox


I just want to make a simple script that prints a colored text in the chat of the sender after executing a specific command.

First the console gave me an error [attempt to index global 'chat' (a nil value)]. After reloading the Singleplayer and opening the script it didn't do anything.

Current Code:

local ply = LocalPlayer()

local function Test( ply, text, team )
    if string.sub( text, 1, 8 ) == "!command" then
        chat.AddText( Color( 100, 100, 255 ), "Test" )
    end
end
hook.Add( "PlayerSay", "Test", Test )

I hope that someone could help me.


Solution

  • You're using LocalPlayer() (which is only called client-side) as well as chat.AddText() (again, only called client-side) inside of a "PlayerSay" hook (which is a server-side hook). You'd need something else, like ChatPrint()

    EDIT: Just realized ChatPrint() doesn't accept Color() arguments in it... you could always try sending a net message:

    if SERVER then 
        util.AddNetworkString( "SendColouredChat" )
    
        function SendColouredChat( ply, text )
            if string.sub( text, 1, 8 ) == "!command" then
                net.Start( "SendColouredChat" )
                    net.WriteTable( Color( 255, 0, 0, 255 ) )
                    net.WriteString( "Test" )
                net.Send( ply )
            end
        end
        hook.Add( "PlayerSay", "SendColouredChat", SendColouredChat )
    end
    
    if CLIENT then 
        function ReceiveColouredChat()
            local color = net.ReadTable()
            local str = net.ReadString()
    
            chat.AddText( color, str )
        end
        net.Receive( "SendColouredChat", ReceiveColouredChat )
    end
    

    EDIT: Returned to this question after a few years. For anyone else who may run into this later on, it's much simpler to just use the GM:OnPlayerChat hook.

    local function Command(ply, text, teamOnly, dead)
        if text:sub(1, 8) == "!command" then
            chat.AddText(Color(100, 100, 255), "Test")
        end
    end
    hook.Add("OnPlayerChat", "TestCommand", Command)