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

我有一个布尔变量,希望在格式化的字符串中显示其值。我尝试使用 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]: ?

我可以通过添加 tostring 将布尔显示出来,

> print(string.format("%s\n", tostring(true)))
true

但这对于这个 Lua 新手来说似乎有点间接。我有没有忽略某一种格式选项?或者我应该使用上面的方法?还是其他什么?

原文链接 https://stackoverflow.com/questions/6615572

点赞
stackoverflow用户111886
stackoverflow用户111886

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

举个例子:

print("this is: " .. tostring(true))  -- 输出: this is true
2011-07-07 19:41:50
stackoverflow用户34799
stackoverflow用户34799

你可以重定义 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)) -- 输出 "bool: true"
2011-07-13 18:19:49
stackoverflow用户272427
stackoverflow用户272427

在 Lua 5.1 版本中,当val不是字符串或数字时,string.format("%s", val)需要手动使用tostring()val包装起来。

然而在 Lua 5.2 版本中,string.format会自动调用新的 C 函数luaL_tolstring,这个函数等同于调用tostring()来处理val

2012-06-01 18:32:27