lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sun, Jan 6, 2013 at 3:35 AM, Rena <hyperhacker@gmail.com> wrote:
On Sat, Jan 5, 2013 at 11:07 AM, Marc Balmer <marc@msys.ch> wrote:
> Is it possible to change the order of parameters in a function taking varargs?  Maybe using the select(n, ...) function?
>
> This is what I want to do:
>
> function foo(fmt, ...)
>     -- switch element 1 and 2 of {...}
>
>    print(string.format('%d %s', ...))
> end
>
>
> foo('%s %d', 42, 'balmer')
>
> (background is doing i18n in Lua, whith messages (= format strings) that can have the order of parameters changed)
>
>

You can probably hack up something to rearrange parameters, but a much
better idea for i18n is string.gsub:

function foo(fmt, ...)
        local values = {...}
        print(('$2 $1'):gsub('%$(%d+)', values))
end

That doesn't handle format strings, but you could easily extend it to
a syntax like $(1.6f 3) to mean the third key formatted with %1.6f.

--
Sent from my Game Boy.


If you were willing and able to modify the string library's source (or copy/paste the string.format definition and possibly its helper functions into a new file), you could add back parameter indexes to string.format patterns; which was apparently present in Lua 4.0. The author of lua-wow (a Lua distribution slightly modified to match World of Warcraft's embedded Lua) did it here:
https://github.com/luaforge/lua-wow/blob/master/trunk/src/lstrlib.c#L771-L776

This uses the same syntax as the GNU formatted output described here:
http://www.gnu.org/software/libc/manual/html_node/Output-Conversion-Syntax.html#Output-Conversion-Syntax

So you can use this as foo:

function foo(fmt, ...)
print( ("%2$d %1$s"):format(...) )
end

But you may not want to mess around with the source or define a separate and slightly modified version of string.format.