简体   繁体   English

如何检查 ETS Erlang/Elixir 中是否存在命名表

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

I want to create a table in ets if it does not exists.如果它不存在,我想在 ets 中创建一个表。 How can I check if this named exists or not?我如何检查这个名字是否存在?

You can use :ets.whereis/1 .您可以使用:ets.whereis/1 It will return :undefined if the named table does not exist:如果指定的表不存在,它将返回:undefined

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

If you're on an older version of Erlang, you can create a lookup function:如果你使用的是旧版本的 Erlang,你可以创建一个查找函数:

def lookup(server, name) do
  case :ets.lookup(server, name) do
    [{^name, pid}] -> {:ok, pid}
    [] -> :error
  end
end

Information taken from: https://elixir-lang.org/getting-started/mix-otp/ets.html信息取自: https ://elixir-lang.org/getting-started/mix-otp/ets.html

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.这将返回一个简单的 boolean() ,您可以在案例中使用它作为操作的基础。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM