lua中的引用与拷贝

Lua中的基本类型是值传递,只有表是引用传递

-----------------例子一
x = 1  
y = x  
y = 10  
print(x)  
--输出:1  

-----------------例子二
function change(x)  
  x = 10  
end  
y = 1  
change(y)  
print(y)   
--输出:1  

-----------------例子三
x = "test"  
y = x  
x = "show"  
print(y)  
--输出:test  


-----------------例子四
x = {abc = "123",456}  
y = x  
x.abc = "xixi"  
print(y.abc)  
--输出:xixi  


-----------------例子五
function show()  
  print("show some thing")  
end   
function move()  
  print("move to")  
end  
x = show  
y = x  
x = move  
y()  
x()  
--输出:show some thing  
--      move to  


-----------------例子六
x = {123,"test"}  
y = x[1]  
x[1] = 456  
print(y)   
--输出:123  


TaskInfo1={
	["id"]=101,
	["info"]={
				["name"]="first_task",["num"]=1
			}
}

TaskInfo2={
	["id"]=102,
	["info"]={
				["name"]="second_task",["num"]=2
		}
}
TaskInfos={}
TaskInfos[1]=TaskInfo1
TaskInfos[2]=TaskInfo2
local List = {}

function fun(Tasks)
	for _, TaskInfo in pairs(Tasks) do
		print(TaskInfo.id)
		List[TaskInfo.id] = TaskInfo
	end
end

fun(TaskInfos)
List[101].id=103
print(TaskInfos[1].id)
--101 102 103

TaskInfos2 = {}
for i=1,2 do
	table.insert(TaskInfos2,TaskInfos[i])
end
TaskInfos2[2].id=104
print(TaskInfos[2].id)


Lua中实现深拷贝:通过把每一层的表给拆分,使得最后一层为lua的基本类型,因此实现拷贝后互相不影响

-- return a deep copy of table<src>
table.deep_clone = function(src)
	if type(src) ~= "table" then
		return src
	end
	local copy_table
	local level = 0
	local function clone_table(t)
		level = level + 1
		if level > 20 then
			--for a,b in pairs(src) do print(a,b) end -- for debug
			error("table clone failed, source table is too deep!")
		end
		local k, v
		local rel = {}
		for k, v in pairs(t) do
			if type(v) == "table" then
				rel[k] = clone_table(v)
			else
				rel[k] = v
			end
		end
		level = level - 1
		return rel
	end
	return clone_table(src)
end
local src_table={["first"] = 1,["second"] = { ["a"] = 2,["b"] = 3}}
print(src_table.second.a)
des_table=table.deep_clone(src_table)
des_table.a = 10
print(src_table.second.a)

--2

--2


猜你喜欢

转载自blog.csdn.net/Hahaha_Val/article/details/79855852
今日推荐