Lua Table Sort

lua์˜ table ์ •๋ ฌ lua์—์„œ table.sort(t,func) ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ ์ •๋ ฌํ•œ๋‹ค. t๋Š” ํ…Œ์ด๋ธ”, func๋Š” ํ•จ์ˆ˜์ด๋‹ค. table.sort(t) ํ–ˆ์„ ๊ฒฝ์šฐ ์š”์†Œ๊ฐ€ ๋ฌธ์ž,์ˆซ์ž๋ฅผ ๊ธฐ๋ณธ ์ •๋ ฌํ•œ๋‹ค. ํ•˜์ง€๋งŒ ์˜ค๋ฆ„์ฐจ์ˆœ, ๋‚ด๋ฆผ์ฐจ์ˆœ, ๋Œ€์†Œ๋ฌธ์ž ๊ตฌ๋ณ„ ๋“ฑ ๋‹ค์–‘ํ•œ ์ œ์–ด๋ฅผ ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ์•„๋ž˜ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด ํ™œ์šฉํ•˜๋ฉด ํŽธ๋ฆฌํ•˜๋‹ค. ์ฃผ์˜ํ•  ์ ์€ ์›๋ณธ table์˜ ์œ„์น˜๊ฐ€ ์ •๋ ฌ์ƒํƒœ๋กœ ๋ฐ”๋€Œ๊ฒŒ ๋œ๋‹ค. ์›๋ณธ์„ ์œ ์ง€ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ๋ณต์‚ฌ๋ณธ์„ ๋งŒ๋“  ๋‹ค์Œ ์ •๋ ฌํ•ด์•ผ ํ•œ๋‹ค. ํ•„ํ„ฐ ํ•จ์ˆ˜ ์ •์˜ -- *sort.asc* : ์ˆซ์ž,๋ฌธ์ž,UTF8 ๋ชจ๋‘ ๊ฐ€๋Šฅ local function ascending(a,b) return a < b -- a๊ฐ€ b๋ณด๋‹ค ์ž‘์œผ๋ฉด true end -- *sort.desc* : ์ˆซ์ž,๋ฌธ์ž,UTF8 ๋ชจ๋‘ ๊ฐ€๋Šฅ local function descending(a,b) return a > b -- a๊ฐ€ b๋ณด๋‹ค ํฌ๋ฉด true end -- *sort.bylength* local function bylength(a,b) return #a < #b -- ๋ฌธ์ž์—ด์˜ ๊ธธ์ด์— ๋”ฐ๋ผ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ end -- *sort.iascendig* - ๋Œ€์†Œ๋ฌธ์ž ๊ตฌ๋ถ„ ์—†์ด ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ local function iascendig(a,b) return string.lower(a) < string.lower(b) end -- *sort.idescending* - ๋Œ€์†Œ๋ฌธ์ž ๊ตฌ๋ถ„ ์—†์ด ์ •๋ ฌ local function idescending(a,b) return string.lower(a) > string.lower(b) end -- *sort.bykey* local function bykey(key) return function(a,b) return a[key] < b[key] end end ํ™œ์šฉ local numbers = {5, 3, 8, 1, 2} table.sort(numbers, ascending) -- ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ local strings = {"banana", "apple", "cherry"} table.sort(strings, alphabetical) -- ์•ŒํŒŒ๋ฒณ ์ˆœ ์ •๋ ฌ local objects = { {name = "Alice", age = 30}, {name = "Bob", age = 25}, {name = "Charlie", age = 35} } table.sort(objects, byKey("age")) -- ๋‚˜์ด์— ๋”ฐ๋ผ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ REFERENCE duck.ai Quick Guide to Lua Table Sort: Mastering Order with Ease https://luascripts.com/lua-table-sort

2025-08-29 ยท 220 words