2011-07-07 52 views
28

我有一個布爾變量,其值我想顯示在一個格式化的字符串。我試着用string.format,但得到的東西就像在language reference所列格式選項的任何選擇以下內容:如何用布爾變量格式化lua字符串?

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初學者來說似乎相當間接。有沒有我忽略的格式選項?還是應該使用上述方法?還有別的嗎?

+0

爲什麼使用string.format?爲什麼不只是打印(tostring(true)) –

+0

你也不能格式化nil,函數,線程,userdata ... – sylvanaar

+0

@Jane T因爲它是一個較長字符串的一部分,所以這個例子被削減到最小。 –

回答

31

看看string.format的代碼,我沒有看到任何支持布爾值的東西。 我想tostring是在這種情況下最合理的選擇。

7

你可以重新定義的String.Format,以支持在參數運行tostring額外%t符:

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" 
19

在Lua 5.1中,string.format("%s", val)要求您使用tostring()手動換行val,前提是val不是字符串或數字。

然而,在Lua 5.2中,string.format將自己調用新的C函數luaL_tolstring,該函數相當於在val上調用tostring()