我有一个布尔变量,我想用格式化的字符串显示它的值。我尝试使用string.format
,但是对于language reference中列出的任何格式选项,都会得到如下所示的结果
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> print(string.format("%c\n", true))
stdin:1: bad argument #2 to 'format' (number expected, got boolean)
stack traceback:
[C]: in function 'format'
stdin:1: in main chunk
[C]: ?
我可以通过添加tostring
来获得要显示的布尔值,
> print(string.format("%s\n", tostring(true)))
true
但对于这个lua初学者来说,这似乎是相当间接的。有没有我忽略的格式化选项?或者我应该使用上面的方法?还有别的吗?
发布于 2011-07-08 03:41:51
查看string.format
的代码,我看不到任何支持布尔值的内容。我想在这种情况下tostring
是最合理的选择。
示例:
print("this is: " .. tostring(true)) -- Prints: this is true
发布于 2012-06-02 02:32:27
在Lua5.1中,如果val
不是字符串或数字,string.format("%s", val)
要求你用tostring( )
手动包装val
。
然而,在Lua5.2中,string.format
本身将调用新的C函数luaL_tolstring
,这相当于在val
上调用tostring( )
。
发布于 2011-07-14 02:19:49
您可以重新定义string.format以支持额外的%t
说明符,该说明符对参数运行tostring
:
do
local strformat = string.format
function string.format(format, ...)
local args = {...}
local match_no = 1
for pos, type in string.gmatch(format, "()%%.-(%a)") do
if type == 't' then
args[match_no] = tostring(args[match_no])
end
match_no = match_no + 1
end
return strformat(string.gsub(format, '%%t', '%%s'),
unpack(args,1,select('#',...)))
end
end
这样,您就可以对任何非字符串类型使用%t
:
print(string.format("bool: %t",true)) -- prints "bool: true"
https://stackoverflow.com/questions/6615572
复制相似问题