Lua implements deep copy of table tables

Source: Internet
Author: User

When a Lua variable is passed as a function parameter, values of the Boolean, string, and number types are also transmitted. Variables of the table, function, and userdata types are referenced and passed. Therefore, when table values are assigned

If a value is assigned to table B, operations on the Elements in Table B will naturally affect Table A. Of course, operations on table B itself, such as B = nil or pointing table B to another table, there is no impact on A. The following is the deep copy of Lua table.

 

Deepcopy = function (object) Local lookup_table = {} Local function _ copy (object) If type (object )~ = "Table" then return object elseif lookup_table [object] Then return lookup_table [object] end local new_table ={} lookup_table [object] = new_table for index, value in pairs (object) do new_table [_ copy (INDEX)] = _ copy (value) end return setmetatable (new_table, getmetatable (object) end return _ copy (object) endlocal Testa = {1, 2, 3, 4, 5} Local testb = testatestb [2] = "" Local testc = deepcopy (testa) testc [2] = "" for K, V in ipairs (testa) Do print ("Testa", K, V) endprint ("======================") for K, V in ipairs (testc) Do print ("testc", K, v) End

The running result is as follows:

Testa 1 1
Testa2 I wipe
Testa33
Testa44
Testa55
======================================
Testc11
Testc2
Testc33
Testc44
Testc55

Lua implements deep copy of table tables

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.