Nested Tables और References
Tables दूसरी tables hold कर सकती हैं, और एक को copy करने के लिए explicit काम चाहिए।
In this page:
Nested Tables और References
एक table grids, records, और trees बनाने के लिए tables contain कर सकती है। Assignment सिर्फ reference copy करता है, इसलिए दो variables same table की ओर point कर सकते हैं। एक shallow copy सिर्फ top level duplicate करती है, जबकि nested tables shared रहती हैं, इसलिए एक deep copy को recursion चाहिए।
Note:
दो tables == से बराबर तभी हैं जब वे बिल्कुल same object हों।
उदाहरण: Nested tables and references
local grid = {{1, 2}, {3, 4}}
print(grid[2][1], #grid)
local a = {1, 2}
local b = a
b[1] = 99
print(a[1], a == b, {} == {})
local function shallow(t)
local c = {}
for k, v in pairs(t) do c[k] = v end
return c
end
local copy = shallow(grid)
copy[1][1] = "shared"
print(grid[1][1])
-- Output:
-- 3 2
-- 99 true false
-- shared
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- यह मान लेना कि local b = a एक separate copy बनाता है
- दो tables के contents test करने के लिए == से compare करना
- एक shallow copy बनाना और एक nested table modify करना
चैप्टर सारांश
- Tables nest हो सकती हैं
- Assignment एक reference share करता है
- एक shallow copy nested tables share करता है
- == tables के लिए identity compare करता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: