← Back to Lua Course | Chapter 3: Strings | Lesson 7 of 7

string.format से Formatting

string.format %d, %s और %.2f जैसे placeholders वाले एक template से text बनाता है।

string.format से Formatting

string.format C के printf जैसा काम करता है। Common specifiers हैं integers के लिए %d, strings के लिए %s, decimals set करते हुए %.2f के साथ floats के लिए %f, hexadecimal के लिए %x और एक quoted string के लिए %q। %5d और %05d जैसे width और flags output pad करते हैं। एक percent sign print करने के लिए %% इस्तेमाल करें।

Note: %s specifier tostring call करता है, इसलिए यह nil और tables समेत किसी भी value के साथ काम करता है।

उदाहरण: Formatting with string.format

lua
print(string.format("%d items", 3))
print(string.format("%s is %d years", "Ann", 30))
print(string.format("%.2f", 3.14159))
print(string.format("[%5d] [%-5d] [%05d]", 42, 42, 42))
print(string.format("%x %X %o", 255, 255, 8))
print(string.format("%q", 'say "hi"'))
print(string.format("%d%%", 50))

-- Output:
-- 3 items
-- Ann is 30 years
-- 3.14
-- [   42] [42   ] [00042]
-- ff FF 10
-- "say \"hi\""
-- 50%
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. %d को एक fractional part वाला float pass करना
  2. placeholders के लिए पर्याप्त arguments supply करना भूल जाना
  3. percent sign print करने के लिए % को double किए बिना लिखना
चैप्टर सारांश
  • %d integers के लिए है
  • %s कोई भी value लेता है
  • %.2f decimals fix करता है
  • %% एक percent sign print करता है

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.