Lua’s “Passage” and “Biographical reference” (also known as “inventory”)

In Lua, except that table is passed by reference, the rest are basically passed by value. So when you print a table directly, what you see is a pointer type data.

On the one hand, you cannot copy a table by simply “=”, because it is still its own reference (address) that is passed in this way, and an additional method must be written to realize the copy of the table;

h3>

On the other hand, the table type data returned by the function return is also a return reference. If you want to get the data in a read-only way, you should perform a copy operation after getting it, and then copy it Make modifications;

For other common data types except table, it is basically the way of passing values. The following uses functions as an example:

function fun_1()

print(“first function”)

end

function fun_2()

Print(“second function”)

end

x= fun_1

y=x

x=fun_2

y()

x()

Output: First function Modifying x has no effect on y, which can be seen as a “value transfer” method.

Second function

p>

The following is an example of implementing copy table:

function cloneTable(tab) – Clone a table < /div>

local function copy(target, res)
for k,v in pairs(target) do
if type(v) ~= “table” then < /div>

Res[k] = v;
Else
Res[k] = {};
]) Recursion
end
end end
end
local result = {}

copy(tab, result)
return result
end

function cloneTable(tab ) Clone a table
local function copy(target, res)
for k,v in pairs(target) do

if type (v) ~ = “table” then

res [k] = v;

else

res [k] = {};
Copy(v, res[k]) – Recursion
End
End
End

local result = {}
copy(tab, result)
return result
end

function cloneTable(tab) – Clone a table

local function copy(target,res)

for k,v in pairs(target)do

If type(v) ~= “table” then

Res[k] = v;

Else

;

copy(v, res[k]) – recursion

end

end

end

local result = {}

copy(tab,result)

return result

end

Leave a Comment

Your email address will not be published.