S
S
Sergey2018-08-14 16:47:41
Programming
Sergey, 2018-08-14 16:47:41

"Slice" nested table at a certain level of the "tower" of tables multiple nested in depth (into themselves)?

Tell me why when building a "tower" from tables (without explicit keys) in depth, you can "cut" a table at a certain level like this: (do not forget about the theory - in lua variables contain references to tables, not copies of tables!)

local t = {{{{{}}}}} -- 4 вложенных
local g = t
local tst = t[1][1][1]

print(t[1][1][1][1]) -- table:
t[1][1] = t[1][1][1]
print(t[1][1] ==  tst, t[1][1][1][1] ) -- true, nil срезалась и "хвост" подтянула!
-- А так нельзя
print( t[1][1][1][1] ) -- table:
local a = t[1][1]
local b = t[1][1][1]
a = b
print( t[1][1][1][1] ) -- table: хвост не подтянут!
print( t[1][1] == g[1][1],  t[1][1]== tst) -- true, false
-- и срез не произошёл! Проверим ещ переменные:
print( a == g[1][1], b == g[1][1], a==b) -- false, false, true
print(a == g[1][1][1], b == g[1][1[1]]) -- true, true

print(a == t[1][1][1], b == t[1][1[1]]) -- true, true
print(t==g) -- true

How can I programmatically implement the correct table slice from the "tower" if I get a nested table at a certain level by a loop:
local pred = t
while (pred) do
    pred = pred[1]
   if pred == t[1][1] then
        pred = pred[1] -- не работает так. см 2 пример
   end
end

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dollar, 2018-08-14
@Graff46

You can not do it this way

local a = t[1][1]
local b = t[1][1][1]
a = b

Because a is just a variable. You assign a new value to it, even a reference, but this does not affect other variables with different names.
But you can do it like this:
local a = t[1]
local b = t[1][1][1]
a[1] = b

Because here we no longer touch the variable a , but work with what it points to, i.e. t[1] , i.e. this is analogous to t[1][1] = b
To answer the question, you not only need to know the nested table at a certain level, but also the table 1 level above (ie the ancestor).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question