0
votes

I'm trying to create two tables using the same record, with two different names, but it creates only any one of them or sometimes throws an exception.

Following is the code from my record file:

-record(account,{acctnum, cnic, name, address,date ,time, balance=0}).

Following is my code from module called accounts:

-module(accounts).
-compile(export_all).
-include("records.hrl").
start()->
ets:new(current,[named_table,{keypos, #account.cnic}]),
ets:new(savings,[named_table,{keypos, #account.cnic}]).

Sometimes it returns an atom called savings, but sometimes it gives the following error:

** exception error: bad argument in function ets:new/2 called as ets:new(current,[named_table,{keypos,3}]) in call from accounts:start/0 (accounts.erl, line 5)

Please do let me know that either it's possible to create two tables in ets using a single record? If not, then how can I Implement it, I'm trying to create two tables, one for the savings account and other for the current account, how can I resolve this problem?

2
It is as @Pascal and @AlexeyKachayev have said: you cannot create more than ONE named table with the same name. If it a private table then not more than one per process, else not more than one in total. It has nothing to do with the record name as the contents of the table tuples is just data. - rvirding
As an example of that tuples in ETS tables are just data they don't even have to be the same size! You can have tuples with different number of elements as long as they are large enough to contain the key. They don't mean anything to ETS so if they all have the same first element or not ETS does not care, it only cares about the keys. - rvirding

2 Answers

1
votes

There is not problem with creating two ETS based on one record.

** exception error: bad argument
     in function  ets:new/2
        called as ets:new(current,[named_table,{keypos,3}])
     in call from accounts:start/0 (accounts.erl, line 5)

Such exception usually means that the table with the same name is already created. I.e. function start was called twice (first one successfully, and second one - not).

0
votes

When you execute start for the first time, everything is ok, and you get the result the last line of the function. You can check this by using the tv module; execute tv:start() and you can inspect any ets or mnesia table. If you execute start again, then as Alexey says, you will get an error because the table current (and saving) already exists. This maks the shell crash, and destroy the 2 tables; so the next time you will use start, it will be ok again.

If you cannot know if the ets table is already existing, you can test it with a code like this:

ensure(T,Def) ->
    case ets:info(T) of
        undefined -> ets:new(T,Def);
        _ -> ets:delete_all_objects(T) %% or anything you need to do in this case
    end.