Sorting, unpack और pack
table.sort एक list order करता है, और unpack और pack tables और value lists के बीच convert करते हैं।
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- numbers और strings मिक्स करने वाली एक list sort करना
- Lua 5.1 की तरह directly unpack call करना
- एक comparison function लिखना जो equal items के लिए true return करे
चैप्टर सारांश
- table.sort in place sort करता है
- एक comparison function order customise करता है
- table.unpack एक table spread करता है
- table.pack count को n में रखता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: