Question about table.Copy

What’s the difference between doing
[lua]tbl = table.Copy(something)[/lua]
[lua]tbl = something[/lua]
I was always wondering ?

with table.Copy if a change is made to the something table then tbl will not be affected, but without it then tbl will be affected by changes to the something table.

If you only do
[lua]tbl = something[/lua]
you are only creating another reference to the same table, not copying the table.

Here’s why this is a useful programming feature.

SomeTable = {500,“I love you”,1234,“Apple pie”}

function RemoveTextValuesFromTable(t)
for k, v in pairs(t) do
if type(v) == “string” then
–the kv loop won’t hit everything correctly now that the table has been shifted
–so this function needs restarting



In examples other than tables, the function’s argument t would be a copy. Since this is not the case with tables (and table-based items such as players and other entities), t remains a reference to the same table that was put into the function. This lets you edit a table from within a function using it as an argument. In my example, that same function runs itself again with that argument, still being a reference instead of a copy.

I’ve had weird things happen when creating a local variable with table.Copy (local copiedtable = table.Copy(sometable)), so I would avoid doing that.

[editline]7th July 2013[/editline]

An example use of table.Copy is the protection of settings from accidental editing.

function RetrieveSavedPlayerRPData(ply)
–insert code here for reading the player’s data from mysql or text files, etc
–example data retrieved is to be referred to below as rpdata
ply.RP = ply.RP || {}
ply.RP.Data = rpdata
return ply.RP.Data

function RetrieveSAFESavedPlayerRPData(ply)
local data = RetrieveSavedPlayerRPData(ply)
if data then return table.Copy(data) end

Accidentally Editing values returned by the second function would not actually change the values on the player. A better example would be player jobs. A player might have ‘player.CurrentJob’ be set to one of a few tables (one per available job). You would not want to ever risk accidentally changing data on a player that affects every player’s job, but you would want a real reference to those job tables in case you were to make a live change on purpose. Thus, you would want a function to retrieve a safe-to-edit copy of the job info table.

Thank you! I get it now, and I see why I would use it.