String Formatting With Native Lua string.format() function

guclusat

Tanınmış Üye
Süper Moderatör
Most of AutoPlay Media Studio users are missing a useful function of Lua and trying to concat variables to get a formatted string . Lua has a build-in string format function under string group
[sourcecode]
string.format(formatstring,...)
[/sourcecode]
Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the printf family of standard C functions. The only differences are that the options/modifiers *, l, L, n, p, and h are not supported and that there is an extra option, q. The q option formats a string in a form suitable to be safely read back by the Lua interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written. For instance, the call
The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument, whereas q and s expect a string.
More Info :
Lua 5.1 Reference Manual
if you look at the example below you will see that it looks complex and ugly by design .
and you should look closer at your codes when performance is important
[sourcecode]
nHwnd = Application.GetWndHandle();
szTitle = "My Application";
szMessage = "Hello From My Application";
nPage = 12;
local Args = ""..nHwnd.. ",\""..szTitle.. "\",\""..szMessage.. "\","..nPage;
[/sourcecode]

The above example can be converted like below using native string.format() function
Much easy , Less complex ,Higher performance
[sourcecode]
nHwnd = Application.GetWndHandle();
szTitle = "My Application";
szMessage = "Hello From My Application";
nPage = 12;
local Args = string.format("%d,%s,%s,%d" ,nHwnd,szTitle,szMessage,nPage);
[/sourcecode]

Some Examples :
[sourcecode]
str = string.format("%.6s ...","Serkan's World");
[/sourcecode]
Result : Serkan ...

[sourcecode]
str = string.format("%.2d",1);
[/sourcecode]
Result : 01

[sourcecode]
str = string.format("%.5d",123);
[/sourcecode]
Result : 00123

[sourcecode]
str = string.format("My %d Years Old Doughter Earns %c %.2f Per %s %c",23,36,1200,"Month",46);
[/sourcecode]
Result : My 23 Years Old Doughter Earns $ 1200.00 Per Month .

 
Geri
Yukarı