Created
May 18, 2011 07:38
-
-
Save walterlua/978150 to your computer and use it in GitHub Desktop.
Implementation of JavaScript array.indexOf() in Lua. Also, adds the function to Lua's table library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- table.indexOf( array, object ) returns the index | |
-- of object in array. Returns 'nil' if not in array. | |
table.indexOf = function( t, object ) | |
local result | |
if "table" == type( t ) then | |
for i=1,#t do | |
if object == t[i] then | |
result = i | |
break | |
end | |
end | |
end | |
return result | |
end | |
-- Example Usage: | |
local t = {1,3,5,7,9} | |
print( table.indexOf( t, 9 ) ) -- output: 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Improving on dragonworx's code
Returns
nil
if it can't find it, so you don't have to checki == -1
. With this you only have to check fori