StackUser
StackUser

Reputation: 265

Lua Tables: how to assign value not address?

Here is my code:

test_tab1={}
test_tab2={}
actual={}
actual.nest={}

actual.nest.a=10
test_tab1=actual.nest 
print("test_tab1.a:" .. test_tab1.a) -- prints test_tab1.a equal to 10

actual.nest.a=20
test_tab2=actual.nest 
print("test_tab2.a:" .. test_tab2.a) -- prints test_tab2.a equal to 20
print("test_tab1.a:" .. test_tab1.a) -- prints test_tab1.a equal to 20

Actual Output:

test_tab1.a:10
test_tab2.a:20
test_tab1.a:20

As per my understanding both test_tab1 and test_tab2 are pointing to same address i.e actual.nest so when I am assigning actual.nest.a=20 value of test_tab1.a is also changing to 20 which was 10 previosuly.

Expected Output:

test_tab1.a:10
test_tab2.a:20
test_tab1.a:10

Can anyone help me getting this output?.If i am changing actual.nest.a=20 second time it should not reflect in test_tab1.a i.e 10

Upvotes: 3

Views: 232

Answers (1)

hjpotter92
hjpotter92

Reputation: 80639

You'll have to do a copy/clone of the tables from source to destination. Doing t1 = t2 just assigns t1 the address of t2 to t1.

Here's a copy of shallow copy method you can use:

function shallowcopy(orig)
    local orig_type = type(orig)
    local copy
    if orig_type == 'table' then
        copy = {}
        for orig_key, orig_value in pairs(orig) do
            copy[orig_key] = orig_value
        end
    else -- number, string, boolean, etc
        copy = orig
    end
    return copy
end

actual={}
actual.nest={}

actual.nest.a=10
test_tab1 = shallowcopy(actual.nest)
print("test_tab1.a:" .. test_tab1.a) -- prints test_tab1.a equal to 10

actual.nest.a = 20
test_tab2 = shallowcopy(actual.nest)
print("test_tab2.a:" .. test_tab2.a) -- prints test_tab2.a equal to 20
print("test_tab1.a:" .. test_tab1.a) -- prints test_tab1.a equal to 20

Upvotes: 3

Related Questions