본문 바로가기
개발/LUA

[LUA] TABLE 정렬(SORT)

by esstory 2019. 10. 19.

루아 테이블 정렬 샘플입니다. 

루아 문서에 있는 table.sort 를 우선 참고

table.sort (list [, comp])

Sorts list elements in a given order, in-place, from list[1] to list[#list]. If comp is given, then it must be a function that receives two list elements and returns true when the first element must come before the second in the final order (so that not comp(list[i+1],list[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead. The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.

출처: http://www.lua.org/manual/5.2/manual.html#pdf-table.sort

 

단순 배열에 대한 정렬은 아래 함수로 쉽게 가능하고

table.sort(list)

 

table 에 있는 키값(예제에서는 name, 또는 '국가') 의 value 로 소팅할 때는 아래 같이 sort 안에 비교 함수를 하나 만들어 넣어야 합니다.

table.sort(list, function(a,b) return a.name < b.name end)

 

소팅 간단한 예제

-- lua sort

-- print 의 결과는 --> 로 표시
function dumpTable(o)
    if type(o) == 'table' then
        local s = '{ '
        for k,v in pairs(o) do
            -- key 가 숫자가 아닌 경우 "key" 
            if type(k) ~= 'number' then 
                k = '"'..k..'"' 
            end
            s = s .. '['..k..'] = ' .. dumpTable(v) .. ','
        end
        return s .. '} '
    else
        return tostring(o)
    end
end

print('--------------------------------------------------------------------')
print('단순 문자 배열 정렬하기')
print('--------------------------------------------------------------------')
local listTable = {"국어", "영어", "수학", 'bbb', 'ccc', 'aaa'}
print(dumpTable(listTable))
table.sort(listTable)
print(dumpTable(listTable))

print('--------------------------------------------------------------------')
print('key=value 테이블 정렬하기')
print('--------------------------------------------------------------------')
local dicTable = {
    {['국적'] = '한국', ['name'] = '영희'},
    {['국적'] ='미국', ['name'] = '철수'},
    {['국적'] = '호주', ['name'] = '가희'},
}

print('소팅전')
print(dumpTable(dicTable))
table.sort(dicTable, function(a,b) return a.name < b.name end)
print('소팅후(이름')
print(dumpTable(dicTable))


table.sort(dicTable, function(a,b) return a['국적'] < b['국적'] end)
print('소팅후(국적')
print(dumpTable(dicTable))

 

결과

댓글