Seg*_*ult 3 string lua boolean
我正在寻找一个布尔插值字符string.format
(如标题所示).
我想要一些可以这样工作的东西:
print(string.format("nil == false: %b",(nil==false))
Run Code Online (Sandbox Code Playgroud)
%b只是一个占位符,你会得到一个错误.我正在寻找'b'.我不能这样做:
print("nil == false: " .. (nil==false))
Run Code Online (Sandbox Code Playgroud)
因为布尔值不能与字符串连接.我可以:
val=(nil==false)
if val==false then truth="false" else truth="true" end
print("nil==false: ".. truth)
Run Code Online (Sandbox Code Playgroud)
但是工作太多了.
那么,首先你应该尝试阅读手册的相关部分.这将让您发现布尔值没有格式说明符.
伟大的狼建议的是一种解决方案,即将值明确地转换为字符串.如果你的真值可能有nil
,但你想输出它false
,这个技巧很有用:
truth = nil
print("nil==false: ".. tostring( not not truth ))
Run Code Online (Sandbox Code Playgroud)
这样既nil
和false
将显示为false
.
编辑(回答评论)
在Lua 5.2中,%s
说明符使用tostring
内部自动将参数转换为字符串.从而:
print( string.format( "%s %s %s", true, nil, {} ) )
Run Code Online (Sandbox Code Playgroud)
打印:
true nil table: 00462400
Run Code Online (Sandbox Code Playgroud)
否则你可以创建自己的格式化函数包装string.format
:
local function myformat( fmt, ... )
local buf = {}
for i = 1, select( '#', ... ) do
local a = select( i, ... )
if type( a ) ~= 'string' and type( a ) ~= 'number' then
a = tostring( a )
end
buf[i] = a
end
return string.format( fmt, unpack( buf ) )
end
print( myformat( "%s %s %s", true, nil, {} ) )
Run Code Online (Sandbox Code Playgroud)
如果你想知道如何修改string.format
它支持bools,这是你可以做到的一种方法:
do
local format = string.format
function string.format(str, ...)
local args = {...}
local boolargs = {}
str = str:gsub("%%b", "%%%%b")
for i = #args, 1, -1 do
if type(args[i]) == "boolean" then
table.insert(boolargs, 1, args[i])
table.remove(args, i)
end
end
str = format(str, unpack(args))
local j = 0
return (str:gsub("%%b", function(spec) j = j + 1; return tostring(boolargs[j]) end))
end
end
print(string.format("%s is %b", "nil == false", nil==false))
Run Code Online (Sandbox Code Playgroud)
跟随它可能有点令人困惑.想法是在字符串中gsub所有"%b"并用双重转义替换它,%%b
因此格式不会尝试解释它.我们让它string.format
做的东西,我们采取结果并%b
自己手动处理.