tags:

views:

210

answers:

2

The following code gives me an error: "syntax error before: Some_ets"

-module(tut).
-export([incr/1]).

Some_ets = ets:new(?MODULE, [bag]).

incr(X) ->
    X+1.

But I am able to delcare the ETS within a function, like:

-module(tut).
-export([incr/1]).

incr(X) ->
    Some_ets = ets:new(?MODULE, [bag]),
    X+1.

Can't I declare a ETS outside a funtion?

+1  A: 

You can't do variable assignments like that in a module. See here.

Matt Kane
+7  A: 

No - unlike other languages there isn't a concept of static initialization - there's no appropriate time for an Erlang system to execute that piece of code.

Erlang does have the concept of a parameterized module however, and that may be what you're after. Have a look here http://www.lshift.net/blog/2008/05/18/late-binding-with-erlang which is a good write up of that - it would allow you to instantiate an "instance" of your tut module bound to a given ets table and save passing around that handle explicitly in your module function calls.

Or if you are into OTP you could have the handle to the ets table passed around in the state variable:

init(_) ->
    Some_ets = ets:new(?MODULE, [bag]),
    {ok, Some_ets}.

and then use it in your handle_call methods:

get_ets_handle() ->
    gen_server:call(?MODULE, {getETSHandle}, infinity).

handle_call({getETSHandle}, _From, Some_ets) ->
    {reply, Some_ets, Some_ets}.
Alan Moore
Object oriented functional programming! I love it! My buzzword-o-meter just went tilt!
Cayle Spandon