Download (32K)
Formatted strings are a real convenience—one that is sorely missing from the Flash Actionscript library. This adds in the sprintf functionality, which lets you reduce something like this:
var m,d; var myDate = new Date(); m = myDate.getMonth() + 1; if (m < 10) m = '0' + m; d = myDate.getDate(); if (d < 10) d = '0' + d; trace(m + '-' + d + '-' + myDate.getFullYear()); // traces out: 02-14-2004
into basically a single line of code:
var myDate = new Date();
Sprintf.trace('%02d-%02d-%4d',myDate.getMonth() + 1, »
myDate.getDate(),myDate.getFullYear()));
// traces out: 02-14-2004
Usage
There are two versions of the sprintf library. The function-based version will work in either Actionscript 1.0 or 2.0, while the class-based version requires Actionscript 2.0. The class-based version was developed by Patrick Mineault (thanks!). Usage of each is described below.
Sprintf.format(formatString, [arg1, [arg2...]])(class)sprintf(format, [arg1, [arg2...]])(function)- I'm not going to get into the ins & outs of using sprintf—but I will send you to read the very well written instructions of one Prof. Don Coltion. Sections 3 through 6 are the relevant ones. Another good source (and the one I developed against) is OS X's printf(1) man page.
- Please note that this isn't a comprehensive implementation. Some conversions, like the pointer address, make no sense in Actionscript. Others are just unimplemented at this time. Functional switches and arguments are:
+- 0anddioxXeEfgGcCsSSprintf.trace(format, [arg1, [arg2...]])tracef(format, [arg1, [arg2...]])- This is shorthand for
trace(Sprintf.format(...)), just to save on typing. Sprintf.TRACEsprintf.SPRINTF_TRACE- Setting this to true will output errors in string formatting to the trace window. False by default.
Sprintf.DEBUGsprintf.SPRINTF_DEBUG- Setting this to true will output errors in string formatting in the parsed string itself. This is more useful for bugs that are only appearing when you aren't in the Flash environment (hate those). False by default.