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

Mic*_*ber 32 lua string-formatting

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

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]: ?
Run Code Online (Sandbox Code Playgroud)

我可以得到布尔通过增加显示tostring,

> print(string.format("%s\n", tostring(true)))
true
Run Code Online (Sandbox Code Playgroud)

但对于这个lua初学者来说,这似乎是间接的.有没有我忽略的格式化选项?或者我应该使用上述方法?别的什么?

Omr*_*rel 38

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


dub*_*jim 20

在Lua 5.1,string.format("%s", val)需要手动换valtostring( ),如果val是其他什么比一个字符串或数字.

在Lua 5.2,然而,string.format将自称为新的C函数luaL_tolstring,它不叫相当于tostring( )val.


Stu*_*ley 10

您可以重新定义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
Run Code Online (Sandbox Code Playgroud)

有了这个,你可以%t用于任何非字符串类型:

print(string.format("bool: %t",true)) -- prints "bool: true"
Run Code Online (Sandbox Code Playgroud)