Go Back   Cockos Incorporated Forums > REAPER Forums > ReaScript, JSFX, REAPER Plug-in Extensions, Developer Forum

Reply
 
Thread Tools Display Modes
Old 11-23-2018, 07:10 PM   #1
dsyrock
Human being with feelings
 
dsyrock's Avatar
 
Join Date: Sep 2018
Location: China
Posts: 565
Default Weird Lua question about passing values between two tables

I tried to pass some values from Table A to Table B, and then things happend confused me

Code:
A,B={},{}

A[1]=1

B=A
At this point, I think Table B got the value "1" from Table A. And then:

Code:
A[2]=2
I thought that I assigned the value 2 to Table A AFTER I assigned Table A to Table B, so that Table B won't get the value 2. But no, I ran the script, and found that Table B is totally equal to Table A, no matter how much values I assign to Table A after that.

So that confused me. Is it a rule that when I wrote B=A, the Table B will change realtimely according to Table A till the end of the world?

Do I have to change the "B=A" to
Code:
for i=1,#A do

  B[i]=A[i]

end
dsyrock is offline   Reply With Quote
Old 11-23-2018, 08:35 PM   #2
Xenakios
Human being with feelings
 
Xenakios's Avatar
 
Join Date: Feb 2007
Location: Oulu, Finland
Posts: 8,062
Default

Assignment of Lua tables just makes them refer to the same table. So yes, you need to manually deep copy every element to your destination table if you want them to be independent copies. There's also no function for that in the Lua standard library, so you need to implement it with your own loop.
__________________
I am no longer part of the REAPER community. Please don't contact me with any REAPER-related issues.
Xenakios is offline   Reply With Quote
Old 11-23-2018, 08:58 PM   #3
mpl
Human being with feelings
 
mpl's Avatar
 
Join Date: Oct 2013
Location: Moscow, Russia
Posts: 3,960
Default

Code:
 
  function CopyTable(orig)--http://lua-users.org/wiki/CopyTable
      local orig_type = type(orig)
      local copy
      if orig_type == 'table' then
          copy = {}
          for orig_key, orig_value in next, orig, nil do
              copy[CopyTable(orig_key)] = CopyTable(orig_value)
          end
          setmetatable(copy, CopyTable(getmetatable(orig)))
      else -- number, string, boolean, etc
          copy = orig
      end
      return copy
  end
mpl is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -7. The time now is 02:37 AM.


Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2024, vBulletin Solutions Inc.