Can't update_counter in ets

According to http://erlang.org/doc/man/ets.html#update_counter-4 it says that I can call

update_counter(Tab, Key, UpdateOp, Default) -> Result
where UpdateOp = {Pos, Incr} | {Pos, Incr, Threshold, SetValue}

So I am trying to call matching the signature
update_counter(Tab, Key, {Pos, Inc, Threshold, SetValue}, Default)

table = :ets.new(:my_table, [:set, :named_table, :public, read_concurrency: true, write_concurrency: true])
:ets.update_counter(table, 1, {0, 1, 0, 0}, {0, 0})

The result is ** (ArgumentError) argument error

Can’t figure out where is a mistake.
OTP version is 20.

OK, some points to make here:

  • Tuples are indexed from 1 not 0. (it’s an index not an offset :smile:)
  • By default the key is the first element of the tuple, index 1. You can set this with :keypos option in the option list when you create the ETS table.
  • The Pos argument is the index of the field you want to increment, in this case it should be 2 as your default tuple has 2 elements. It must not be larger than the index of the element you want to increment.
  • Seeing you have set the threshold to 0 you won’t be able to increment it. This is not an error.

It is the Pos value which generates the error here as it must be 2. update_counter will not allow you increment the index or an element outside the existing element tuple.

7 Likes