string/find

From Garry's Mod
(Difference between revisions)
Jump to: navigation, search
m
m (Spell correct "world" to "word")
 
(3 intermediate revisions by 2 users not shown)
Line 28: Line 28:
 
{{Ret
 
{{Ret
 
|type=number
 
|type=number
|desc=Starting position of the found text
+
|desc=Starting position of the found text, or nil if the text wasn't found
 
}}
 
}}
 
{{Ret
 
{{Ret
 
|type=number
 
|type=number
|desc=Ending position of found text
+
|desc=Ending position of found text, or nil if the text wasn't found
 
}}
 
}}
 
{{Ret
 
{{Ret
 
|type=string
 
|type=string
|desc=Matched text for each group if patterns are enabled and used
+
|desc=Matched text for each group if patterns are enabled and used, or nil if the text wasn't found
 
}}
 
}}
 
{{Example
 
{{Example
|Description=Change the world "fuck" to "****" in chat messages
+
|Description=Change the word "heck" to "****" in chat messages
|Code=hook.Add( "PlayerSay", "PreventTheFWord", function( ply, text )
+
|Code=hook.Add( "PlayerSay", "NoHeckHere", function( ply, text )
local fStart, fEnd = string.find( text:lower(), "fuck" )
+
local heckStart, heckEnd = string.find( text:lower(), "heck" )
if fStart then
+
if heckStart then
local civilText = string.sub( text, 1, fStart - 1 ) .. "****" .. string.sub( text, fEnd + 1 )
+
local civilText = string.sub( text, 1, heckStart - 1 ) .. "****" .. string.sub( text, heckEnd + 1 )
 
return civilText
 
return civilText
 
end
 
end
 
end )
 
end )
 
}}
 
}}

Latest revision as of 09:53, 3 January 2018

 string.find( )

Contents

Description

Attempts to find the specified substring in a string, uses Patterns by default.

Arguments

string haystack

The string to search in.

Arguments

string needle

The string to find, can contain patterns if enabled.

Arguments

number startPos=1

The position to start the search from, can be negative start position will be relative to the end position.

Arguments

boolean noPatterns=false

Disable patterns.

Returns

number

Starting position of the found text, or nil if the text wasn't found

Returns

number

Ending position of found text, or nil if the text wasn't found

Returns

string

Matched text for each group if patterns are enabled and used, or nil if the text wasn't found

Examples

Example

Change the word "heck" to "****" in chat messages

hook.Add( "PlayerSay", "NoHeckHere", function( ply, text )
	local heckStart, heckEnd = string.find( text:lower(), "heck" )
	if heckStart then
		local civilText = string.sub( text, 1, heckStart - 1 ) .. "****" .. string.sub( text, heckEnd + 1 )
		return civilText
	end
end )


Personal tools
Navigation