lua格式化字符串string.format

引用lua的官方文档:

string.format (formatstring, ···)##

Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the ISO C function sprintf
. The only differences are that the options/modifiers *, h, L, l, n, and p
are not supported and that there is an extra option, q
.

简单的说就是lua格式化字符串和 c sprintf (string print format)遵循同样的规则,唯一的不同是修改了*, h, L, l, n新增了q选项。
sprintf规则格式

%[指定参数][标识符][宽度][.精度]指示符

%% 印出百分比符号,不转换。
%c 整数转成对应的 ASCII 字元。
%d 整数转成十进位。
%f 倍精确度数字转成浮点数。
%o 整数转成八进位。
%s 整数转成字符串。
%x 整数转成小写十六进位。
%X 整数转成大写十六进位。

大神说过

Talk is cheap. Show me the code

local string_format_test = {
'string.format("%%")',
'string.format("%c", 48)',
'string.format("%d", 48)',
'string.format("%.2f", math.pi)',
'string.format("%.5o", math.pi)',
'string.format("%.5s", math.pi)',
'string.format("%x", 10)',
'string.format("%X", 10)'
}

for k, v in ipairs(string_format_test) do
    local f = loadstring("return "..v)
    print(tostring(v), "->", f())
end

输出:

string.format("%%") ->  %
string.format("%c", 48) ->  0
string.format("%d", 48) ->  48
string.format("%.2f", math.pi)  ->  3.14
string.format("%.5o", math.pi)  ->  00003
string.format("%.5s", math.pi)  ->  3.141
string.format("%x", 10) ->  a
string.format("%X", 10) ->  A

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容