Lua: Implementing and understanding deep copy

Preface: This article mainly talks about how deep copy is implemented. It does not talk about shallow copy. If you don’t know about shallow copy, you can read other blogs.

Meaning: If you want to copy a table in the program, directly using the = sign assignment actually gets the address of the table. In essence, these two variables The same table is stored. If a value in the table is changed in one variable, it will also be changed in another variable. The meaning of deep copy is to copy an identical but not the same table.

实现深拷贝的代码:
t={
    
    name="asd",hp=100,table1={
    
    table={
    
    na="aaaaaaaa"}}};

function copy_Table(obj)

		function copy(obj)
			if type(obj)  ~= "table" then						--对应代码梳理“1”  (代码梳理在下面)
				return obj;
			end
			local newTable={
    
    };									--对应代码梳理“2

			for k,v in pairs(obj) do
				newTable[copy(k)]=copy(v);						--对应代码梳理“3
			end
			return setmetatable(newTable,getmetatable(obj));
		end
		
	return copy(obj)
end

a=copy_Table(t);

for k,v in pairs(a) do
	print(k,v);
end

explain:

  • Core logic: Use recursion to traverse all elements in the table.
  • Code sorting:
    1. First look at the code in the copy method. If this type is not a table, there is no need to traverse it. You can Assign directly as the return value;
    2. The variable currently passed in is a table, so create a new table to store the data in the old table. The following is to traverse the old table and assign k and v respectively. After completing the assignment to the newly created table, assign the metatable of the old table to the new table.
    3. When assigning values ​​to k and v, the copy method must also be called to determine whether it is a table. If it is a table, a new table must be created to receive the data in the table. Analogy and close to infinite recursion.

operation result:

>lua -e "io.stdout:setvbuf 'no'" "6.17.lua" 
table1	table: 00B09180
name	asd
hp	100
>Exit code: 0

Judgment:

  1. Determine whether table a after deep copy and original table t are the same function address;
  2. Determine whether na of table in table1 of table a has been copied;
print(t);
print(a);
print(a.table1.table.na);

operation result:

>lua -e "io.stdout:setvbuf 'no'" "6.17.lua" 
table: 00B594A0
table: 00B59798
aaaaaaaa
>Exit code: 0

おすすめ

転載: blog.csdn.net/u011229164/article/details/106816260