2016-09-19 8 views
3
여기

내 코드입니다 :루아 테이블 : 어떻게 값을 할당하지 주소?

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.nest 것은 내가 actual.nest.a=20 값을 할당하고 때

test_tab1.a:10 
test_tab2.a:20 
test_tab1.a:20 
대한 이해를 모두 test_tab1 당으로

test_tab2이 같은 주소를 가리키는 test_tab1.a도 20 이전으로 변경되었습니다.

예상 출력 :

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

이 사람이 날이 출력을 받고 도와 드릴까요 .If 내가 test_tab1.a 즉 10

+1

출력이 – moteus

+0

출력은 괜찮 올바른 올바른 것입니다. 하지만 어떻게하면 두 번째 산출물을 얻을 수 있습니까? test_tab1.a : 10 test_tab2.a : 20 test_tab1.a : 10 – StackUser

+0

create separeate table이 필요합니다. 'test_tab1'에 할당하거나'test_tab2'를 할당하고이 사본에서 값을 변경할 때 이것을 할 수 있습니다. 실제로 사용 사례에 따라 다릅니다. – moteus

답변

3

당신은 사본을해야 할 것이다에 반영 안 actual.nest.a=20초 시간을 변경하고/source에서 destination까지 표를 복제합니다. t1 = t2을 실행하면 의 주소가 t2t1으로 할당됩니다.

여기 shallow copy method의 복사본을 사용할 수있다 :

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