Difference between revisions of "Table.find"

From GiderosMobile
(Created page with "__NOTOC__ '''Available since:''' Gideros 2022.3<br/> '''Class:''' table<br/> === Description === Within the given array-like table ''t'', find the first occurrence of ''v...")
 
m (Text replacement - "</source>" to "</syntaxhighlight>")
 
(One intermediate revision by the same user not shown)
Line 5: Line 5:
 
=== Description ===
 
=== Description ===
 
Within the given array-like table ''t'', find the first occurrence of ''value'', starting from ''index'' or the beginning if not provided. If the value is not found, nil is returned.
 
Within the given array-like table ''t'', find the first occurrence of ''value'', starting from ''index'' or the beginning if not provided. If the value is not found, nil is returned.
<source lang="lua">
+
<syntaxhighlight lang="lua">
 
(any) = table.find(t,value,index)
 
(any) = table.find(t,value,index)
</source>
+
</syntaxhighlight>
  
 
  '''A linear search algorithm is performed'''
 
  '''A linear search algorithm is performed'''
Line 20: Line 20:
  
 
=== Example ===
 
=== Example ===
<source lang="lua">
+
<syntaxhighlight lang="lua">
 
local t = {"a", "b", "c", "d", "e"}
 
local t = {"a", "b", "c", "d", "e"}
 
print(table.find(t, "d")) --> 4
 
print(table.find(t, "d")) --> 4
 
print(table.find(t, "z")) --> nil, because z is not in the table
 
print(table.find(t, "z")) --> nil, because z is not in the table
 
print(table.find(t, "b", 3)) --> nil, because b appears before index 3
 
print(table.find(t, "b", 3)) --> nil, because b appears before index 3
</source>
+
</syntaxhighlight>
  
 
{{Table}}
 
{{Table}}

Latest revision as of 15:33, 13 July 2023

Available since: Gideros 2022.3
Class: table

Description

Within the given array-like table t, find the first occurrence of value, starting from index or the beginning if not provided. If the value is not found, nil is returned.

(any) = table.find(t,value,index)
A linear search algorithm is performed

Parameters

t: (table) source table
value: (any) value to find
index: (number) index to start the search at optional

Return values

Returns (any) the index of first occurence of value or nil if not found

Example

local t = {"a", "b", "c", "d", "e"}
print(table.find(t, "d")) --> 4
print(table.find(t, "z")) --> nil, because z is not in the table
print(table.find(t, "b", 3)) --> nil, because b appears before index 3