Check if table has element (LUA)

Simple function to check whether a specific key exists within a table in LUA

Similar To

  • Python: if "foo" in dict:
  • PHP: array_key_exists("foo",$array);

Details

Snippet

function tableHasKey(table,key)
    return table[key] ~= nil
end

Usage Example

local t={ ["foo"] = "bar" }

print(tableHasKey(t,"foo"))
print(tableHasKey(t,"notthere"))

Video