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

How to call a player in a shortened string?

Asked by 5 years ago

Sorry, I have no code. But I'd like to know how I could make a function to call a players name for later use. For example, since I'm making an admin. A command could be, "respawn Cha" it would respawn anyones name who has "cha" in it.

It's a command bar, no chat hook.

2 answers

Log in to vote
1
Answered by 5 years ago

Question

How to call a player in a shortened string?

Answer

We can iterate over all the players in the game and see if the front of their name matches the given string.

How do we get the front of a name?

Well we can use the :sub method which all string datatypes have. When called it will return the text between the positions you gave it.

Example: someName:sub(1, #givenStr)

It will get the 1st part of the string and everything following that has a position less than or equal to the length of #givenStr.

Another Example: local a = ("I like apples"):sub(1, 5) This would result in a being set to the string "I lik" because the first 5 letters of the string are I lik

Fuller Code Example

This would return the player who's name matches the given string.

In this case I would be in the game and it would find my player instance given the string SinisterMem.

It will define the ingame players, iterate over them, check if the name's partial is equal to the partial name, then if so it will return said player.

local players = game:GetService("Player")

local function getPlayerByPartialName(partialName)
    local partialName = partialName:lower() --// so its not case sensitive
    local ingamePlayers = players:GetPlayers()

    for i, player in next, ingamePlayers do
        local name = player.Name:lower() --// so its not case sensitive
        local partial = name:sub(1, #partialName)

        if partial == partialName then
            return player
        end
    end
end

local sinisterMemories = getPlayerByPartialName("SinisterMem")
Ad
Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

When searching for any string in a given string, I find string.find very helpful.

function GetPlayersMatching(str)
    local players = {}
    for _, player in pairs(game:GetService("Players"):GetPlayers()) do
        if string.find(player.Name, tostring(str)) then -- username contains the value
            table.insert(players, player)
        end
    end
    return players
end

String.find can also be used as :find. An example would be

local str = "This is a string"
if str:find("is") then
    print("Found an 'is'.")
end

String.find also returns values of which index the match was found which could be used in conjunction of string.sub.

0
wow you ninja'd me by 3 entire minutes. EpicMetatableMoment 1444 — 5y
0
I use the term ninja'd too! Do we know each other? Like I use the term ninja'd on a daily basis. LucarioZombie 291 — 5y

Answer this question