1
solidity语言的知识点
for
ETH网络中,对于区块链的写入操作,是需要用户支付Gas的,所以我们很多时候选用 memory 而不是 storage。
memory用于临时存储,类似于RAM。
这样定义多个 memory。
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;
可以得到: [2, 4, 6, 8, 10]
payable,ether
还记得我们学习过的函数可视范围词么?
还有对于函数的操作范围的限定词:
还有可以自定义的限定词:
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
- 招募50名开发者(识别下图二维码或点击“阅读原文”即可了解详情并报名)
北京blockathon回顾:
Blockathon(北京):48小时极客开发,区块松11个现场交付项目创意公开
成都blockathon回顾:
网友评论