Reference counting issue

This forum is for the Lua scriptable clone of DM/CSB called Dungeon Strikes Back by Sophia. Use DSB to build your own highly customised games.

Moderator: Sophia

Forum rules
Please read the Forum rules and policies before posting.
Post Reply
User avatar
Sophia
Concise and Honest
Posts: 4306
Joined: Thu Sep 12, 2002 9:50 pm
Location: Nowhere in particular
Contact:

Reference counting issue

Post by Sophia »

A recent bug in DSB was due to the fact that while Lua table references are reference counted, any pointers to userdata that they may contain are not. Bitmaps and other such things are implemented as Lua tables in DSB, so what this means is that if you are going to use a duplicate of a bitmap, you must be sure that it is regarded as the same table by Lua.

Code: Select all

bmp = dsb_get_bitmap("TEST")
bmp2 = bmp
bmp = nil
This code is fine, because bmp2 is simply a reference to the same DSB bitmap (i.e., a Lua table) as bmp. This use case also covers parameter passing and such, and pretty much most other uses of bitmaps. In other words, if you don't know if your code is fine or not, it probably is.

The problem lies here:

Code: Select all

bmp = dsb_get_bitmap("TEST")
bmp2 = { }
for i in pairs(bmp) do
   bmp2[i] = bmp[i]
end
bmp = nil
Making a copy of the table (as opposed to simply another reference to the same table) will cause the underlying bitmap to be destroyed as soon as any variable that contains it goes out of scope. This means that after bmp is set to nil, the garbage collector will destroy the underlying bitmap, and using bmp2 will cause DSB to crash.

This problem is esoteric enough I have no plans to fix it at the moment, but I thought at least the problem should be documented. :)
Post Reply