Module script variables returning refences instead of new objects

I’m creating a system that uses tables of variables that are all based off a single template.
As these same tables are used multiple times in multiple scripts, the obvious answer to me is to stick them in a module script.

However, every variable I attempted to create seems to be refencing the template instead of creating a new table.

The following code is in a module script:

local LOOT_TABLE_TEMPLATE ={
    ID =0;
}

Loot_Tables ={
    Default =LOOT_TABLE_TEMPLATE;
    Test =LOOT_TABLE_TEMPLATE;
    NoItems =LOOT_TABLE_TEMPLATE;
}

Loot_Tables.Default.ID =1
Loot_Tables.Test.ID =2
Loot_Tables.NoItems.ID =3

return Loot_Tables

Printing “Loot_Tables” from above shows all three table’s "ID"s are 3, instead of the actual number each was separately assigned.

I’ve been unable to find any documentation, info, or even mention concerning this behavior at all.
Though I may be missing something, I’m at a complete loss as to how to fix it.

Setting a variable or index to a table gives a reference to that table instead of cloning. Its like referencing an instance, you don’t clone it, you take a reference. You can use table.clone to get a copy instead.

2 Likes

Additionally, table.clone returns a shallow copy of a table, so nested tables will reference the same tables and should also be cloned if necessary.

I think table.clone only works on arrays: lua-users wiki: Copy Table (speaking in the context of this post)

Instead, you’d have to deep copy the dictionary then use that.

Just create a function that returns a new table:

local function getTemplate()
    return {
        ID = 0;
    }
end

It creates a reference because it’s supposed to do that. It’s the exact same table. It’s just like a part. It’s still the same part even though you assign two different variables to it.

2 Likes

That “Quick & Dirty” implementation of table.clone isn’t actually relevant here. Luau’s table.clone can also be used to clone dictionaries.

luau

Huh, I had no idea such a table function existed.
Imagin a world where Roblox properly documents their functions…

Shallow doesn’t deal with nested tables?

image
image

Exactly. As mentioned in last month’s Luau Recap,

if some keys refer to tables that need to be cloned, that can be done manually by modifying the resulting table.

1 Like