Solidity中有以下三种类型的变量:
-
局部变量(local)
- 在函数内声明
- 不存储在链上
-
状态变量(state)
- 在函数外声明
- 存储在链上
-
全局变量(global)
- 获取链上信息,如当前区块的时间戳等
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
contract Variables {
// 状态变量存储在链上
string public text = "Hello";
uint public num = 123;
function doSomething() public {
// 局部变量不存在链上
uint i = 456;
// 下面是一些全局变量
uint timestamp = block.timestamp; // 当前区块的时间戳
address sender = msg.sender; // 当前方法调用者的地址
}
}