3

Since functions are not first-class objects in Solidity, is there any way to invoke a dynamically-determined function at runtime? e.g.

string fname = "Bar";

function Foo() {
  InvokeByName(fname);
}

function Bar() {
  // do something
}

Please respond regarding the feasibility and disregard security for the purpose of this question.

Raine Revere
  • 3,600
  • 2
  • 23
  • 34

1 Answers1

8

Yes, this is possible, but with some limitations.

You can call a function based on its ABI, so in your case

this.call(bytes4(sha3("Bar()")));

will call the Bar function of your contract. If the function takes an argument, you can add it to the call like so:

this.call(bytes4(sha3("Bar(int256)")), 42);

The only limitation to this is that you cannot return a value from this function, it only returns true, or false if it hits an exception.

You could use a global result variable, though.

In terms of security, it really depends on the context but be careful using msg.sender for authentication -- you may want to use callcode or delegatecall depending on your needs.

Tjaden Hess
  • 37,046
  • 10
  • 91
  • 118
  • Thank you! The duplicate that was marked is very useful, too: http://ethereum.stackexchange.com/questions/3342/pass-a-function-as-a-parameter-in-solidity – Raine Revere May 20 '16 at 19:38