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

Nested Tables और References

Tables दूसरी tables hold कर सकती हैं, और एक को copy करने के लिए explicit काम चाहिए।

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

lua
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
{# 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. यह मान लेना कि local b = a एक separate copy बनाता है
  2. दो tables के contents test करने के लिए == से compare करना
  3. एक shallow copy बनाना और एक nested table modify करना
चैप्टर सारांश
  • Tables nest हो सकती हैं
  • Assignment एक reference share करता है
  • एक shallow copy nested tables share करता है
  • == tables के लिए identity compare करता है

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.