How & When to use Weak key and value?

https://developer.roblox.com/articles/Metatables

I know how to use MetaTables but I don’t get the concept of _mode what is it useful for and how do I use it?

So when / why / how do you use Weak Keys/Values?

2 Likes

For Roblox, you never really need to.

Some people like to use instances as keys for things like:

local coins = {}

…where coins has keys of Player instances and values of their coin amount. They then learn that when the player leaves, this doesn’t GC the object. So, they try this:

local coins = setmetatable({}, { __mode = "k" })

The idea is that the rest of your code is normal, but when the player leaves (and is parented to nil), it’ll clear out the key. However, that’s not the case because Weak Tables don't work with Instances.

The actual solution is just to hook on PlayerRemoving and set the data to nil there.

The point is that you never need weak tables and using them only really causes problems down the line; there’s almost always a better and more explicit solution.

20 Likes

So it’s basically useless then?

That is a shame.

Can you show me an Example of how to use it with something else that aren’t Instances?

1 Like

I used to ask questions on a website called scripting helpers. I asked this question: Weak Tables. EgoMoose explained it really well with their answer. It helped me understand weak tables.

7 Likes

So let’s say you have a table in a script whose lifetime is as long as the server and whose keys are all of the hats of every character in the game, mapped to the player the hat belongs to. It might sound absurd but I’ve written it before.

I had what was effectively a memory leak because characters were getting deleted but their hats were being held onto by the table. If a player wore 7 accessories and died 100 times there would be 700 useless entries on the table because I forgot to clean it up when they died. The simplest solution is to make the keys weak so when the hats get deleted from the game the entry in the table gets deleted as well.

1 Like

Very interesting but this method doesn’t work with Instances, so how did you make it work?

Hmm looks like I need to take another look at that code then :grimacing:

1 Like

You could simply use the CharacterRemoving and CharacterAdded events to do this. It is better to do these types of things explicitly, similar to what Kampfkarren said.

I wanted to avoid this because I figured utilizing the garbage collector would be faster than Lua space code.

1 Like