list[item].status, changes every items status?

Report any Hollywood bugs here
Post Reply
Bugala
Posts: 1179
Joined: Sun Feb 14, 2010 7:11 pm

list[item].status, changes every items status?

Post by Bugala »

I have isolated my programs problem to here:

Code: Select all

DebugPrint("status1 :"..wave.enemytable[1].status)
      p_InitializeEnemy(wave.enemytable[0])
DebugPrint("status2 : "..wave.enemytable[1].status)

Function p_InitializeEnemy(enemy)
        enemy.status=1
EndFunction


When program gets to first debuprin place, it continues to this function, and there is nothing else but this one line (i removed all the rest) and then it jump directly back to next debugprint.

But a strangest thing happens.

In first debugrpint, status = 2, but in second debugprint, status = 1?

I am sending item[0] there, yet changing item 0.status to 1, changes also every other items status to 1? Why?

I also tried changing enemy into enemmy in case there was some global table there doing something, but no use.

effit: also changing 0 and 1 to 1 and 2 make no difference, so it doesnt have to do with 0 table chagning all only.
Bugala
Posts: 1179
Joined: Sun Feb 14, 2010 7:11 pm

Re: list[item].status, changes every items status?

Post by Bugala »

I found the problem. Have to say, hardest bug to fid so far I have got in my code.

Problem was that I didnt take into consideration that everytime you put something normally to a table, it is actually a reference instead of independent copy.

In my code my code, i was handling rarity of random appearance by having rarity be for example 10.

This meant that:

Code: Select all

for n = 1 to 10
   insertitem(table, same_item_again_and_again)
next
This naturally resulted in when I would change one of those instances values, it would change all of their values, since each place was actually just having reference to the original.

Solution however was simple:

Code: Select all

for n = 1 to 10
   inseritem(table, CopyTable(same_item_again_but_now_an_independent_copy_each_time) )
next
User avatar
airsoftsoftwair
Posts: 5446
Joined: Fri Feb 12, 2010 2:33 pm
Location: Germany
Contact:

Re: list[item].status, changes every items status?

Post by airsoftsoftwair »

This behaviour is described in the Hollywood documentation, chapter 5.3: tables.
One thing that is important to know when dealing with tables is that when
you assign a table to a new variable, the new variable receives only a
reference to the table. It does not receive an independent copy of the
table. Consider the following code:

Code: Select all

    a = {1, 2, 3, 4, 5}       ; create a table with 5 elements
    b = a                     ; create a REFERENCE of a in b
    b[0] = 2                  ; change element 0 to 2
    DebugPrint(a[0], b[0])    ; will print "2 2"
If you want to create an independent copy of a table, you can use the
CopyTable() function for this.
:)
Post Reply