2016-09-19 4 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 

実際の出力:

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

私の理解test_tab1test_tab2の両方を1として、私はactual.nest.a=20値を代入していたときにそうつまりactual.nest同じアドレスを指していますtest_tab1.aも20に変更されています(以前は10でした)。

予想される出力:?

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

誰もが、この出力を得る私を助けることができます.IF私はあなたがコピーを行う必要があるでしょう10

+1

出力 – moteus

+0

出力は大丈夫であるという正しい正解です。しかし、どのように私は2番目の出力を得ることができますか? test_tab1.a:10 test_tab2.a:20 test_tab1.a:10 – StackUser

+0

create separeate tableが必要です。 'test_tab1'に代入するとき、または' test_tab2'を代入してこのコピーの値を変更するときにこれを行うことができます。それは実際にあなたのユースケースに依存します。 – moteus

答えて

3

すなわち、それはtest_tab1.aに反映していないはずですactual.nest.a=20秒の時間を変更しています/ sourceからdestinationまでの表のクローン。 t1 = t2を実行すると、t1のアドレスはt2になり、t1に割り当てられます。ここで

は、あなたが使用することができます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 
関連する問題