Check if value exists in table



Published: 2021-06-05 09:30:31 +0000
Categories: LUA,

Language

LUA

Description

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)

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

Keywords

Table, array, dict, has value, in_array, LUA,

Latest Posts


Copyright © 2021 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk and http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion