I have an init function which I call start_server:

start_server() ->
    spawn_link(game_loop(0,0)).

The purpose is to start a new process that begin to loop and waiting for someone to send a message there:

game_loop(X,Y) ->
receive
{move, left} ->
    tell_client(X+1,Y),
    game_loop(X+1,Y);

{move, right} ->
    tell_client(X-1,Y),
    game_loop(X-1,Y)
end.

My thaught was that start_server would return the Pid so that I could write something like this in the Erlang terminal:

> Server = server:start_server().

And then use the variable Server to handle the servers via functions like:

move_left(Pid) ->
    Pid ! {move, left}.

But that does not work since start_server() never returns, why is that?

有帮助吗?

解决方案

The function spawn_link/1 takes a function as an argument. But in your code you dont pass a function into it:

start_server() ->
    spawn_link(game_loop(0,0)).

That sample means that the function game_loop/2 will be called first and after it returns spawn_link/1 will be called with an argument which is a result of calling of game_loop/2. But your function game_loop/2 implements infinite loop so it will never returns and so spawn_link/1 will never be called. If we even assume that game_loop/2 returns it must return a function to call spawn_link/1 properly, otherwise an exception will rise.

To do what you want you should pass game_loop/2 as a function into spawn_link/1:

start_server() ->
    spawn_link(fun () -> game_loop(0,0) end).
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top