Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How to use string.match when it comes to chat commands?

Asked by 7 years ago

I am trying to make my own chat command script but, I haven't really figured out how to use string.match to make it easier to find a player. so far is this the script:

game.Players.PlayerAdded:connect(function(plr)
    local admin = plr:GetRankInGroup(groupid)
    plr.Chatted:connect(function(m)
        local msg = string.lower(m)
        if string.sub(msg, 1, 7) == ":handto" and admin >= 248 then
            local target = string.sub(m, 9, string.len(m))
            game.Players[target].Character.Humanoid.Health = 0
        end
    end)
end)

But how to make it possible to not having the need to write the full username to kill a player?

1 answer

Log in to vote
1
Answered by
M39a9am3R 3210 Moderation Voter Community Moderator
7 years ago

Typically what I will do for an admin command script is make my own function to iterate through all of the players and try to match the name. I would not recommend using string.match() in this instance as you may get a bad comparison. Say you were searching for "AGuy" and there are two people "AGuyWithAShortName" and "IAmAGuy". You might actually end up hitting IAmAGuy unintentionally if he were to have joined the server first.

The basic idea for the code is to get the string that the admin has said and compare it to the other player's names. However, the for other player's name, you will need to compare partial names. So say I had "The" and I am comparing it to "TheLastTheUltimate", I would have to make "TheLastTheUltimate" a partial name. When I compare the string the admin provided and the substring from the username, they should end up matching.

function GetPlayer(targetedPlayerName)
    for _,player in pairs(game:GetService("Players"):GetPlayers()) do
        if targetedPlayerName:lower() == player.Name:sub(1,targetedPlayerName:len()):lower() then --If the targetedPlayerName in all lowercase letters matches the player's name substring from 1 to however long the targetedPlayerName string is in all lowercase letters, then run the logic.
            return player --The actual player object is being returned.
        end
    end
    return nil --At this point, the loop is done and there are no matches.
end

Now in your code, you would be able to get a player from a command such as ":kill M39a" such as below.

if command:sub(1,6) == ":kill " then
    local target = GetPlayer(command:sub(7))
    if target then
        target.Character:BreakJoints()
    end
end

Hopefully this answered your question. If it did, do not forget to hit the accept answer button. If you have any questions, feel free to comment down below and I will get back to you.
0
That seems to be over-complicating things: you could use the 'find' function, which would produce a simpler result. (string:find(thing) == 1) TheeDeathCaster 2368 — 7y
Ad

Answer this question