←  Ask a Pro

ComputerCraft | Programmable Computers for Minecraft

»

is this a Bug?

gabriel's Photo gabriel 20 Jun 2015

I'm trying to use a table inside a table, bur for some reason is not working
t={teste}
teste={1,2,3}
print(t[1][1])
print(teste[1])
table.insert(t[1],1,5)
print(t[1][1],teste[1])
this is returning
1
1
51

if for example I change "teste={7,2,3}" the first time that this code run it returns
1
7
57
and the second time it returns
7
7
57
I'm pretty confused, the expected result to me was something like
1
1
11
I'm using the computer craft from the tekkit mod, I think it's version is 1.6 or 1.6.1 from what I can do
Quote

Bomb Bloke's Photo Bomb Bloke 21 Jun 2015

First off, bear in mind that when you build a new table, the variable you assign it to doesn't end up holding "the table", it ends up holding a pointer - like a shortcut, or alias - that leads to the table. I suspect you're already aware of this, but it's worth bearing in mind.

Anyway, when you do:

t={teste}

... what is teste? The answer to that is "whatever it was when your script last ended". The reason that value's hanging around in memory is because you didn't define it as being local to the script, and so it went into the global space, which persists until the computer reboots. Read up on scope here.

When you change teste to point to a new table on your second line:

teste={1,2,3}

... that doesn't change which table t[1] points to; it continues to hold a pointer to the table teste pointed to when that first line executed, that being whatever teste was set to at that time.

So: reverse the order of those first two lines.
Quote