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

"Plr" returns nil?

Asked by 8 years ago

I'm trying to learn string.match and this script looks correct, but it returns nil.

wait()
local player            =game.Players.LocalPlayer
local players           =game.Players:GetChildren()

function match_name(name)
    for i,v in pairs(players) do
        local plr=string.match(v.Name,name)
        if plr then
            return plr
        end
    end
end

player.Chatted:connect(function(msg)
    if string.sub(msg,1,6)=="check~" then
        local plr=match_name(string.sub(msg,7))
        if plr then
            print(plr.Name)
        end
    end
end)

2 answers

Log in to vote
2
Answered by
Phenite 20
8 years ago

You have to return v, because that is the player, instead of plr, which is the string.

Ad
Log in to vote
0
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
8 years ago

In Lua, although not in every language, it is safe to directly compare strings, so that string.match() is not the best way to solve this problem.

Additionally, your check~ command will never return anything anyway, because you make players an empty Table (since game.Players is empty when this script first runs) and then never update it.

wait()
local player = game.Players.LocalPlayer

function match_name(name)
    for i,v in pairs(players) do
        if plr.Name == name then
            return v
        end
    end
end

player.Chatted:connect(function(msg)
    if string.sub(msg,1,6) == "check~" then
        local plr=match_name(string.sub(msg,7))
        if plr then
            print(plr.Name)
        end
    end
end)

This page has the most comprehensive documentation of string patterns, which is what I assume you're trying to learn here.

Answer this question