如何使用布尔变量格式化lua字符串



我有一个布尔变量,我想用格式化字符串显示它的值。我尝试使用string.format,但是对于语言参考中列出的格式选项的任何选择,都可以获得以下内容:

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> print(string.format("%cn", 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("%sn", tostring(true)))
true

,但这对lua初学者来说似乎相当间接。是否有我忽略的格式化选项?还是应该使用上述方法?别的吗?

string.format的代码,我没有看到任何支持布尔值的东西。我想在这种情况下tostring是最合理的选择。

的例子:

print("this is: " .. tostring(true))  -- Prints:   this is true

在Lua 5.1中,如果val不是字符串或数字,则string.format("%s", val)要求您手动将valtostring( )包装在一起。

然而,在Lua 5.2中,string.format将自己调用新的C函数luaL_tolstring,这相当于在val上调用tostring( )

可以重新定义字符串。格式来支持额外的%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"

最新更新