0

Unfortunately, sorting tables in lua still remains difficult for me. Who can help me with the following question:

I would like to sort the table below by pluNumber:

Original tabel:

[3] = {
    [1] = {
        ['article'] = {
            ['pluNumber'] = '204',
            ['name'] = 'Cola Zero'
        }
    },
    [2] = {
        ['article'] = {
            ['pluNumber'] = '202',
            ['name'] = 'Sinas'
        }
    },
    [3] = {
        ['article'] = {
            ['pluNumber'] = '203',
            ['name'] = '7-up'
        }
    },
    [4] = {
        ['article'] = {
            ['pluNumber'] = '201',
            ['name'] = 'Cola'
        }
    }
}

New table:

[3] = {
    [1] = {
        ['article'] = {
            ['pluNumber'] = '201',
            ['name'] = 'Cola'
        }
    },
    [2] = {
        ['article'] = {
            ['pluNumber'] = '202',
            ['name'] = 'Sinas'
        }
    },
    [3] = {
        ['article'] = {
            ['pluNumber'] = '203',
            ['name'] = '7-up'
        }
    },
    [4] = {
        ['article'] = {
            ['pluNumber'] = '204',
            ['name'] = 'Cola Zero'
        }
    }
}

Where do I begin? I didn't succeed with a normal table.sort

Please help

1 Answer 1

0

You need to provide a function that tells Lua which of two table elements comes first.

table.sort(yourTable, function (a, b)
   return a.article.pluNumber < b.article.pluNumber end

Or

table.sort(yourTable, function (a, b)
   return a.article.pluNumber > b.article.pluNumber end

for decending order. This is explained in the Lua reference manual.

https://www.lua.org/manual/5.4/manual.html#pdf-table.sort

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.