forgit
ETH网络中,对于区块链的写入操做,是须要用户支付Gas的,因此咱们不少时候选用 memory 而不是 storage。微信
memory用于临时存储,相似于RAM。网络
这样定义多个 memory。app
uint[] memory evens = new uint[](5);
for 语句和其余语言里面的语句很相似。函数
function getEvens() pure external returns(uint[]) { uint[] memory evens = new uint[](5); // Keep track of the index in the new array: uint counter = 0; // Iterate 1 through 10 with a for loop: for (uint i = 1; i <= 10; i++) { // If `i` is even... if (i % 2 == 0) { // Add it to our array evens[counter] = i; // Increment counter to the next empty index in `evens`: counter++; } }
return evens;oop
能够获得: [2, 4, 6, 8, 10]学习
payable,ether
还记得咱们学习过的函数可视范围词么?区块链
还有对于函数的操做范围的限定词:ui
还有能够自定义的限定词:this
payable 是solidity语言里面的另一个很是有用的限定词。
ether 是solidity语言里面的以太币单位。
咱们来看一下这个函数:
function buySomething() external payable { // Check to make sure 0.001 ether was sent to the function call: require(msg.value == 0.001 ether); // If so, some logic to transfer the digital item to the caller of the function: transferThing(msg.sender); }
msg.value :用户支付的以太币
若是这个函数没有payable而用户支付的以太币不会被接受
Withdraws
假设你编写了一个小游戏,有不少玩家能够在游戏里面购买装备。你的这个小游戏赚钱了。
等积累到了必定程度,你是否是想把钱取出来呢?
你能够这样编写一个函数:
contract GetPaid is Ownable { function withdraw() external onlyOwner { owner.transfer(this.balance); } }
假设,Ownable 和 onlyOwner 是经过modifier实现了的函数。
this.balance 是指这个Dapp的以太币
transfer 是转帐函数。
好比,若是咱们的用户支付了多余的以太币,能够这样找零
uint itemFee = 0.001 ether; msg.sender.transfer(msg.value - itemFee);
咱们甚至能够帮助用户之间交易装备:
seller.transfer(msg.value)
本系列文章做者:HiBlock区块链技术布道群-Amywu
原文发布于简书
加微信baobaotalk_com,加入技术布道群
Blockathon|48小时极客竞赛,区块链马拉松等你挑战(上海)
时间:2018年10月19-21日
地点:(上海黄浦)露香园路1号(近淮海东路)P2
北京blockathon回顾:
Blockathon(北京):48小时极客开发,区块松11个现场交付项目创意公开
成都blockathon回顾: