hey so i've seen a lot of carts which have a function for printing a string of text in the centre of the area on the x axis which they have depicted, and it often ends up looking something like this:
-- actual function
function cprint(txt,centre,y,c)
print(txt,centre-#txt*2,y,c)
end
-- example
function _init()
cls()
end
function _draw()
cprint("Centre:64",64,0,7)
for x=0,127,8 do
for y=16,127,8 do
line(x,0,x,127,8)
line(0,y,127,0,8)
end
end
cprint("Hello World!",64,62,7)
end |
but often one thing that they don't account for is the extra space in which the characters with an id over 127 cover. for example,
-- chr(151)
cprint("❎❎❎❎❎❎❎",64,62,7)
cprint("❎❎❎❎❎❎",64,68,7)
cprint("❎❎❎❎",64,74,7) |
in order to fix this, i first built a function which returns how many characters in the string are doubled in length,
function has_double(str) local letters=0 for i=1,#str do local char_code=ord(sub(str,i,i)) if char_code>=128 and char_code<=255 then letters+=1 end end return letters end |
then i implemented it into the "cprint" function as so
function cprint(txt,centre,y,c) for i=1,#txt do local added_letters=has_double(txt) print(text,centre-(#txt+added_letters)*2,y,c) end end |
feel free to copy
You can also print offscreen, because print returns the rightmost position of the text. If you do width = print(text, 0, -100) then you can just offset by half the width.
[Please log in to post a comment]




