API format

From Wowpedia
Jump to: navigation, search
string.format(formatstring, e1, e2, ...)
format(formatstring, e1, e2, ...)

Create a formatted string from the format and arguments provided. This is similar to the printf("format",...) function in C. An additional option %q returns string in a format that can safely be read back by Lua interpreter (puts quotes around a string and escapes special characters), but used by World of Warcraft to preparse all strings before saving them between sessions.

  • c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as an argument.
  • q and s expect a string.
> = string.format("%s %q", "Hello", "Lua user!")   -- string and quoted string
Hello "Lua user!"
> = string.format("%c%c%c", 76,117,97)             -- char
> = string.format("%e, %E", math.pi,math.pi)       -- exponent
3.141593e+000, 3.141593E+000
> = string.format("%f, %g, %.2f", math.pi, math.pi, math.pi)       -- float and compact float
3.141593, 3.14159, 3.14
> = string.format("%d, %i, %u", -100,-100,-100)    -- signed, signed, unsigned integer
-100, -100, 4294967196
> = string.format("%o, %x, %X", -100,-100,-100)    -- octal, hex, hex
37777777634, ffffff9c, FFFFFF9C

Conversions can be applied to the n-th argument in the argument list, rather than the next unused argument. In this case, the conversion character % is replaced by the sequence %d$, where d is a decimal digit in the range [1,9], giving the position of the argument in the argument list. For instance, the call format("%2$d -> %1$03d", 1, 34) will result in "34 -> 001". The same argument can be used in more than one conversion.

Note: if you want a % character to be output as part of your format string, you need to enter %%. ie.

> = string.format("Ratio is %u %%",12)
Ratio is 12 %

Macro Example

This macro prints out the time remaining on the Polymorph debuff in seconds, rounded to the nearest whole number:

/run for i=1,40 do local n,_,_,_,_,_,x,_,_=UnitDebuff("focus",i);if (n=="Polymorph")or (n=="Polymorph(Pig)")or (n=="Polymorph(Turtle)")then SendChatMessage('''format("%.0f"''',-1*(GetTime()-x)).." secs left on "..UnitName("focus").."'s CC!","EMOTE");end end 

External links