print( string, [x, y], [color] )
string | the string you want to print |
x | (optional) a number |
y | (optional) a number |
color | (optional) a color number (0-15) |
The print() function is used to write strings to the game screen at the (x,y) position and in the color you specify. The default position is automatically set to the next line of the current cursor position. The default color is the current draw color set by either color() or any draw function with a color argument given. The default draw color when you startup PICO-8 is #6, light gray.
For example:
print("1 hello world")
print("2 hello world",10,10)
print("3 hello world",20,20,8)
print("4 hello world",12)
These four lines of code show the different arguments you can pass to the print
function.
Line #1, we only pass the string, "1 hello world"
and PICO-8 will print that at the default position (0,0)
and default color (#6)
.
Line #2, we also pass the (x,y) coordinates of (10,10)
so it prints there and still with the default color (#6)
.
Line #3, we pass the string and the X and Y coordinates of (20,20)
and also include the color argument, setting the color to red (#8)
.
Line #4, we do something interesting and pass the string plus one more argument, which you might assume would be the X coordinate. However, PICO-8 is smart enough to accept this argument as the color, not the position! So it prints at a default position of the next line down from our last print (where the cursor left off) and in the color blue (#12)
which we specified.
Using Print's Return Values
The print
function returns 2 values, the X and Y coordinates of the bottom right pixel after the last printing.
x,y = print("hello world")
--x = 44
--y = 72
This can be useful for finding the width of the string that you want to print in order to do various things such as: animate it, center it properly, make sure it doesn't print outside of your dialog box, etc. In many of those cases, you will want to get the returned X value (essentially the width of the string) before actually printing the string to the screen, and to do that you can print your string off screen once, starting at an X position of 0 and a negative Y position.
string="hello world"
--print off screen to get width
width = print(string, 0, -10)
--print centered using width
print(string, 64-width/2, 64)
Advanced
Another use for this could be to print each character of the string independently so that you can animate the character's position or color. What is nice is that the returned X
value is the exact position you would want to print the next character.
function _draw()
cls()
local string = "hello world"
--wavy text
local x = 0
for char in all(string) do
y = 10+sin(time()-x/40)*2
x = print( char, x, y, 6 )
end
--colorful text
local x = 0
for char in all(string) do
c = 10+sin(time()-x/40)*2
x = print( char, x, 20, c )
end
end
1193
9 Aug 2024