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 |
Improving on dragonworx's code
function table.indexOf(t, object)
if type(t) ~= "table" then error("table expected, got " .. type(t), 2) end
for i, v in pairs(t) do
if object == v then
return i
end
end
end
Returns nil
if it can't find it, so you don't have to check i == -1
. With this you only have to check for i
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why not return straight from the if statement? also throw an error if invalid 1st arg: