简体   繁体   中英

Declaration of ETS in Erlang

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 declare 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 function?

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}.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM