string.find

From GMod Wiki

Jump to: navigation, search
Function
Syntax string.find( String string, String pattern[, Number startindex, Boolean plain] )
Where is this used?
Description:
Returns the start and end positions of the first occurance of pattern starting at startindex till the end of the string, if startindex is not given then it will do from 1 to the end of the string. nil is returned if the pattern cannot be found.
Returns: Integer , Integer
Part of Library: String
Realm: NewerShared.png
BBCode Link: [b][url=http://wiki.garrysmod.com/?title=String.find]String.find [img]http://wiki.garrysmod.com/favicon.ico[/img][/url][/b]



Examples

DescriptionWe'll use this to find the word tea in a message.
Used onNewerShared.png
Code
 
-- The word "tea" starts at the 13th character in this string.
--This prints 13, because tea starts at character 13.
Msg(string.find("Do you want tea for breakfast?","tea"))
 
Output13 is printed in the console


DescriptionMake use of startindex (3rd argument) to start at the 10th index
Used onNewerShared.png
Code
 
Msg(string.find("cake can be good, some cake is not", "cake"))
--this will output 1
Msg(string.find("cake can be good, some cake is not", "cake", 5))
--this will output 24
 
Output1 is printed within the console, then 24 is, showing that if we start at a certain point (i.e. 5) it will skip all letters before that point.


DescriptionFind a period in a string.
Used onNewerShared.png
Code
 
print(string.find("Hello. How are you?", "."))
--this will output 1, in patterns, a period(.) means "match any single character" (you can escape all special chars using "%")
print(string.find("Hello. How are you?", "%."))
--this will output 6 as it now correctly found the period
print(string.find("Hello. How are you?", ".",1,true))
--this will also output 6
 
Output1 is printed within the console, then 6 is, showing how to correctly use "%" to escape special characters, then another 6, showing how to do that with the "plain" argument. The later two ways will also work to find "(" which normally initiates a capturing sub-pattern.


Additional Notes

See Also

Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox