简介:上一节,我们介绍了智能合约的开发范例,本节我们将详解智能合约开发中常用的Lib工具库。由于内容较长,工具库我们将分两部分介绍,本文将介绍LibInt和LibString。
- 常用库简介
在合约开发规范中,我们看到contracts目录下有个子目录utillib,此子目录下,是JUICE开放服务平台提供的一些常用工具库。这些工具库提供的方法,和具体的业务没有关系。它的作用,和JAVA中的各种util工具类似。常用的有:
1. LibInt 封装对整数的操作(支持直接调用、using调用)https://open.juzix.net/api_doc/contract/utillib/LibInt.html
2. LibString 封装对字符串的操作 (支持直接调用、using调用) https://open.juzix.net/api_doc/contract/utillib/LibString.html
3. LibJson 封装对JSON格式的字符串操作(支持直接调用、using调用)https://open.juzix.net/api_doc/contract/utillib/LibJson.html
4. LibStack 封装对堆栈的使用(仅支持直接调用)https://open.juzix.net/api_doc/contract/utillib/LibStack.html
5. LibLog 封装日志操作(仅支持直接调用)https://open.juzix.net/api_doc/contract/utillib/LibLog.html
6. 使用方法
在业务合约的头部引入库文件:
pragma solidity ^0.4.2;
import "./utillib/LibLog.sol";
Copy
在合约中直接调用方式:
function myLogger() constant public returns(bool _out) {
LibLog.log("here is my logger message");
...
...
_out = true;
}
Copy
在合约中using使用方式:
pragma solidity ^0.4.2;
import "./utillib/LibString.sol";
contract StringTest is OwnerNamed {
using LibString for * ;
function myString() constant public returns(bool _out) {
LibLog.log("here is my string test");
string memory _string = "hello world";
//using 方式
bool result = _string.compare("hello world");
//直接调用方式
//bool result = LiString.compare(_string, "hello world");
_out = result ;
}
}
注意:
LibJson虽然支持直接调用、using调用,但是它的using调用方式稍有不同,详情查看LIbJson库说明。https://open.juzix.net/api_doc/contract/utillib/LibJson.html
以下示例都将采用 using for *; 方式进行调用
LibInt
LibInt 主要封装了对整形的一系列操作;
支持直接调用、using for *;调用
uint转为字符串
描述:将一个整数转为指定长度字符串
结构定义
function toString(uint _self, uint width) internal returns (string _ret);
示例
uint _uint = 1000;
string memory _ret= _uint.toString(3); // _ret = 100