Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Erlang, how do you invoke a function dynamically?

Tags:

erlang

I want to call xyz with the name of a function to be invoked.

-module(sample).
-export([xyz/1]).

xyz(Name) -> Name().

p() -> "you called p".
g() -> "you called g".

But I get the following error:

1> c(sample.erl).
./sample.erl:6: Warning: function p/0 is unused
./sample.erl:7: Warning: function g/0 is unused
{ok,sample}
2> sample:xyz('p').
** exception error: bad function p
     in function  sample:xyz/1
3>
like image 988
ottodidakt Avatar asked Aug 21 '09 06:08

ottodidakt


1 Answers

It is correct that you have to export p and g. You can then use apply/3 to call it.

erlang:apply(sample, p, []).

Only fun-values are usable with the Fun(...) syntax. You are passing in an atom-value. An atom is a 'bad function' as the error message go. You could do something similar to

xyz(p) -> fun p/0;
xyz(g) -> fun g/0.

Then go ahead and call

Fun = xyz(p),
Fun()
like image 98
Christian Avatar answered Dec 11 '22 22:12

Christian