Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

"Plr" returns nil?

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

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

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.