lua-users home
lua-l archive

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


On Sat, Jan 5, 2013 at 8:07 PM, 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)

local nargs = select("#", ...) -- since ... may have nils inside
local args = { ... }
args[1], args[2] = args[2], args[1]
print(string.format("%d %s", unpack(args, 1, nargs))

But IMO in i18n it is often better to use named placeholders, not
positional ones.

I.e.

L = fill_placeholders --
https://github.com/lua-nucleo/lua-nucleo/blob/master/lua-nucleo/string.lua#L160
L("${ID}, ${NAME}", { ID = 42, NAME = "foo" })

HTH,
Alexander.