Roku Developer Program

Join our online forum to talk to Roku developers and fellow channel creators. Ask questions, share tips with the community, and find helpful resources.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
mkdir1995
Visitor

Is there a simple way to set and get a global variable?

If you need to set a global variable within your main file (where your screen is created and set) you can do it via the global node.


  m.global = screen.getGlobalNode()
  m.global.id = "GlobalNode"    
  m.global.addFields( {
    globalVariable: yourVariableHere
  } )


If you need to set a global variable outside of where your screen is set, I found a very helpful function in one of the examples (I forgot which one) but I use it in my code as well...
function AddAndSetFields( node as object, aa as object )
  addFields = {}
  setFields = {}
  for each field in aa
    if node.hasField( field )
      setFields[ field ] = aa[ field ]
    else
      addFields[ field ] = aa[ field ]
    end if
  end for
  
  node.setFields( setFields )
  node.addFields( addFields )
end function


And then I use the function in a separate .brs file like so:

AddAndSetFields( m.global, { globalContent: myVariableHere } )     


After this is set and working correctly, I can retrieve and use the variable I need by calling m.global.globalContent 😄
Hope that helps! I actually got that figured out by help from the forum!
0 Kudos
Need Assistance?
Welcome to the Roku Community! Feel free to search our Community for answers or post your question to get help.

Become a Roku Streaming Expert!

Share your expertise, help fellow streamers, and unlock exclusive rewards as part of the Roku Community. Learn more.