Solidity-variables
提供:Dev Guides
堅牢性-変数
Solidityは3種類の変数をサポートしています。
- 状態変数-値が契約ストレージに永続的に保存される変数。
- ローカル変数-関数が実行されるまで値が存在する変数。
- グローバル変数-ブロックチェーンに関する情報を取得するために使用されるグローバル名前空間に特別な変数が存在します。
Solidityは静的に型指定された言語です。つまり、宣言中に状態またはローカル変数の型を指定する必要があります。 宣言された各変数には、その型に基づいたデフォルト値が常にあります。 「未定義」または「ヌル」の概念はありません。
状態変数
値が契約ストレージに永続的に保存される変数。
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData; //State variable
constructor() public {
storedData = 10; //Using State variable
}
}
ローカル変数
値が定義されている関数内でのみ使用可能な値を持つ変数。 関数パラメーターは、常にその関数に対してローカルです。
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData;//State variable
constructor() public {
storedData = 10;
}
function getResult() public view returns(uint){
uint a = 1;//local variable
uint b = 2;
uint result = a + b;
return result;//access the local variable
}
}
例
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData;//State variable
constructor() public {
storedData = 10;
}
function getResult() public view returns(uint){
uint a = 1;//local variable
uint b = 2;
uint result = a + b;
return storedData;//access the state variable
}
}
link:/solidity/solidity_first_application [Solidity First Application]の章に記載されている手順を使用して、上記のプログラムを実行します。
出力
0: uint256: 10
グローバル変数
これらはグローバルワークスペースに存在する特別な変数であり、ブロックチェーンとトランザクションプロパティに関する情報を提供します。
Name | Returns |
---|---|
blockhash(uint blockNumber) returns (bytes32) | Hash of the given block - only works for 256 most recent, excluding current, blocks |
block.coinbase (address payable) | Current block miner’s address |
block.difficulty (uint) | Current block difficulty |
block.gaslimit (uint) | Current block gaslimit |
block.number (uint) | Current block number |
block.timestamp (uint) | Current block timestamp as seconds since unix epoch |
gasleft() returns (uint256) | Remaining gas |
msg.data (bytes calldata) | Complete calldata |
msg.sender (address payable) | Sender of the message (current caller) |
msg.sig (bytes4) | First four bytes of the calldata (function identifier) |
msg.value (uint) | Number of wei sent with the message |
now (uint) | Current block timestamp |
tx.gasprice (uint) | Gas price of the transaction |
tx.origin (address payable) | Sender of the transaction |
ソリッド変数名
Solidityで変数に名前を付けるときは、次のルールに留意してください。
- Solidityの予約済みキーワードを変数名として使用しないでください。 これらのキーワードについては、次のセクションで説明します。 たとえば、ブレークまたはブール変数名は無効です。
- Solidity変数名は数字(0-9)で始まってはなりません。 文字またはアンダースコア文字で始まる必要があります。 たとえば、123testは無効な変数名ですが、_123testは有効な変数名です。
- Solidity変数名では大文字と小文字が区別されます。 たとえば、名前と名前は2つの異なる変数です。