Skip to content

Instantly share code, notes, and snippets.

@walterlua
Created May 18, 2011 07:38
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walterlua/978150 to your computer and use it in GitHub Desktop.
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
-- 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
@dragonworx
Copy link

why not return straight from the if statement? also throw an error if invalid 1st arg:

table.indexOf = function( t, object )
    if "table" == type( t ) then
        for i = 1, #t do
            if object == t[i] then
                return i
            end
        end
        return -1
    else
            error("table.indexOf expects table for first argument, " .. type(t) .. " given")
    end
end

@wackbyte
Copy link

wackbyte commented Jul 28, 2018

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