Confusion by weak tables

So I know how weak tables work in the way that they don’t count as a reference, blah blah blah, that’s not really what I’m thinking about.

So one of my friends at the time, we were talking about table copying and he showed an example on which he seemed to have copied a table by making a table weak and then set that table to another variable and it basically made a copy.

I was wondering if that’s a result from weak table’s implemention because it isn’t a reference or something?

This friend messed a lot with pure Lua and mixed a lot of things which are valid in Lua but not in Luau, is this still the same with Luau?

I think it is the same process and it is documented:

I’m not actually looking into how cloning tables work, more like working out how weak tables work so I can handle them properly and use them properly.
I have been having some code that could benefit from them recently and I just wanna know if I can do it better or if I’m using them right.

Unless you show the code, there’s not much to say here.

Assigning a table, weak or not, does not make a copy of that table:

local a, b, c = {}, {}, {}

local t = setmetatable({
["a"] = a,
["b"] = b,
["c"] = c
}, {__mode = "v"})

local copy = t

print(t)    -- table: 0x28067bc40
print(copy) -- table: 0x28067bc40

print(getmetatable(t))    -- 0x280655880
print(getmetatable(copy)) -- 0x280655880

for k, v in pairs(t) do print(k,v) end
for k, v in pairs(copy) do print(k,v) end

--[[
b	table: 0x280658240
a	table: 0x28065a8c0
c	table: 0x280658f40

b	table: 0x280658240
a	table: 0x28065a8c0
c	table: 0x280658f40
]]
1 Like

What he did was something like this;

local T = {} --// pretend it's weak

local t2 = T
t2.index = 12

--// T2 should have that value on it but not the original "T".

So it doesn’t seem like it was a table copy but it kind of acted like one

We don’t have to pretend

local t = setmetatable({}, {__mode="kv"}) -- make it weak

local t2 = t

t2.something = "test"

print(t.something) --> test
print(t2.something) --> test
1 Like

I’ll look into it further when I can I guess, I wonder if that’s specific to some Lua version