recursal/Fanatic-Fandom huggingface dataset:
Backup

backup
Saves a backup of the current file to the backup folder.
PICO-8 will create a backup of your cartridge in `{appdata}/pico-8/backup` when you quit without saving or overwrite an existing file. You can also trigger a backup manually with the `backup` command.

## Examples

At the PICO-8 prompt, never having saved:

```
> backup
backed up

```

This creates a file in the backup folder named something like: `20201225_123987_untitled.p8`

And if the cart is saved first:

```
> save winterwonderland.p8
saved winterwonderland.p8
> backup
backed up winterwonderland.p8

```

This creates a file in the backup folder named something like: `20201225_124203_winterwonderland.p8`

## See also

* `load`
* `save`
* `folder`
Cstore

cstore( destaddr, sourceaddr, len, [filename] )
Store a region of memory in the cartridge file, or another cartridge file.
destaddr

The address of the first byte of the destination in the cartridge.

sourceaddr

The address of the first byte in memory to copy.

len

The length of the memory region to copy, as a number of bytes.

filename

If specified, the filename of a cartridge to which data is written. The default is to write to the currently loaded cartridge.

The `cstore()` function copies a region of memory to the cartridge, modifying the cartridge file.

This is useful for building PICO-8 development tools inside PICO-8, such as a specialized graphics editor that saves sprite or map data to another cartridge.

Data can be loaded from an arbitrary cartridge file using the reload() function.

If a filename is provided and there exists a cartridge with that name, the data is patched into the appropriate location. If there is no file with the given name, a new empty cartridge is created with the data patched in. Unlike reload(), the filename must end in `.p8` or `.p8.png` if the intended cartridge file has that extension. (The filename extension is not inferred from existing files.)

The memory layout for cartridge data is identical to PICO-8 memory for the address region 0x0000-0x4300. See Memory for an explanation of memory and cartridge data, and for a description of the memory layout.

**Caution:** The `cstore()` function modifies the cartridge file. This operation cannot be undone, so it might be wise to keep a copy of the original cartridge files, and test to make sure data is written to the correct file and memory location.

## BBS Behavior

This function is supported on the BBS:

* If called without the filename argument, it will modify the cartridge in the user's local storage - meaning it will affect the data that'll get loaded the next time the user will run your BBS cart.
* If called with the filename argument, it will write a cartridge with this name to the user's local storage. (Readable by reload() from any BBS cart)

Note that:

* When uploading an updated version of a previously-uploaded BBS cart, any cstore() calls made without the filename argument in the previous versions will not affect the new version.
* It is not possible to write to any other BBS cart with the filename argument.

## Examples

Consider a utility cartridge that generates map data and saves it to a different cartridge:

```
-- generate some map data
generate\_map()

-- save the map data to a separate cartridge
cstore(0x2000, 0x2000, 0x1000, 'mygame.p8')

```

## See also

* Memory
* `peek()`
* `poke()`
* `memcpy()`
* `reload()`
* `memset()`
The Tower of Archeos

Creator
 Genre
 Player Count

## Description

Climb the Tower of Archeos and kill the evil sorceror!

## Rules

* Attack a group of the same kind of monsters!
* Monsters will retaliate, but group size does not affect final damage, so try to destroy large groups first.
* When your XP reaches 0, your health and items are refilled, and you also gain another heart slot.
* Blocked doors and chests can be opened by killing monsters that are next to it.
* To go up a floor, you need to go through a door.
* Reach the 8th level to fight Archeon, the evil sorceror!

## Controls

* Use the Up/Down/Left/Right to move the Cursor.
* Use the Z button to attack/go through doors/grab items.
* Use the X Button to enter or leave your inventory.
Peek4

peek4( addr, [n] )
Reads one or more 32-bit fixed-point number values from contiguous groups of four consecutive memory locations.
addr

The address of the first memory location.

n

The number of values to return. (1 by default, 32767 max.)
The `peek4()` function reads and returns 32-bit values from groups of four consecutive bytes in the addressable memory region (0x0000-0x7fff). The value is interpreted in the Little Endian representation, which stores the lowest 8 bits of the fractional part in the first byte, and the lowest 8 bits of the integer part in the third byte.

See Memory for information about the memory layout.

## $ operator

The unary-`$` operator added in 0.2.0 performs the same function as `peek4(address)` and is now the recommended way to read one 32-bit word of memory at a time, as it uses fewer tokens, costs fewer cycles at runtime, and runs on the real host CPU much more efficiently. Simply replace `peek4(address)` with `$address`.

## Examples

```
poke(0x4300, 0x00, 0xc0, 0xff, 0x0f)

b = peek4(0x4300)  -- 0x0fff.c000, or 4095.75 in decimal

b = $0x4300        -- preferred method

```

## See also

* Memory
* `peek()`
* `peek2()`
* `poke()`
* `poke2()`
* `poke4()`
* `memcpy()`
* `reload()`
* `cstore()`
* `memset()`
Unpack

unpack( tbl, [i,] [j] )
Returns the elements from the given table.
tbl

The table to unpack.

i

First index to unpack. Default is 1.

j

Last index to unpack. Default is `#tbl`.

Returns the elements from the given table as a tuple.

Conceptually, the inside of a call to `unpack(tbl,i,j)` would look like this:

```
return tbl[i], tbl[i+1], ···, tbl[j]

```

## Examples

This call can be useful for passing arguments to functions that are called later and/or in other parts of the program. This example has the update stage telling the draw stage to print "hello" at 64,64 in color 14 (pink):

```
function \_update()
  message = {"hello", 64, 64, 14}
end

function \_draw()
  cls()
  print(unpack(message))
end

```

 See also

* `pack()`
Не удалось оформить заказ

## Не удалось оформить заказ из-за высокого уровня риска

Иногда при попытке приобрести что-то на Google Play и оплатить посредством Google Wallet пользователи сталкиваются с проблемой отклонения заказа. На экране устройства появляется сообщение примерно следующего содержания: «Не удалось оформить заказ из за высокого уровня риска». Это сообщение генерируется автоматически и является результатом работы системы обнаружения мошенничества, используемой сервисами Google (в том числе маркетом Google Play и платежным сервисом Wallet).

Наиболее часто защита срабатывает в том случае, когда клиент пользуется для оформления заказов устройствами, работающими под управлением разных ОС — Android и Windows. Платеж не проходит, и возможность совершить его может быть заблокирована на срок, который может составить от 30 минут до 7 дней, если, конечно, не решить проблему самостоятельно и не исправить ошибку. К счастью, целый ряд причин не может являться серьезным поводом для беспокойства и легко устраняется.

Сообщение «Не удалось оформить заказ из за высокого уровня риска» может быть вызвано любыми изменениями, внесенными вами в стандартную процедуру оформления заказа, или неверно введенной информацией. Наиболее частые причины ошибки:

* Недостаток средств;
* Случайный сбой в работе PayPal;
* Использование виртуальной кредитной карты (может не приниматься к оплате на Google Play \*Маркет в данный момент времени);
* Устаревшие данные кредитной карты;
* Неверная информация о карте;
* Неверный код безопасности (или CVC);
* Несовпадение введенной вами информации с банковскими реквизитами (некорректный номер счета);
* Отклонения от стандартной процедуры покупки.

Методы исправления ошибки «Ваш заказ отклонен...»:

* *Обновление учетной записи Google* (изменить пароль, заново ввести всю информацию, включая Gmail и Google+).
* *Обновление способа оплаты*: удалить ранее выбранный способ и относящиеся к нему данные, заново выбрать метод оплаты, при использовании кредитной карты корректно ввести ее номер (без тире и пробелов), срок действия карты (убедиться, что он еще не истёк), внимательно ввести правильный код или CVC.
* *Корректировка информации*: Проверьте и исправьте в случае необходимости платежные реквизиты, в частности, для выставления счетов, в своем аккаунте Google Wallet и у кредитной карты.
* *Техподдержка*: свяжитесь со специалистами Google по тел. 855-492-5538, чтобы получить помощь в решении проблемы.

Как обновить информацию на Android-устройстве:

* Чтобы обновить информацию на Android-смартфоне или планшете, кликните на стоимость покупки и перейдите в раздел выбора вариантов оплаты.

В соответствующие окна на странице настроек вбейте данные кредитной карты, платежный код или данные аккаунта PayPal.

* Учтите, что если вы уже использовали для покупок сервис PayPal, удалить данные и ввести их заново на Android-устройстве не удастся — это нужно будет сделать с помощью компьютера.

Источник
NULL

Creator
 Genre
 Player Count

## Description

A "surreal adventure game" (along with being a puzzle game) comprised of five areas. Each area has a different, unspecified goal that must be accomplished before the player can be transported to the next area.

## Rules

* Wander around each area. Try to find and read all newspapers.
* A black creature can be triggered in every area. Interact with it every single time in order to see a different ending (along with reading all newspapers).
* In the first area (The Station), locate and activate several switches to unlock more places in the level. Find the ticket and board a train to be transported to the next area.
* In The Open (the next area), there are clues to follow to be teleported to The Rift.
* In The Rift, you must make it to the next teleport at the end of the playfield. Correct timing is needed in order to avoid several traps that will transport you back to the beginning of the area.
* In The Grove, you must activate several areas by standing on them for several seconds each in order to be transported to The Remains.
* In The Remains, you must collect all blue blobs in the area, which will open a door in a building at the top middle area of the level, which will end the game once you enter the building.

## Controls

* At the title screen, press z or x to start the game.
* Use the arrow keys to move.
* Use the x, z or c keys to interact with various items/read newspapers and to speed up onscreen dialog.
* Use the enter or p key to pause the game or reset the cart.
Dget

dget( index )
Gets a value from persistent cartridge data.
index

The index of the value, 0 to 63.

A cartridge can store 64 numbers (256 bytes) of data to persistent storage. This data is available the next time the user runs the cart, and persists in the player even if the cartridge is replaced with a new version of the same cartridge.

The `dget()` function retrieves the value for the given index (0 to 63).

## See also

* `cartdata()`
* `dset()`
Ovalfill

ovalfill( x0, y0, x1, y1, [col] )
Draws a filled oval shape.
x0

The x coordinate of the upper left corner.

y0

The y coordinate of the upper left corner.

x1

The x coordinate of the lower right corner.

y1

The y coordinate of the lower right corner.

col

The color of the oval. If omitted, the color from the draw state is used.

## Examples

```
-- draw a filled red oval of a wider shape
cls(0)
function \_draw()
  ovalfill(10,30,100,100,8)
end

```

## See also

* Graphics
* Draw state
* `oval()`
* `circ()`
* `circfill()`
Cls

cls( [color] )
Clears the graphics buffer.
color

A color to use for the background. The default is 0 (black).

The `cls()` function clears the graphics buffer. By default this means setting every pixel to color index 0, which is black by default. Optionally, a different color index may be provided to clear the screen to that color.

The clip rectangle is automatically reset to (0, 0, 128, 128) before the clear is performed, so it is only possible to use `cls()` to clear the entire screen. To clear sub-rectangles of the screen, use `rectfill()` instead.

Additionally, the cursor position in the draw state is set to (0, 0).

The color index written is always exactly as given, rather than being remapped via the `pal()` feature. For instance, `pal(8, 12) cls(8)` fills the screen with 8 (red), not 12 (blue).

It is common (though not required) to call `cls()` at the beginning of the `_draw()` function as part of the game loop.

## Examples

```
function \_init()
  x = 0
end

function \_update()
  -- add 1 to x. if x > 128, wrap it to 0.
  x = (x + 1) % 128
end

function \_draw()
  cls()
  circfill(x, x, 10, 8)
end

```

Try removing the `cls()` call from this example.

## See also

* Graphics
* Draw state
* `cursor()`
* `rectfill()`
Yield

yield( [...] )
Yields control back to the caller from within a coroutine.
...

Arguments to be passed to the `coresume()` that resumed its coroutine.

A coroutine is a special kind of function that can yield control back to the caller without completely exiting. The caller can then resume the coroutine as many times as needed until the function exits.

The coroutine calls `yield()` to suspend the coroutine and return control back to the caller in this way. As of PICO-8 v0.2.4b, it can accept a single option value to return from `coresume()` , although this is currently undocumented and may be dangerous to rely upon.

`yield()` returns all extra arguments passed to the `coresume()` that resumed its coroutine.

To terminate the coroutine, the function returns with the `return` statement. After this point, the coroutine is considered dead and cannot be resumed.

## Examples

See `cocreate()` and `coresume()` for examples.

## See also

* `cocreate()`
* `coresume()`
* `costatus()`
Fget

fget( n, [f] )
Gets the value of a flag of a sprite.
n

The sprite number.

f

The flag index (0-7). If omitted, a bit field of all flags is returned.

Each sprite has eight flags that can be set in the sprite editor or by the fset() function. You can use these flags for any purpose. One possible purpose is to define "layers" of map tiles, which modifies the behavior of the map() function.

Flags are numbered from 0 to 7, appearing left to right in the sprite editor.

When `fget()` is called without a flag index, it returns a number that represents all of the flags. This is a bit field where flag 0 is the "least significant" bit: flag 0 (leftmost) has a value of 1, flag 1 has a value of 2, flag 2 has a value of 4, and so on, up to flag 7 with a value of 128.

## Examples

Given a sprite with flags 0, 1, and 7 set:

```
first = fget(16, 0)   -- true
second = fget(16, 1)  -- true
third = fget(16, 2)   -- false
eighth = fget(16, 7)  -- true

flags = fget(16)      -- 131 (1 + 2 + 128)

```

## See also

* Graphics
* `fset()`
* `map()`
CommandReference

A command is an action you can perform in PICO-8 by typing it at the command prompt. Commands are used to load and save cartridges, manage files, and launch the Splore cartridge explorer.

## Executing commands

Unlike functions, you do not use parentheses after the command name. For commands that take arguments, you type each argument after the command separated by spaces. String arguments such as filenames are not surrounded by quote marks.

```
> load jelpi.p8

```

Almost all commands can be called by source code as functions, but some do not work in code, such as most file operations. The ones that do work use parentheses around the argument list, quotes around string arguments, and commas between arguments. Most commands don't do anything useful when called from code.

```
-- load a new cart, overwriting this one
load('jelpi.p8')
-- list /carts/ directory and save a table of results to a variable
dir=ls("")

```

## Help and information

* `help`
* `info`
* `install\_demos`
* `splore`

## Files and folders

* `backup`
* `cd [dirpath]`
* `dir`
* `export filename`
* `folder`
* `import filename`
* `load filename`
* `ls`
* `mkdir dirname`
* `save [filename]`

## Running and quitting

* `reboot`
* `reset` (undocumented)
* `resume`
* `run`
* `shutdown`

## Configuration

* `config`
* `keyconfig`

## See also

* APIReference
* Category:Command
Astero

Creator
 Genre
 Player Count

## Description

Scrolling space shooter where the player must destroy as many ships as possible while avoiding their fire and collecting power-ups.

## Rules

* Each enemy has a certain attack pattern and weapon, as Sentries travel straight down vertically but fire one shot to each side at about a 45 degree angle. Wardens only fire one vertical shot at a time but they move diagonally. Jackals quickly move horizontally while firing up to two Missiles that rapidly travel downwards and Alphas move slowly horizontally, but then stop and fire a powerful laser for a few seconds.
* Occasionally a destroyed enemy will release a power-up, which includes a Fan, which will enable the player’s shots to fire in three directions: at about a 45 degree angle from each side and straight forward. The Tri shot will enable the player’s ship to fire forward and left and right all at once. The Double shot fires two shots at once and the Laser will fire a continuous powerful beam. All power-ups only last a few seconds after being collected.
* Colliding with any enemy ship or its weapon will cause the player to lose a ship and the game will end when there are no more remaining ships. The player will also lose a power-up’s ability if they are in possession of one when they lose a ship.
* The game will also end if the player beats all six levels.

## Controls

* At the title screen, press the x or z keys to play the game.
* Use the arrow keys to move.
* Use the z or x keys to fire.
* Use the enter or p keys to pause the game and/or reset the cart.
Memset

memset( destaddr, val, len )
Writes a byte value to every address in a region of memory.
destaddr

The address of the first memory location to write.

val

The byte value to write.

len

The length of the region of memory to write, as a number of bytes.

The `memset()` function is a fast way to fill a region of memory with one byte value.

## Examples

```
-- clear all user data, 0x4300-0x5dff
memset(0x4300, 0, 0x1b00)

-- fill the screen with white
-- (equivalent to rectfill(0,0,128,128,7))
memset(0x6000, 0x77, 0x2000)

```

## See also

* Memory
* `peek()`
* `poke()`
* `memcpy()`
* `reload()`
* `cstore()`
Install demos

install\_demos
Installs the PICO-8 demo cartridges.
This command creates a `demos/` subdirectory in the cartridge storage area containing a collection of demonstration cartridges.

After these are created, you can use `splore` or the `load` command to explore these carts.

## Examples

```
> install_demos

```

## See also

* `splore`
* `cd`
* `load`
Poke4

poke4( addr, [...] )
Writes one or more 32-bit fixed-point PICO-8 number values to contiguous groups of four consecutive memory locations.
addr

The address of the first memory location.

...

The 32-bit values to write to memory. If these are omitted, a zero is written to the first 4 bytes.

The `poke4()` function writes one or more 32-bit values to contiguous groups of four consecutive bytes in the addressable memory region (0x0000-0x7fff). The values are interpreted in the Little Endian representation, which stores the lowest 8 bits of the fractional part in the first byte, and the lowest 8 bits of the integer part in the third byte.

See Memory for information about the memory layout.

## Examples

```
poke4(0x4300, 0x0fff.c000)

b0,b1,b2,b3 = peek(0x4300, 4)  -- 0x00,0xc0,0xff,0x0f
w0,w1       = peek2(0x4300, 2) -- 0xc000,0x0fff

```

## See also

* Memory
* `peek()`
* `peek2()`
* `peek4()`
* `poke()`
* `poke2()`
* `memcpy()`
* `reload()`
* `cstore()`
* `memset()`
Mkdir

mkdir path
Creates a new directory.
path

The path to the new directory.

PICO-8's cartridge storage uses a hierarchical filesystem of directories that corresponds to that of the host operating system. The `mkdir` command makes a new directory that can contain files and other directories.

The path can be a *relative path* from the current working directory or an *absolute path* from the root of the storage area. The last part of the path is the name of the new directory. The name must not already exist (as a directory or a file), and the rest of the path must be to a directory that exists. See `cd`.

**Caution:** As of 0.1.6, the `mkdir` command does not report an error when the directory could not be created. Use the `ls` command to confirm that the directory was created successfully.

**Note:** There is no way to delete or rename a directory from the PICO-8 command prompt. If you're organizing your files, it's easier to use the `folder` command to open your operating system's file browser.

## Examples

```
> cd /
> mkdir projects

> cd projects
> mkdir squashy

> cd /
> mkdir projects/squashy

```

## See also

* `cd`
* `folder`
* `ls`
Asteroids

Creator
 Genre
 Player Count

## Description

Shoot as many asteroids as possible while avoiding being destroyed by them.

## Rules

* Shoot asteroids! Shooting a large one will split into two medium-sized ones, shooting a medium asteroid will split into two small ones, then shooting a small asteroid will destroy it.
* Being hit by an asteroid will cost the player a ship and the game will end when there are no more ships left in reserve.
* An extra ship is awarded at 5000 points.
* Along with turning, the player can also thrust their ship around the screen to avoid asteroids.

## Controls

* Use any key (Z, X and arrow keys) to start a game.
* Use the left/right arrow keys to turn ship and the up arrow key to thrust.
* Use the Z button to shoot.
* Use the Escape or Enter keys to pause the game.
CheatSheet

The PICO-8 cheat sheet is an interactive web page summary of the PICO-8 API and features intended as a quick reference for PICO-8 developers. It was created and is maintained by Neko250, with contributions from the community.

* Link: http://neko250.github.io/pico8-api/
* Discussion: http://www.lexaloffle.com/bbs/?tid=2687
Multiple States System

## Description

Ever wanted a Title Screen or a Menu?

This guide can show you how to manage multiple states at the same time!

*Note:* For examplatory purposes, we'll be using the prefixes "game" and "title" for this tutorial.

## Instructions

###

### Initializing

The function "\_init()" is what happens when the game is started up (or in this case, the State).

```
function \_init()
  titleinit() -- does title things.
end

function titleinit()
  mode = 0
  --whatever you wish to do when the title starts up.
end

function gameinit()
  mode = 1
  --what to do at the start of the play session.
end

```

We'll call on gameinit() later.

### Updating

The function "\_update()" is where gameplay elements are changed (like a timer).

```
function \_update()
  if (mode == 0) then --Title Screen mode
    titleupdate()
  else
    gameupdate()
  end
end

function titleupdate()
  --Example "Press Z to start"
  --if btn(4,0) then
  -- gameinit()
  --end
end

function gameupdate()
  --gameplay elements (or whatever used to be in \_update) goes here.
end

```

The example given can be used by simply getting rid of the dashes (or rather uncommenting it).

### Drawing

The function "\_draw()" is called to draw things to the screen. (There's some repetition in this one.)

```
function \_draw()
  if (mode == 0) then --Tit
    titledraw()
  else
    gamedraw()
  end
end

function titledraw()
  --Example "Title"
  --print("Super Cool Game")
end

function gamedraw()
  --the screen drawing mechanisms(or whatever used to be in \_draw) goes here.
end

```

## Notes

- If you want to add more to "\_draw" or "\_update", simply follow this guideline:

```
else if (mode == 2) then
    --optiondraw() or optionupdate()

```

just be sure to put that before the else statement!
Palt

palt( [col,] [t] )
Change the transparency of a color in the draw state for subsequent draw calls.
col

The number of the color to modify.

t

If `true`, treat this color as transparent. If `false`, treat this color as opaque.

When the `spr()`, `sspr()`, and `map()` functions copy sprite pixels onto the screen, some colors are considered *transparent* and are not drawn. By default, color 0 (black) is transparent, so when a sprite's pixel is this color and the sprite is drawn on top of an existing image, that pixel preserves the color underneath.

The `palt()` function changes the transparency of a given color.

If called with only one argument, the transparency settings of all colors are specified simultaneously using a single 16-bit field, with set bits specifying transparent, and cleared bits specifying opaque. Bit 0 (value 1) is for color 15, bit 1 (value 2) for color 14, and so on, down to color 0.

If called without arguments, `palt()` resets the transparency for all colors. The `pal()` function called without arguments also resets transparency, though the opposite is not true and `palt()` will not reset colors.

## Examples

```
-- draw black pixels
palt(0, false)

-- don't draw red pixels
palt(8, true)

-- draw anything but black, orange, and yellow pixels
palt(0b1000000001100000)

-- reset transparency
palt()

-- pal() also resets transparency when it resets colors
pal()

```

## See also

* Draw state
* Graphics
* Palette
* `color()`
* `pal()`
Sub

sub( str, start, [end] )
Gets the substring of a string.
str

The string.

start

The starting index, counting from 1 at the left, or -1 at the right.

end

The ending index, counting from 1 at the left, or -1 at the right. (default -1)

The start and end indices are inclusive, which is to say the characters at both indices will be included in the result.

In Lua, strings may contain any number of characters within them. The expression `""` represents a string of `0` length. Lua doesn't actually expose a "character" type, but strings with a length of `1` are typically *called* characters. Whether extracting characters or substrings, the `sub()` function is the way to obtain *portions* of a string.

Single characters can be extracted from a string by passing the same index for both start and end, e.g. `sub(s,i,i)`. As mentioned, the result is still a string, just with a length of 1.

As of v0.2.5, the recommended way to extract single characters is `s[i]`.

Additionally, negative indices can be very useful. They work exactly like positive indices, but index from the end of the string *backwards*. For instance:

```
> s="something"
> print(sub(s,-5))     -- get the string from the 5th-to-last char onwards
thing
> print(sub(s,-4,-3))  -- print "hi" since we know s ends with "thing"
hi
> print(sub(s,-2,nil)) -- print the last two characters
ng

```

## Notes

PICO-8 adds the ability to represent characters as their *ordinal* value, a whole number in the range 0..255. There are two calls that can convert back and forth between the two representations:

* To convert an ordinal number n to its single-character string counterpart, use `chr(n)`.

* To convert a single-character string c to its ordinal number counterpart, use `ord(c)`.

* To convert a single character at index i in a longer string s to its ordinal number, use `ord(s, i)`.

## Examples

```
print(sub("hello there", 1, 5))    -- hello
print(sub("hello there", -5))      -- there
print(sub("hello there", 7, 7))    -- t
print(sub("hello there", 7, nil))  -- t

```

## See also

* Lua
* `ord()`
* `chr()`
Export

export filename
Exports the cartridge in various forms.
filename

The filename to export, ending in `.html`, `.png`, `.bin`, or `.wav`.
The `export` command serves several functions. It can be used to produce a standalone version of the cartridge that can be added to a website and played in a browser. It can also be used to generate a PNG image of the sprite sheet, or a WAV audio file of the sound effects or music.

Exported files are created in the current working directory of the cartridge storage area. You can use the `folder` command to access this area with your operating system's file browser.

## Exporting a web player

```
> export mygame.html

```

To export the cartridge so it can be embedded in a website, use a filename that ends in `.html`. PICO-8 generates two files: an HTML file with this name, and a JavaScript file with a similar name and a `.js` extension.

The HTML file contains the code that adds the cart to the page along with control features. You can include this code in your website and modify it as needed.

The JS file contains the cartridge data and a standalone PICO-8 player that runs in a web browser. This file is referenced by the HTML file, and should not be changed.

## Exporting a desktop app

```
> export mygame.bin

```

To export the cartridge so it can be downloaded and played on Windows, Linux (64-bit), and macOS computers, use the `.bin` filename extension.

This creates a folder named `mygame.bin` containing a `windows/` subdirectory with the Windows files, a `linux/` subdirectory with the Linux files, and the `mygame.app` macOS bundle.

These are standalone versions of the game and do not require PICO-8 to play.

## Exporting the sprite sheet

```
> export mygame_sprites.png

```

To export the sprite sheet as a PNG file, use a filename that ends in `.png`. The image is 128 pixels wide and 128 pixels high, and uses the PICO-8 palette.

This file is suitable for importing into another cartridge with the `import` command.

*Note:* If the cartridge uses the bottom half of the sprite sheet for map data, this data will be included in the exported image. See Graphics.

## Exporting sound effects

```
> export mygame_sfx.wav

> export mygame_sfx_%d.wav

```

To export the sound effects as WAV audio files, use a filename that ends in `.wav`.

The audio file contains each of the sound effects, one after another. To export each sound effect as a separate audio file, include `%d` somewhere in the filename, e.g. `mygame_sfx_%d.wav`. This will be replaced by the number of the sound effect (`mygame_sfx_01.wav`).

There is no way to import sound effects.

## Exporting music

```
> export mygame_music.wav

> export mygame_music_%d.wav

```

To export the music tracks as WAV audio files, make sure the music tab is open in the PICO-8 editor, press ESC, and then type the export command using a filename that ends in `.wav`.

## Examples

```
> export mygame.html

> export mygame_sprites.png

> export mygame_sfx.wav

```

## See also

* Graphics
* Sound
* `import`
* `save`
Fset

fset( n, [f,] v )
Sets the value of a flag of a sprite.
n

The sprite number.

f

The flag index (0-7). If omitted, a bit field of all flags is returned.

v

The value, either `true` or `false` if the flag index is specified, or the bit field of all flags if it is not.

Each sprite has eight flags that can be set in the sprite editor or by the **fset()** function. You can use these flags for any purpose. One possible purpose is to define "layers" of map tiles, which modifies the behavior of the map() function.

To set a specific flag, specify the flag index as the second argument, and either `true` or `false` as the value. Flags are numbered from 0 to 7, appearing left to right in the sprite editor.

When `fset()` is called without a flag index, it accepts a number that represents all of the flags. This is a bit field where flag 0 is the "least significant" bit: flag 0 (leftmost) has a value of 1, flag 1 has a value of 2, flag 2 has a value of 4, and so on, up to flag 7 with a value of 128.

Setting a flag changes the data in memory, but does not change the cartridge. A program can restore the original data from the cartridge with reload(), and can save the modified data to the cart with cstore(). See Memory for information about the memory addresses to use.

## Examples

```
-- Set flag 0 (leftmost) of sprite 16.
fset(16, 0, true)

-- Clear flag 7 (rightmost) of sprite 16.
fset(16, 7, false)

-- Set flags 0, 1, and 7 of sprite 16.
fset(16, 131)  -- 131 = 1 + 2 + 128

```

## See also

* Graphics
* `fget()`
* `map()`
Setmetatable

setmetatable( tbl, metatbl )
Updates the metatable for a table.
tbl

The table whose metatable to modify.

metatbl

The new metatable.

*return-value*

The same tbl that was passed in.
In Lua, tables are general purpose objects that contain values and can be manipulated with operators. The default behaviors of operators on a table value are stored in its *metatable*, using keys such as `__index` that refer to functions that perform the operator's task.

The `setmetatable()` function updates the metatable for a table, allowing you to customize the built-in operations. This has several useful applications for creating custom value types in Lua. For example, you can:

* Define a vector data type that supports arithmetic operators for addition and subtraction
* Set comparison operators on a new value type to use it with a generic sorting routine, such as sorting displayable objects by their display depth
* Implement inheritance: construct objects (tables) that refer to another table as a *prototype* (or class) by setting the `__index` operator to access the prototype's properties

PICO-8 supports overwriting the `__tostring` metamethod. Tables can now be concatenated with strings, or printed directly.

PICO-8 includes Lua's `rawget()`, `rawset()`, `rawlen()`, and `rawequal()` functions, which ignore custom `__index`, `__newindex`, `__len`, and `__eq` metamethods, respectively.

Note: The return value is just the input, `tbl`, given back to you, which can be convenient in pseudo-constructors. See `pixel:new()` in the example below for a demonstration.

## Metamethods

A summary of the lua metamethods, as they pertain to pico-8.

## Examples

```
-- default attribute values for a "pixel" class
pixel = {
  x = 0,
  y = 0,
  c = 7
}
pixel.\_\_index=pixel

-- the pixel class constructor
function pixel:new(o)
  return setmetatable(o or {}, self)
end

-- using the pixel class
p1 = pixel:new()
print(p1.x)   -- 0
print(p1.y)   -- 0
print(p1.c)   -- 7

-- use an instance of pixel to subclass it
-- (prototypical inheritance)
newpixel = pixel:new({y=100})

p2 = newpixel:new()
print(p2.x)   -- 0
print(p2.y)   -- 100

```

## External samples & references

The Lua documentation on metatables includes an example of implementing a set container type, using metamethods to implement set unions and intersections with the `+` and `*` operators.

The Lua documentation on objects demonstrates how to use the `__index` metamethod to implement inheritance.

On the PICO-8 forums, user **geckojsc** posted a metatable tutorial demonstrating adding and subtracting vector values.

## See also

* `getmetatable()`
* `rawset()`
* `rawget()`
* `rawlen()`
* `rawequal()`
* Metatables
* Tables
* Lua
Folder

folder
Opens the PICO-8 cartridge folder in the host operating system.
When you execute this system command at the PICO-8 prompt, your operating system's file browser opens a window showing the files and folders in the cartridge storage area. You can copy files in and out of this area to make them available to PICO-8.

## Examples

At the PICO-8 prompt:

```
> folder

```

## See also

* `load`
* `save`
* `ls`
Rotl

Superseded / Deprecated
The feature described in this article has been superseded by a newer feature. This feature still works in PICO-8, but the new feature should be used instead. See the article's "Superseded by..." section for specific details.

rotl( num, bits )
Rotates the bits of a number to the left.
num

The number.

bits

The number of bits to rotate.

The `rotl()` function takes a number and a bit count, and returns the result of rotating the bits of the number to the left by that count.

Numbers in PICO-8 are stored using a 32-bit *fixed point* format, with 16 bits for the integer portion, 16 bits for the fractional portion, and a two's complement representation for negative and positive values. Bit rotating uses the entire number representation. (See examples below.)

See `rotr()` to rotate bits to the right.

## Superseded by <<> operator

The `<<>` operator added in 0.2.0 performs the same function as `rotl()` and is now the recommended way to rotate bits left, as it uses fewer tokens, costs fewer cycles at runtime, and runs on the real host CPU much more efficiently. Simply replace `rotl(a,b)` with `a<<>b`.

## Examples

```
-- 8 = 0b00001000 binary
-- 64 = 0b01000000 binary
print(rotl(8, 3))      -- 64

-- 0.125 = 0b0000.0010 binary
-- 1.000 = 0b0001.0000 binary
print(rotl(0.125, 3))  -- 1

-- -4096.0000 = 0b1111000000000000.0000000000000000 binary (two's complement)
-- rotate <-- by 12 bits
-- 0.0586 = 0b0000000000000000.0000111100000000 binary
print(rotl(-4096,12))  -- 0.0586

print(8 <<> 3)         -- 64, preferred method

```

## See also

* Math
* `band()`
* `bor()`
* `bxor()`
* `bnot()`
* `shl()`
* `shr()`
* `lshr()`
* `rotr()`
Pakutto BOY

Creator
 Genre
 Player Count

## Description

In this maze game, the player must eat all foods (while avoiding ghosts) in each round in order to advance to the next one.

## Rules

* The food in each maze moves, which Pakutto BOY must chase after in order to consume.
* Ghosts chase BOY and if one of them catches him then a life will be lost. The game will end when there are no more BOYs left in reserve, although extra BOYs are awarded at 2000 and 5000 points.
* With each new maze, life, and with each time BOY eats a piece of food, they will be able to briefly eat a ghost, which will take it out of play for several seconds. After several rounds, however, the effect will become shorter until it does not even work at all after eating a piece of food.
* Ghosts and/or food will speed up as more rounds are cleared.

## Controls

* At the title screen, press the x or z keys to play the game.
* Use the arrow keys to move.
* Use the enter or p keys to pause the game and/or reset the cart.
I'm Not Santa!

Creator
 Genre
 Player Count

## Description

The player controls a "shitty wizard" who just wants to drink his coffee in peace, but children mistake him for Santa and won't leave him alone!

## Rules

* If left idle for a few seconds at a time without moving, the wizard will rack up points by drinking his coffee.
* Children start appearing and making their way towards the wizard; if any of them make contact with him, the game will end.
* The wizard can shoot and temporarily stun children by turning them into snowmen, which will start cluttering up the playfield with the more children he shoots.

## Controls

* Click on the play icon to start a game.
* Use the arrow keys to move the wizard.
* Use the Z key to shoot.
* Use the escape or Enter key to pause the game.
Time

time( )
Returns the amount of time since PICO-8 was last started, as a (fractional) number of seconds.
The `time()` function returns the (fractional) number of seconds since PICO-8 was started.

Calling `time()` multiple times in the same frame will always return the same result.

## Technical notes

PICO-8's number type has an upper limit of 32767.9999 before it wraps back to -32768. This means the values from `time()` may become problematic after roughly 9 hours and 6 minutes. An app that needs to track elapsed times of significant duration would be wise to track time as a series of delta-times, accumulating them into a representation capable of tracking longer periods.

Time may also be measured in several different ways, and at high resolution, through the system stats. See the `stat()` function for details.

As of v0.2.4b, carts with a Game Loop will only see `time()` update when their Game Loop loops - it won't update if they call `flip()` manually.

There is a semi-documented alias to the `time()` function in the form of `t()`. This may be useful for carts that are tight on source code space, most notably Tweetcarts.

## Examples

```
function \_init()
  last = time()
end

function \_update()
  -- (empty update to use game loop)
end

function \_draw()
  cls()
  if (time() - last) > 10 then
    print("time's up!", 44, 60, 7)
  end
end

```

## See Also

* `stat()`
* `t()`
Cocreate

cocreate( func )
Creates a coroutine from a function.
func

The function for the coroutine to run.

*return-value*

A new coroutine.
A coroutine is a special kind of function that can yield control back to the caller without completely exiting. The caller can then resume the coroutine as many times as needed until the function exits.

To create a coroutine, call `cocreate()` with a function. This function is expected to take no arguments, to return no value, and to call `yield()` to temporarily return control to the caller. `cocreate()` returns the coroutine that can be used to control execution of the function.

`cocreate()` does not call the coroutine function. Instead, the caller is expected to call `coresume()` with the coroutine to start or resume execution of the function.

The coroutine function calls `yield()` to suspend execution and return control to the caller of `coresume()`. The function can also call another function that calls `yield()`, and the entire call stack will be preserved. The coroutine function continues from where it left off the next time you call `coresume()` with the coroutine.

If the coroutine function returns instead of yields (such as by allowing control to reach the end of the function body, or by using `return`), the coroutine dies and cannot be revived by `coresume()`. You can test the status of a coroutine object by calling the `costatus()` function.

Coroutines are useful for preserving the state of a function in progress for later continuation. It is a way to preserve state, and is well suited to pausing and resuming a sequence of actions that terminates. This works especially well with the PICO-8 game loop as a way to initiate an action that takes place over multiple frames.

**Caution:** As of PICO-8 v0.1.10, if a runtime error occurs inside a coroutine function, the function aborts, but instead of stopping the program and printing an error message, the coroutine dies and execution continues. This can make debugging coroutines difficult, as many common errors (such as incorrect nil values) manifest as runtime errors.

## Examples

The following example uses a coroutine to animate a circle moving across the screen. The animation is initiated by pressing button 5.

```
x=4
y=4
cor = nil

function anim()
  for i=4,124,4 do
    x=i
    y=i
    yield()
  end
end

function \_update()
  if btnp(5) then
    cor = cocreate(anim)
  end
  if cor and costatus(cor) != 'dead' then
    coresume(cor)
  else
    cor = nil
  end
end

function \_draw()
  cls()
  circfill(x, y, 4, 7)
end

```

## See also

* `coresume()`
* `costatus()`
* `trace()`
* `yield()`
* Cutscenes and Coroutines, an article by dddaaannn
Ord

ord( str, [index,] [count] )
Gets the ordinal (numeric) versions of an arbitrary number of characters in a string.
str

The string whose character(s) are to be converted to ordinal(s).

index

The index of the character in the string. Default is 1, the first character.

count

The number of characters to read from the string. Default is 1.

*return-values*

The ordinal value(s) of the count character(s) at index in str, as a tuple.
This function permits conversion of an arbitrary number of characters in a string to the ordinal(s) corresponding to them, which in turn can be converted back to the original characters with `chr()`.

If the string passed in is missing or empty, or the index is outside of the extents of the string, `nil` will be returned.

Typically this would be called with a single-character string, to convert that character to an ordinal:

```
> print(ord("h"))
104
> print(chr(104))
h

```

However, the optional index and count parameters (which default to 1) may be used to return multiple characters' ordinals from a longer string:

```
> print(ord("hi!"))
104
> print(ord("hi!", 2))
105
> print(ord("hi!", 3))
33
> print(chr(104)..chr(105)..chr(33))
hi!
> a, b, c = ord("hi!", 1, 3) -- returns 104, 105, 33
> print(b)
105
> print(chr(b))
i
> print(chr(a, b, c))
hi!

```

This allows a string to be easily and rapidly converted to the list of ordinals that represent it. These ordinals may be manipulated and then possibly converted back to a string, saved to memory, or placed in save data.

## Examples

This implements writing a length-prefixed "Pascal" string to memory:

```
-- write a string to memory, in pascal format:
-- bytes 0,1: 16-bit length
-- bytes 2->: character ordinals
function pokestr(mem\_addr, str, max\_len)
  -- limit its length to avoid buffer overruns
  local len = min(#str, max\_len)
  -- write the 16-bit length to the first 2 bytes
  poke2(mem\_addr, len)
  -- followed by that many character ordinals as bytes
  poke(mem\_addr + 2, ord(str, 1, len))
end

```

See `chr()` for the complementary `peekstr()` code example.

## Technical notes

* If the str argument is a *number*, it will be converted internally to a string. This means that both `ord(789, 2)` and `ord("789", 2)` will return the same value, 56, which is the ordinal for the second digit's character, '8'.

* Types other than numbers are *not* converted to strings. Instead, `ord()` will return nothing. Usually this is converted to a `nil`, but inspecting the value may produce different results, possibly a Runtime Error.

* `ord()` is similar to `string.byte()` in native Lua, but that version doesn't take a third argument for an end of range, only an index.

## See also

* `chr()`
* `poke()`
* `sub()`
PicoLove

PicoLove is a third-party implementation of the PICO-8 runtime environment based on Lua and the Löve game engine. PicoLove can be used to run PICO-8 games on platforms not currently supported by PICO-8 or the PICO-8 web player, such as mobile devices.

PicoLove was created by impbox, and has been forked and extended by gamax92.

* impbox original on Github: https://github.com/picolove/picolove
* gamax92 fork on Github: https://github.com/gamax92/picolove
* Discussion: http://www.lexaloffle.com/bbs/?tid=2444
CoinAge

Creator
 Genre
 Player Count

## Description

Collect as many coins as possible while avoiding enemies!

## Rules

* The player must collect as many coins as possible. Once a coin is collected, another one will instantly appear elsewhere in the maze. Two coins appear onscreen maximum.
* An enemy appears in the pen in the center of the screen; after several seconds, it will enter the maze. After a while, another one will appear in the pen and also enter the maze until several enemies are onscreen at once.
* Enemies will change their direction once they reach an opening in their path.
* The player can utilize four escape tunnels that appear onscreen (two running vertically and two horizontally), warping them to the opposite end of a tunnel when entered.
* If an enemy catches the player, they will lose a life and the difficulty level will start over (i. e. with only one enemy appearing in the pen). Once all lives are lost the game will end.

## Controls

* At the title screen, press the x key to play the game.
* Use the arrow keys to move.
* Use the enter or p keys to pause the game and/or reset the cart.
Flr

flr( num )
Returns the nearest integer at or below a number (its "floor").
num

The number.

*return-value*

The nearest integer at or below num.
If the given number is a fractional value between two integers, the lower integer is returned.

If the given number is already exactly an integer, it is returned as-is.

## Examples

```
print(flr(5.9))   -- 5

print(flr(-5.2))  -- -6

print(flr(7))     -- 7

print(flr(-7))    -- -7

```

## Technical notes

* PICO-8's number system is based on 32-bit fixed-point numbers, with 16 bits to the left of the decimal point and 16 bits to the right. This function effectively sets all bits to the right of the decimal point to 0. Therefore, its functionality can be done inline by using the & (and) operator with a mask which has the top 16 bits set to 1s and the bottom 16 bits set to 0s, i.e. `0xffff.0000`, which is actually just `-1` in normal decimal notation.

Thus, these two lines are identical:

```
print(flr(5.9))   -- 5
print(5.9 & -1)   -- 5

```

This optimization has the benefit that it runs significantly faster in tight inner loops, but it has two drawbacks. One drawback is that it produces less-readable code. Another drawback that it is *not* portable to systems other than PICO-8, where numbers may not be stored in a format (e.g. floating-point) that accommodates this kind of bitmasking.

* It is also possible to use `value\1` to get the floor of a value, but beware that divides are very slow operations. It's useful for conserving characters in a tweetcart or some other kind of code golf, but otherwise `value&-1` is the preferred inline optimization.

## See also

* `ceil()`

* Math