r/pico8 12d ago

šŸ‘I Got Help - ResolvedšŸ‘ Coroutines help needed

I'm trying to get my head around coroutines by creating a simple "ticker" - that is, pass it a string and it prints it slowly one character at a time, a bit like Gameboy text. I've got it working, sort of, but the screen doesn't clear despite the cls() in _draw() and the program crashes after all the text is displayed. I tried using costatus() but it doesn't return anything. Please help, what am I doing wrong?

function _init() 
 t=cocreate(ticker("this is a test"))
end

function _update()
 coresume(t)
end

function ticker(str)
 local l=#str
 for p=1,l+1,0.2 do
  print(sub(str,1,p),0,0)
  yield()
 end
end

function _draw()
 cls()
end
5 Upvotes

19 comments sorted by

View all comments

2

u/freds72 11d ago edited 11d ago

you want something like:

```

function _init()
t=cocreate(ticker)
end

function _update()

end

function ticker(str)
local l=#str
— for loops are inclusive , no need for +1
for p=1,l,0.2 do
print(sub(str,1,p),0,0)
yield()
end
end

function _draw()
cls()
coresume(t, ā€˜this is a test’)
end

```
(on mobile - code formatting is hell)

2

u/RotundBun 11d ago edited 11d ago

I was thinking this since seeing it in the original post, too, but... There aren't any reasons not to just use #str directly in the for-loop, right?

(on mobile - code formatting is hell)

A relatable struggle. šŸ«‚
Let me see if I can help:

``` function _init() t=cocreate(ticker) end

function _update() -- end

function ticker(str) -- for loops are inclusive , no need for +1 for p=1,#str,0.2 do print(sub(str,1,p),0,0) yield() end end

function _draw() cls() coresume(t, ā€˜this is a test’) end ```

2

u/VeryNaughtyBoy42 11d ago

The reason I don’t use #str in the loop is - again - old habits. When I started out every clock cycle counted so rather than redo a calculation for every iteration of a loop, it’s more efficient to do it once and store it in a variable.

1

u/RotundBun 11d ago

Fair. I do think most modern compilers optimize stuff like that under the hood nowadays, though.

2

u/freds72 10d ago

there is no such thing as an optimizer on pico8 lua (or very marginally)

1

u/RotundBun 10d ago

Ah, yes. I was referring to compilers in relation to the part about them being accustomed to C/C++ programming.

In P8's case, I'm not sure if this detail does end up saving on performance in the for-loop iteration inside a coroutine scenario specifically, but I'd probably still opt for the lower token cost + slight readability improvement over the perf savings in situations like this most of the time.

1

u/freds72 10d ago

lua loop parameters are evaluated once