Adding a chat command.

I’m pretty new to lua and I was wondering how I can add a chat command. I asked in the WDYNHW thread but I didn’t get much feedback. I think I need to use ‘Gamemode.PlayerSay’, but I want the command to set a player to a team. For example:

/setplayer frankie admin (or team 2 as it says in the shared.lua table)

How would I go about doing this and designating the player name if it has spaces in it?

Use string.find to search for something within a string (and return it). To get specific things, use string.match. If you want really simple stuff, you can use string.Explode to split the string into chunks.

If you want to allow whitespaces in names, you either have to implement something that allows the usage of “” (if you have a table containing the single words that you split before, check if the argument starts with " (string.find(str, ‘"’) ~= nil) and then iterate over the array until you find one that ends with " (using either string.find(str, ‘"$’) ~= nil or string.find(str, ‘"’) == #str) and concat all tokens within.)

tl;dr: The function would look like this:
[lua]-- Returns all arguments and returns “foo bar” as one.
function GetArgs(str)
– The arguments we are going to return
local args = {}
– the tokens, seperated by whitespace
local tokens = string.Explode(’ ', str)
– are we currently merging?
local concat = false

-- Iterate through all tokens
for _, v in pairs(tokens) do
	-- Concating?
	if concat then
		-- Check if the string ends with "
		if string.find(v, '"', 0, true) == string.len(v) then
			-- stop merging.
			concat = false
			-- remove the " from the end.
			v = string.sub(v, 1, string.len(v)-1)
		-- merge.
		args[#args] = args[#args] .. ' ' .. v
	-- otherwise..
		-- are we a new token beginning with "? 0, true is for "simple matching" - we don't need fancy patterns for this.
		if string.find(v, '"', 0 true) == 1 then
			-- merge now.
			concat = true
			-- remove the " from the beginning.
			v = string.sub(v, 2)
		-- Push it.
		table.insert(args, v)

-- return the arguments.
return args


Example usage:
local args = GetArgs(’/somecommand “here is a playername” “here some other argument” foo bar blorp’)
– args is {’/somecommand’, ‘here is a playername’, ‘here some other argument’, ‘foo’, ‘bar’, ‘blorp’}

I tested it quickly, no guarantee though. Also, I’m not sure if there isn’t already a function like this implemented somewhere in GMod. Also, keep in mind that players can have awkward names and implement something to get them by SteamID/UserID as well.