In Solidity, there is the uncommon instruction _;
.
_;
is used inside a modifier to specify when the function should be executed.
A modifier is a piece of code that manipulates the execution of a function.
The _;
instruction can be called before and after the call of the function. So, we can put _;
inside the modifier when we want to execute the function, e.g., after checking if something is correct.
Let’s look at some common usage of the _;
instruction.
In this case, we call the instruction after we check that the address of the caller is not equal to 0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B
.
Note: If the check fails, the function will not be executed at all.
pragma solidity ^0.5.0;contract HelloWorld {modifier notForVitalik() {require(msg.sender != 0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, "Not owner");_;}bytes32 message;constructor (bytes32 myMessage) public {message = myMessage;}// this function is NOT for vitalikfunction getMessage() notForVitalik public view returns(bytes32) {return message;}}
We can run the function and make something else afterwards. This is useful in certain cases.
In this case, we emit the event emitGotMessage
after we call the function.
pragma solidity ^0.5.0;contract HelloWorld {event gotMessage();modifier emitGotMessage() {_;emit gotMessage();}bytes32 message;constructor (bytes32 myMessage) public {message = myMessage;}function getMessage() emitGotMessage public returns(bytes32) {return message;}}