|
[Solved] Table question 9 Months, 2 Weeks ago
|
|
I have a question about "Table":
| Code: |
function test_table()
t1 = {"t1", 1, 2, 3}
t2 = t1
t2[1] = "t2"
temp = t2[4]
t2[4] = t2[2]
t2[2] = temp
Rainlendar_ShowMenu(-1, -1, t1)
end
|
It display {"t2", 3, 2, 1}, but it should display {"t1", 1, 2, 3}.
Why? and how can I fix it?
|
|
|
|
Last Edit: 2013/03/06 12:40 By anoob.
I couldn't speak English! This skin released to Customize.org(Do you want it? Click Picture) Please contact me if interested: jhg5702@gmail.com

|
|
|
Re: Table question 9 Months, 2 Weeks ago
|
|
|
I can't test this right but, but when you make t2=t1, is a reference copy or the creation of a new table with the values of the old one? e.g.
t1 = {"t1", 1, 2, 3} t2 = {"t1", 1, 2, 3} temp = ?
t1 = {"t1", 1, 2, 3} t2 = {"t2", 1, 2, 3} temp = ?
t1 = {"t1", 1, 2, 3} t2 = {"t2", 1, 2, 3} temp = 3
t1 = {"t1", 1, 2, 3} t2 = {"t2", 1, 2, 1} temp = 3
t1 = {"t1", 1, 2, 3} t2 = {"t2", 3, 2, 1} temp = 3
And the ShowMenu function have t1 as an argument...
Did you copy/paste the function from the file or write here directly?
|
|
|
|
|
|
|
Re: Table question 9 Months, 2 Weeks ago
|
|
|
Yes, I want to create a new table with the values of the old one.
Then I can modify the new one, and do not change the old one.
I am write the function here directly (just for example).
|
|
|
|
I couldn't speak English! This skin released to Customize.org(Do you want it? Click Picture) Please contact me if interested: jhg5702@gmail.com

|
|
|
Re: Table question 9 Months, 2 Weeks ago
|
|
Lua, as I forgot, it's based on C, and C doesn't have functions to copy arrays. It directly copy the pointer to the array.
Here's the same question:
stackoverflow.com/questions/640642/how-do-you-copy-a-lua-table-by-value
And the proposed solution in that post (I tried and it works):
| Code: |
function table.copy(t)
local t2 = {}
for k,v in pairs(t) do
t2[k] = v
end
return t2
end
t1 = {"t1", 1, 2, 3}
t2 = table.copy(t1)
|
|
|
|
|
|
|
|
Re: Table question 9 Months, 2 Weeks ago
|
|
|
Thanks, Jorge_Luis
In "Programming in Lua", there is explain, but, because my English is very poor, so I cannot understand what mean.
Now I know, directly setting newTable = oldTable will create a pointer, instead of copy the content of oldTable.
|
|
|
|
I couldn't speak English! This skin released to Customize.org(Do you want it? Click Picture) Please contact me if interested: jhg5702@gmail.com

|
|
|