I tried to write a wrapper for ets with which you can read and write structures in etc, question is: how to make id to be generated automatically
defmodule StructTable do
defstruct id: 0, data: nil
def create_table do
:ets.new(__MODULE__, [:orderedset, :named_table, {:keypos, 1}])
end
def insert_into_table(%__MODULE__{ id: id, data: data}) do
if hd(:ets.lookup(__MODULE__, id)) == false do
:ets.insert(__MODULE__, {id,data})
else IO.puts("already exists")
end
end
def select_data(iid) do
hd(:ets.lookup(__MODULE__, iid))
end
def select_all do
:ets.tab2list(__MODULE__)
end
end
I used
:ets.last()to get the last key and added one to it; if it was an empty table, it gets anidof 1. Table type isordered_set, which sorts keys.