While true loop keeps crashing roku

 

When I run the below code my roku has a black screen and eventually crashes.
I think the issue is the while true loop but I haven’t figured out how to have a wait or sleep

I found sleep() but it did not do anything to stop the crash
Neither did a thing with wait(0,port) (I may have implemented it wrong)

Here are all my files, their names and locations are designated by “FILE pkg:/*****/*.

File pkg:/components/Pong.brs

Function init() 'Function is run when XML is parsed
m.top.backgroundColor = “0xabc123FF” 'Set background color to black
m.top.backgroundURI = “” 'Set background URI (image) to empty so background color displays

m.Ball = m.top.findNode(“ball”) 'Sets pointer to TopLabel node to adjust fields
m.Ball.blendColor=“0xFFFFFFFF”

ballXPos = CreateObject(“roFloat”)
ballXPos = 0
bounceDirection = CreateObject(“roInt”)
bounceDirection = 0

while true
if ballXPos > 1920
bounceDirection = 1
end if

if ballXPos < 0
bounceDirection = 0
end if

if bounceDirection = 0
ballXPos = ballXPos + 50
else
ballXPos = ballXPos - 50
end if
m.Ball.translation = [ballXPos, 50]
end while

end Function

File pkg:/components/Pong.brs

<?xml version="1.0" encoding="UTF-8"?> FILE pkg:/source/main.brs sub Main() screen = createObject("roSGScreen") 'Creates screen to display screensaver port = createObject("roMessagePort") 'Port to listen to events on screen screen.setMessagePort(port) scene = screen.createScene("Pong") 'Creates scene to display on screen. Scene name (AnimatedScreensaver) must match ID of XML Scene Component screen.show() while(true) 'Uses message port to listen if channel is closed msg = wait(0, port) if (msg <> invalid) msgType = type(msg) if msgType = "roSGScreenEvent" if msg.isScreenClosed() then return end if end if end while end sub

Yeah, you can’t do stuff like that on the UI thread - i.e. not in any visual component.

https://developer.roku.com/en-gb/docs/developer-program/core-concepts/threads.md

You could create a ‘Task’ node which updates its ballXPos field on an interval, and have the UI code watch that field and update the x position when it changes.

Or if you don’t want to bother with tasks, you can use a Timer node set to repeat and run your game loop code in that:

https://developer.roku.com/en-gb/docs/references/scenegraph/control-nodes/timer.md

Thank you! This works really well!

A few things about their example for others who might find this thread :
Make sure to change the “extends” thing from “Group” to “Scene”
And you can also set the timer to really low values like 0.01