Because PICO-8's Lua has no standard library, there is no way to get the length of a string, which means there is no way to (dynamically) center (an arbitrary string of) text when printing (unless I'm missing something :)

It would be nice to have either a len() function to get a string's length, or a way to ask print() to center text.

Looks like it's being considered.. (see 15)
https://www.lexaloffle.com/bbs/?pid=10718#p10718

As a workaround right now, you could store both the string and its length in a table like {s="hi", l=2}

shl(#s,16) also works.

> Looks like it's being considered..

> As a workaround right now, you could store both the string and its length in a table

Yeah that's what I ended up doing for now :p

> shl(#s,16) also works.

Oh wow, I had no idea that was possible (I didn't even know # could be used with a string, and I've been using Lua for a few years!). Thanks!

As for the bit-shifting left, why does the # operator return the whole number to the right of the decimal point anyway? Is that a bug? Is it returning a 32-bit integer instead of a 16:16 fixed point like the rest of PICO-8's numbers? I'm not sure I understand what's going on there :)

Yup, it's like you say. The original implementation of Lua returns a 64-bit floating point - as long as the value stays within 52-bit, it's identical to the integer value. For the 16:16 fixed point format, the number is 16 bits too far to the right, so the left-shift fixes that.

Note that the # operator will be fixed in 0.1.1, so the SHL work-around will break at that point!

Hooray! Good to know :)

I guess that means there's no real need for len() then...?

Right. I think the only extra string function that is vital is substr(str, offset, len).

Wow it's just #? I was really over thinking it. :o

1

I don’t think that’s correct: #txt would return only the number of characters (example 6 for "press "), so we have to multiply by the width in pixels taken by each character. This is complicated by wide characters (ex. "press 🅾️"). For my first game I am working around that with a param "extrapx" to my center/print functions, which isn’t really great but works.

8

For people finding this thread: with v0.2.2, 'print' returns the x position at the end of the string, taking into account wide characters, custom font width and control characters. This can be used to get string width in pixels by printing at x=0, y=offscreen before printing on screen!

Thank you, @merwok, just what I needed.