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

时间:2011-07-07 18:48:46

标签: lua string-formatting

我有一个布尔变量,其值我想在格式化的字符串中显示。我尝试使用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初学者来说似乎是间接的。有没有我忽略的格式化选项?或者我应该使用上述方法?还有别的吗?

3 个答案:

答案 0 :(得分:35)

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

答案 1 :(得分:20)

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

但是,在Lua 5.2中,string.format本身会调用新的C函数luaL_tolstring,这相当于在tostring( )上调用val

答案 2 :(得分:9)

您可以重新定义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"