• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!
  • It's time for the first HD Modeling Contest of 2024. Join the theme discussion for Hive's HD Modeling Contest #6! Click here to post your idea!

Lua Weak tables for (unit) indexing

Status
Not open for further replies.
Level 9
Joined
Mar 26, 2017
Messages
376
Making a table weak valued allows handle indices that are held in a lua table to be recycled, even though they are still kept in the lua table.

Lua:
setmetatable(<table name>, {__mode = 'v'})

I see in an empty map, that a unit handle gets recycled ~12 seconds after the unit is removed. If the line above is not called, the unit handle never gets recycled, as the lua table reference prevents handle recycling.


I don't know if this is widely used, but it seems useful for (unit) indexing applications. With weak valued tables, it is no longer needed to nil entries when their corresponding game objects get removed.
 
Level 17
Joined
Apr 27, 2008
Messages
2,455
It is useful to prevent memory leaks, but not really for an unit indexer as it's not instant.
In few (most ?) cases you have to clean more data or just do things in game related to the unit (removing special effects or whatever) and you want to do it right when the unit gets removed, not after some time.
So using the __gc method won't help to achieve that.
 
Level 9
Joined
Mar 26, 2017
Messages
376
Yeah, you may be right. If you need the slot cleared immediately this won't work. For instance if you iterate over this table, and only want alive units to be included. Or if the length of the table has meaning.

Still for my personal use, this is helpful on those tables that store unit data. It removes the need to nil this unit data when the unit dies. In some cases even, it removes the need to put a trigger on unit death entirely if the only action would be to nill the table entry that holds the unit handle.

Almost all tables in my map that hold unit data do not require immediate clearing.

Since those tables often have the unit handle as a key, the line would have to be changed into following;
Lua:
setmetatable(<table name>, {__mode = 'k'})
 
Last edited:
Level 17
Joined
Apr 27, 2008
Messages
2,455
In fact that would be the case for pretty much almost every jass type.
I mean what would the point to keep an entry table if the object used as a key is destroyed.
It's just even more true for units because it's the less abstract type / most interactive one.

Only one metatable can be used per table though, that's something to keep in mind.
 
Status
Not open for further replies.
Top