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

How do I match a string with an object?

Asked by 8 years ago

I tried this:

local plrs = game.Players:GetPlayers

function findPlayer(message,speaker)
    if (string.sub(message,1,5) == "kill/" and (string.sub(message,7) == plrs.Name then
        print("kaboom.")
end

This script is trying to match a chat message with an object, but this won't work.

BTW, don't tell me I don't know how to use tables and to add parenthesis, I just want to know how I am supposed to get a string and if the string matches with the player's name, then print kaboom.

1 answer

Log in to vote
1
Answered by 8 years ago
Edited 8 years ago

Well, there are several mistakes here.

One is, as you listed in your initial message, the lack of parenthesis in the part

local plrs = game.Players:GetPlayers

which won't work unless you make it

local plrs = game.Players:GetPlayers()

Next, in the statement plrs, you have a list of all the players in the game - Not one player. Take for example if I did

local plrs = game.Players:GetPlayers()

plrs might be a list like:

[1] - Player1

[2] - sayhisam1

[3] - laughablehaha

and so on. plrs.Name isn't actually a part of this list, so your script will throw an error at you because it doesn't know what to do because you are asking for something that doesn't exist.

To remedy this, you can check if the player's name matches for each and every player in the list. This is done with a loop, as follows:

for i,v in pairs(plrs) do
    if v.Name == string.sub(message,7) then
        print("Kaboom")
        break -- This stops the loop
    end
end

Putting it all together, you might end up with some code like this:

local plrs = game.Players:GetPlayers()

function findPlayer(message,speaker)
     if (string.sub(message,1,5) == "kill/" then
        for i,v in pairs(plrs) do
            if v.Name == string.sub(message,7) then
                print("Kaboom")
                break -- This stops the loop
            end
        end
    end
end

There are also quite a few more errors here, such as the usage of string.sub() in order to find the player's name. It won't work because string.sub() returns a substring of a string, meaning that if you have something of variable length like a player's name, you won't necessarily know how long the substring should be.

0
Thank you!! laughablehaha 494 — 8y
Ad

Answer this question