Fendec
Fendec

Reputation: 367

Extracting a value from an ets:lookup() - Erlang

I have a ets table formatted as below

ets:new(players, [set,named_table])

The data that is put into the table is a players name and their age.

It is in the format of [{Name,Age}]

I made a function to try get a players age and age only.

getPlayerAge(PlayerName)->
  Player = ets:lookup(players,PlayerName),
  [{_,Age}] = Player,
  Age.

I am getting a badmatch error and honestly I am confused as hell.

Can this be done or am I way off?

Upvotes: 0

Views: 1297

Answers (1)

legoscia
legoscia

Reputation: 41668

Presumably the exact error is this one:

{badmatch, []}

That is, the value you got from ets:lookup is [], the empty list, and that doesn't match the pattern [{_,Age}]. ets:lookup returns an empty list if it doesn't find an element with the given key. You could check that the table actually contains what you expect it to contain by calling ets:tab2list(players) and inspecting the return value.

Upvotes: 1

Related Questions