How to format a lua string with a boolean variable?

Looking at the code of string.format, I don't see anything that supports boolean values. I guess tostring is the most reasonable option in that case.

Example:

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

You can redefine string.format to support an additional %t specifier that runs tostring on an argument:

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

With this, you can use %t for any non-string type:

print(string.format("bool: %t",true)) -- prints "bool: true"

In Lua 5.1, string.format("%s", val) requires you to manually wrap val with tostring( ) if val is anything other than a string or number.

In Lua 5.2, however, string.format will itself call the new C function luaL_tolstring, which does the equivalent of calling tostring( ) on val.