Vice City: Multiplayer

Server Development => Scripting and Server Management => Topic started by: aXXo on May 14, 2015, 02:54 AM

Title: Unexpected behaviour of Squirrel tables
Post by: aXXo on May 14, 2015, 02:54 AM
I have been facing an issue in my entire script, which is caused by my misinterpretation of Squirrel tables.
Here is a sample code:

myTable <- {};

function onScriptLoad()
{
   myTable.rawset( "key", 1 );
   print( "My Table's initial length:" + myTable.len() );

   local backup_table = myTable; // Copy the entire table into another table
   print( "Backup's initial length:" + backup_table.len() );

   myTable.rawdelete( "key" );
   print( "My Table's length after deletion:" + myTable.len() );
   
   print( "Backup's length after deletion:" + backup_table.len() );
}

The output for this is:
[SCRIPT]  My Table's initial length:1
[SCRIPT]  Backup's initial length:1
[SCRIPT]  My Table's length after deletion:0
[SCRIPT]  Backup's length after deletion:0

I expected the backup_table 's length to stay as 1, since I did not touch that table. But apparently, every change made to myTable is copied over automatically to backup_table, hence it is not much of a backup.

How can I avoid this? Has this something to do with "delegation"(whatever that is)?
Title: Re: Unexpected behaviour of Squirrel tables
Post by: Murdock on May 14, 2015, 03:25 AM
That happens because you are copying the reference to 'myTable' instead of cloning the actual table.
To copy the table, you should use the 'clone' expression.

Clone performs shallow copy of a table, array or class instance (copies all slots in the new object without recursion).
If the source table has a delegate, the same delegate will be assigned as delegate (not copied) to the new table.

Try out this code:

myTable <- {};

function onScriptLoad()
{
   myTable.rawset( "key", 1 );
   print( "My Table's initial length:" + myTable.len() );
 
   local backup_table = clone myTable; // Copy the entire table into another table
   print( "Backup's initial length:" + backup_table.len() );
 
   myTable.rawdelete( "key" );
   print( "My Table's length after deletion:" + myTable.len() );
   
   print( "Backup's length after deletion:" + backup_table.len() );
}