lua-users home
lua-l archive

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


On Tue, Jul 29, 2014 at 05:06:12PM +0200, Benoit Germain wrote:
> Unfortunately I can't sort something like this (my data is more complex
> than that of course, I have 600 lines of simular Lua code per settings
> file):
> 
>                 ["pushForceCurve"] =
>                 {
>                     ["param1"] = -4,
>                     ["param3"] = 0.502515,
>                     ["param2"] = 2
>                     ["centerOfMassOffset"] =
>                     {
>                        ["x"] = 0,
>                        ["y"] = 0
>                     },
>                 },

I usually sort it in Lua. I have a sorted_pairs functio which I use when
writing out table data to file. For example,

for k,v in sorted_pairs(t) do
	-- write table data out
end


Here's the sorted_pairs function:

local function sorted_pairs(t)
        local keys = {}

        for k, _ in pairs(t) do
                keys[#keys + 1] = k
        end

        table.sort(keys)

        local i = 0

        return function ()
                if i < #keys then
                        i = i + 1

                        return keys[i], t[keys[i]]
                end
        end
end -- sorted_pairs