Browsing through the Ethereum docs I came across this modifier:
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
I am not familiar with usage of _. What does it mean in this context?
Browsing through the Ethereum docs I came across this modifier:
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
I am not familiar with usage of _. What does it mean in this context?
"_" is a special character that is used in functional modifiers. It returns the flow of execution to the original function that is annotated.
Taking your example...
modifier onlyOwner {
if (msg.sender != owner) throw;
_; <- here comes the original code
}
Let's write a function that uses this modifier:
function setContactInformation(string info) onlyOwner{
contactInformation = info;
}
Flow after the modifier is applied:
if (msg.sender != owner) throw;
contactInformation = info;
You can get more info in this section of Solidity docs
This style of coding is called Condition-Oriented programing (you may read a nice coverage by Gavin Wood).
This is a modifier. It's a form of source code roll up.
You use it by tagging a function with the name of the modifier, like this:
function doSomethingSensitive() onlyOwner {
// do stuff
}
The _ tells how to merge the code. In this case, first the modifier code, then the function code.
So, it compiles.
function() ... {
if (msg.sender != owner) throw;
// do stuff
}
You're allowed to reverse that or do more:
modifier onlyOwner {
// do before
__
// do after
}
but I don't recommend it as it introduces flow-control related security problems and head-scratchers in most situations.
You can think of "do after" as "may not make it this far" because the function might (of course) have other ideas, and may not continue as expected.
Hope it helps.
onlyWhileVacant costs(2 ether)
– taco
Apr 09 '21 at 09:10