Search code examples
rgwidgets

How to increment value of a counter by clicking on a button?


I have a button like this :

win <- gwindow("Extraction des mots clés", visible=TRUE)
obj2 <- gbutton("Valider et afficher les mots suivants",container=win)

I want that each time I press the button, a counter which is set to 0 in my script is incremented.

k<-0

I created this handler :

addHandlerClicked(obj2,handler = function(h,...){
k<-k+1
print (k)
return(k)
})

but when I doprint k outside of the addHandlerClicked, kis still 0. So how can I do ? Moreover, is the instruction return (k)that I wrote above can be used to achieve this ?

Thanks in advance


Solution

  • This is the way R functions work. Objects in (global) workspace have one value and when you create a same-name object within a function, it has no memory of the same name object outside. R functions don't modify other variables, you have to return the modified value and overwrite it explictily. Normally. Enter <<-. This assignment operator will go from the function all the way to the global environment and try to find the same name object and write over/to it. See more info by typing ?"<<-".