How to check if a named table exists or not in ETS Erlang/Elixir

Viewed 2974

I want to create a table in ets if it does not exists . How can I check if this named exists or not ?

4 Answers

You can use :ets.whereis/1. It will return :undefined if the named table does not exist:

iex(1)> :ets.new :foo, [:named_table]
:foo
iex(2)> :ets.whereis :foo
#Reference<0.2091350666.119668737.256142>
iex(3)> :ets.whereis :bar
:undefined

Your best best is just to see if the table is in the list of all tables. A check as simple as this should be good:

lists:member(table_name,ets:all())

This returns a simple boolean() that you can use in a case to base actions on.

This should do the trick:

def create_table? do 
  if Enum.member?(:ets.all(), :my_table) == false do
      :ets.new(:my_table, [:public, :named_table])
  end
end
Related