gtk2hs
Duncan Coutts
duncan@coutts.uklinux.net
Sun, 15 Jun 2003 23:07:12 +0100
On Fri, 13 Jun 2003 19:39:53 +0200
Christian Buschmann <white_russian@gmx.net> wrote:
> I tried to implement a simple counter with gtk2hs. To increase my
> counter I defined following event:
>
> onClicked btn $ do si <- textBufferGetStartIter tb
> ei <- textBufferGetEndIter tb
> val <- textBufferGetText tb si ei False
> textBufferSetText tb $ show $ (+1) $ read val
>
> But now I don't want always read the textfield to get my counter-value,
> I would like to save the state of my increased value and would like to
> pass it to the next call of the function.
> How can I do this?
Use an IORef or an MVar
eg. (untested code)
let initialCounterValue = 0
counter <- newIORef initialCounterValue
btn `onClicked` do
counterValue <- readIORef counter
tb `textBufferSetText` show (counterValue + 1)
writeIORef counter (counterValue + 1)
or with an MVar:
let initialCounterValue = 0
counter <- newMVar initialCounterValue
btn `onClicked` do
modifyMVar_ counter (\counter -> do
tb `textBufferSetText` show (counterValue + 1)
return (counterValue + 1))
The second version is threadsafe.
There are more elegant techniques that hide the evil imperitive state
(the IORef or MVar) but this is the easiest technique to start with.
Duncan