Jump to content




Local table problem


4 replies to this topic

#1 tinynja98

  • Members
  • 7 posts

Posted 01 February 2015 - 04:45 AM

Hello,

I'm working on a chat program and i've encountered a problem where if i call the function editBoxText(task,boxTable,char) with the boxTable being s[cScreen][cBox], the function will change the values of the local table "boxTable" AND the table s[cScreen][cBox]. Is this normal? What i thought would happen is the function changing the values of the local table and not touching the table s[cScreen][cBox]. Thats why i put a "return boxTable" at the end of the function.

Basically, when i enter a letter via my keyboard, it starts the function charInput(), which runs the function editBoxText(), which edits the values of the table (position, text, horizontal position...) and then the charInput() function asks the printBox() function to print the box table that was returned by the function editBoxText.

Here's my code:

c[something] means "current[something]"
s means "screen"

Spoiler

Thanks for your help!

Edited by tinynja98, 01 February 2015 - 04:56 AM.


#2 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 01 February 2015 - 05:04 AM

The idea is that when you do this:

a = {}

... "a" isn't being set to "a table", but rather it's being set to a pointer to where ever the table is in memory.

Thus if you do:

a = {}
b = a
b[1] = "moo"
print(a[1])

... it'll say "moo", because "a" and "b" both lead to the same table.

Same goes for function and co-routine assignments.

#3 tinynja98

  • Members
  • 7 posts

Posted 01 February 2015 - 05:12 AM

Alright thanks for the quick reply! I'll try to find a workaround by myself :)

Have a good one

#4 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 01 February 2015 - 08:54 AM

If you specifically "need" to clone a table, a "simple" way to do so is to serialise then unserialise it. Eg:

myNewTable = textutils.unserialize(textutils.serialize(myOldTable))

The other option is to iterate through the old table and copy everything in it to the new one, though things start getting slightly complex if there're tables in tables, etc.

#5 tinynja98

  • Members
  • 7 posts

Posted 02 February 2015 - 12:17 AM

Thank you for the idea of serializing and unserializing the table. I haven't thought about that. But fyi, i just made the function edit the original table directly and it works perfect now.

Thanks again!





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users