lua的string.format函数中,布尔插值字符是什么?

我正在寻找一个适用于string.format的布尔插值字符(正如标题所述)。

我想要一个像这样工作的东西:

print(string.format("nil == false: %b",(nil==false))

% b只是一个占位符,你会得到一个错误。我正在寻找“b”。我不能这样做:

print("nil == false: " .. (nil==false))

因为布尔值无法与字符串连接。我可以这样做:

val=(nil==false)
if val==false then truth="false" else truth="true" end
print("nil==false: ".. truth)

但是这太麻烦了。

点赞
用户2633423
用户2633423

首先你应该尝试阅读《手册》中的相关部分。这将使您发现布尔值没有格式说明符。

Greatwolf 提供的解决方案是,将值显式转换为字符串。如果存在将您的真值可能为nil,但您想将其输出为false的可能性,此技巧非常有用:

truth = nil
print("nil==false: ".. tostring( not not truth ))

通过此方式,nilfalse都将显示为false

编辑(回答评论)

在Lua 5.2中,%s说明符会自动使用内部的tostring将参数转换为字符串。因此:

print( string.format( "%s  %s  %s", true, nil, {} ) )

打印:

true  nil  table: 00462400

否则,您可以创建自己的格式化函数包装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, {} ) )
2013-09-07 20:31:57
用户234175
用户234175

如果你想知道如何修改 string.format 以支持布尔类型,这里有一种方法:

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))

这可能有点难以理解。其思想是用双重转义 %%b 替换字符串中的所有 %b,以避免格式尝试解释它。我们让 string.format 做自己的工作,取得结果后,我们手动处理 %b

2013-09-07 21:00:58