3

In a file I do a code like this:

Source = {}
Source[1] = { a = 1, b = 2, ... }

in another file, I do the next:

Table = {}
Table[1] = Source[1]
Table[2] = Source[1]

I use this method for creating objects in Lua. Though, they don't act separately, for example, I can't give a different a value for the two tables.

Why? Also, what can I do for it? I want to avoid defining tables one by one.

Zoltán Schmidt
  • 1,286
  • 2
  • 28
  • 48
  • `Source[2]` is `nil` from your code, are you trying to make `Table[2]` the same content as `Table[1]`? – Yu Hao May 28 '14 at 00:53
  • possible duplicate of [How do you copy a Lua table by value?](http://stackoverflow.com/questions/640642/how-do-you-copy-a-lua-table-by-value) – hjpotter92 May 28 '14 at 03:51

1 Answers1

2

The reason is that the variables Table[1] and Table[2] are only references to the same table value, they don't contain the value.

To copy a table by value, copy the values one by one:

for k, v in pairs(Source[1]) do
    Table[1][k]  = v
    Table[2][k]  = v
end

For more on copying tables, see How do you copy a Lua table by value?.

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • Using `pairs` and `iparis` was always hard for me, because I've never leartn something like them in C++. Thank you! – Zoltán Schmidt May 28 '14 at 01:10
  • 1
    @ZoltánSchmidt It's pretty much the same `for (pair c : map({ { "a", 1 }, {"b", 2}} )) cout << c.first << " " << c.second << endl;` except that Lua's [generic for statement](http://www.lua.org/manual/5.2/manual.html#3.3.5) allows multiple loop variables. – Tom Blodget May 28 '14 at 05:45
  • After several failed attempts of implementing this code, I realised that on the right side, a simple `v` is enough. – Zoltán Schmidt May 28 '14 at 12:25