String.count: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
No edit summary
(Simplify the function)
Line 13: Line 13:
== Code ==
== Code ==
<syntaxhighlight lang="lua">
<syntaxhighlight lang="lua">
function string.count(text, search)
function string.count (text, search)
if search and text then
if ( not text or not search ) then return false end
local string_count = 0
for i in string.gfind(text, search) do
return select ( 2, text:gsub ( search, "" ) );
string_count = string_count + 1
end
return string_count
else
return 0
end
end
end
</syntaxhighlight>
</syntaxhighlight>
Line 29: Line 23:


<syntaxhighlight lang="lua">
<syntaxhighlight lang="lua">
outputChatBox(string.count("A Text", "T")) -- and the result is 2!
outputChatBox( string.count( "Just a test string", "t" ) ) -- and the result is 4!
</syntaxhighlight>
</syntaxhighlight>


Code and Edit by Krischkros.
Created by Krischkros, Edited by nextz.

Revision as of 02:17, 5 March 2016

This function counts how many times a string is found from within another string.

Syntax

int string.count(string text, string search)

Required Arguments

  • text: A string to find the text from
  • search: A string defining what to find

Code

function string.count (text, search)
	if ( not text or not search ) then return false end
	
	return select ( 2, text:gsub ( search, "" ) );
end

Usage:

outputChatBox( string.count( "Just a test string", "t" ) ) -- and the result is 4!

Created by Krischkros, Edited by nextz.