Check if value exists in table (LUA)

This short LUA snippet lets you check whether a table contains a specific value

Similar To

  • Python: if value in dict.values():
  • PHP: in_array($value, $array)

Details

  • Language: LUA

Snippet

function table_contains(tbl, x)
    found = false
    for _, v in pairs(tbl) do
        if v == x then 
            found = true 
        end
    end
    return found
end

Usage Example

local t = {"a","b","c"}
print(table_contains(t,"a")) -- true
print(table_contains(t,"z")) -- false