【问题标题】:How to check if a named table exists or not in ETS Erlang/Elixir如何检查 ETS Erlang/Elixir 中是否存在命名表
【发布时间】:2019-02-05 06:36:06
【问题描述】:

如果不存在,我想在 ets 中创建一个表。如何检查这个名字是否存在?

【问题讨论】:

  • 我建议在 try..catch 表达式中创建它。

标签: erlang elixir ets


【解决方案1】:

您可以使用:ets.whereis/1。如果命名表不存在,它将返回: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

【讨论】:

  • iex(14)> :ets.new :foo, [:named_table] :foo iex(15)> :ets.whereis :foo ** (UndefinedFunctionError) 函数 :ets.whereis/1 是未定义或私有(stdlib):ets.whereis(:foo)
  • 你使用的是什么版本的 Erlang?你也可以试试:ets.info(:foo)。
  • ets:whereis 是在 Erlang/OTP 21.0 中引入的。
【解决方案2】:

如果你使用的是旧版本的 Erlang,你可以创建一个查找函数:

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

信息来自:https://elixir-lang.org/getting-started/mix-otp/ets.html

【讨论】:

  • 如果表不存在,这将引发badarg 错误。
  • 是的。这是真的。
【解决方案3】:

最好的办法就是查看该表是否在所有表的列表中。像这样简单的检查应该是好的:

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

这会返回一个简单的 boolean(),您可以在案例中使用它来作为操作的基础。

【讨论】:

    【解决方案4】:

    这应该可以解决问题:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 2014-11-30
      • 2015-02-17
      • 2016-07-25
      • 2011-12-15
      • 2021-12-21
      • 1970-01-01
      相关资源
      最近更新 更多