[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Basic question on weak keys
- From: Rena <hyperhacker@...>
- Date: Thu, 14 Jun 2012 15:07:04 -0600
On Wed, Jun 13, 2012 at 8:12 PM, TNHarris <telliamed@whoopdedo.org> wrote:
> On Wednesday, June 13, 2012 05:59:54 PM Andrew Starks wrote:
>>
>> Why nil? I thought that since a[b] was not weak, it would keep it as a
>> reference? What does __mode ="k" do if an object is collected when it
>> is used in a table as a key? Can someone be so kind as to provide an
>> example?
>>
>
> As has been mentioned, you are not testing what you think you're testing.
> Consider this instead.
>
> a = {}
> b = {}
> a[b] = "foo"
> for k,v in pairs(a) do print(k,v) end
> --> table: 0x18066a0 foo
> b = nil
> collectgarbage('collect')
> for k,v in pairs(a) do print(k,v) end
> --> table: 0x18066a0 foo
>
> In contrast,
>
> a = setmetatable({}, {__mode="k"})
> b = {}
> a[b] = "foo"
> for k,v in pairs(a) do print(k,v) end
> --> table: 0xd9f8b0 foo
> b = nil
> collectgarbage('collect')
> for k,v in pairs(a) do print(k,v) end
> -->
>
>
> -----
> -- tom
> telliamed@whoopdedo.org
>
...but note that the behaviour of the garbage collector isn't
guaranteed, and can be tweaked, so b might not be collected after one
cycle. Or so I've heard...
--
Sent from my Game Boy.