← Back to Lua Course | Chapter 4: Tables | Lesson 7 of 7

Sorting, unpack और pack

table.sort एक list order करता है, और unpack और pack tables और value lists के बीच convert करते हैं।

Sorting, Unpack, और Pack

table.sort(t, comp) एक optional comparison function के साथ in place sort करता है जो true return करता है जब पहले argument को पहले आना चाहिए। table.unpack(t) items को separate values की तरह return करता है, और table.pack(...) values को count holding एक n field वाली एक table में collect करता है। Lua 5.3 में unpack table library में रहता है।

Note: Comparison function consistent होना चाहिए, इसलिए <= या >= की बजाय < या > इस्तेमाल करें।

उदाहरण: Sorting, unpack and pack

lua
local nums = {5, 2, 8, 1}
table.sort(nums)
print(table.concat(nums, " "))
table.sort(nums, function(a, b) return a > b end)
print(table.concat(nums, " "))

local words = {"pear", "fig", "banana"}
table.sort(words, function(a, b) return #a < #b end)
print(table.concat(words, " "))

print(table.unpack({1, 2, 3}))
local packed = table.pack("x", nil, "z")
print(packed.n, #packed >= 1)

-- Output:
-- 1 2 5 8
-- 8 5 2 1
-- fig pear banana
-- 1	2	3
-- 3	true
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. numbers और strings मिक्स करने वाली एक list sort करना
  2. Lua 5.1 की तरह directly unpack call करना
  3. एक comparison function लिखना जो equal items के लिए true return करे
चैप्टर सारांश
  • table.sort in place sort करता है
  • एक comparison function order customise करता है
  • table.unpack एक table spread करता है
  • table.pack count को n में रखता है

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.