Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

22.8 KB
Raw Blame
/*
**  PICO-8 library functions - ported from ZEPTO-8 (C++ -> pure C)
**
**  Original: Copyright 2016-2024 Sam Hocevar <[email protected]> (WTFPL)
**  Port: fix32_t function calls instead of C++ operator overloads.
*/

#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#define lpico8lib_c
#define LUA_LIB

#include "lua.h"

#include "lauxlib.h"
#include "llimits.h"
#include "lobject.h"

#include "trigtables.h"

static int pico8_max(lua_State *l) {
    lua_pushnumber(l, fix32_max(lua_tonumber(l, 1), lua_tonumber(l, 2)));
    return 1;
}

static int pico8_min(lua_State *l) {
    lua_pushnumber(l, fix32_min(lua_tonumber(l, 1), lua_tonumber(l, 2)));
    return 1;
}

static int pico8_mid(lua_State *l) {
    lua_pushnumber(l, fix32_mid(lua_tonumber(l, 1),
                                lua_tonumber(l, 2),
                                lua_tonumber(l, 3)));
    return 1;
}

static int pico8_ceil(lua_State *l) {
    lua_pushnumber(l, fix32_ceil(lua_tonumber(l, 1)));
    return 1;
}

static int pico8_flr(lua_State *l) {
    lua_pushnumber(l, fix32_flr(lua_tonumber(l, 1)));
    return 1;
}

static lua_Number sin_helper(lua_Number x) {
    /* Reduce angle to 0x0 ... 0x0.3fff, with the following PICO-8 rules:
     *  - sin(x) = -sin(x + 0.5)
     *  - sin(x) equals sin(~x) rather than sin(-x)
     *  - the last two bits are rounded
     * We use a lookup table of sin(x)-4x generated by PICO-8 to ensure
     * that we get the exact same results. */
    int32_t xbits = fix32_bits(x);
    int32_t base = (xbits & 0x4000) ? fix32_bits(fix32_bnot(x)) : xbits;
    int32_t a = (base & 0x3fff) + 2;
    int32_t idx = a >> 2;
    if (idx > 4095) idx = 4095;  /* clamp to table bounds */
    fix32_t ret = fix32_from_bits((idx << 4) + sintable[idx]);
    return (xbits & 0x8000) ? ret : fix32_neg(ret);
}

static int pico8_cos(lua_State *l) {
    lua_pushnumber(l, sin_helper(fix32_sub(lua_tonumber(l, 1), fix32_from_bits(0x4000))));
    return 1;
}

static int pico8_sin(lua_State *l) {
    lua_pushnumber(l, sin_helper(lua_tonumber(l, 1)));
    return 1;
}

static int pico8_atan2(lua_State *l) {
    lua_Number x = lua_tonumber(l, 1);
    lua_Number y = lua_tonumber(l, 2);
    int32_t xbits = fix32_bits(x);
    int32_t ybits = fix32_bits(y);
    int32_t bits = 0x4000;
    if (xbits != 0) {
        /* Use integer abs instead of fix32_abs to emulate PICO-8’s behaviour
         * with e.g. atan2(0x8000, 0x8000.0001) */
        int64_t ax = (int64_t)xbits; if (ax < 0) ax = -ax;
        int64_t ay = (int64_t)ybits; if (ay < 0) ay = -ay;
        int64_t q = (ay << 16) / ax;
        if (q > 0x10000)
            bits -= atantable[((int64_t)1 << 32) / q >> 5];
        else
            bits = atantable[q >> 5];
    }
    if (xbits < 0) bits = 0x8000 - bits;
    if (ybits > 0) bits = -bits & 0xffff;
    /* Emulate a bug in PICO-8 with e.g. atan2(1, 0x8000) */
    if (xbits != 0 && ybits == (int32_t)0x80000000) bits = -bits & 0xffff;
    lua_pushnumber(l, fix32_from_bits(bits));
    return 1;
}

static int pico8_sqrt(lua_State *l) {
    int64_t root = 0, x = (int64_t)fix32_bits(lua_tonumber(l, 1)) << 16;
    if (x > 0) {
        /* Square root by abacus algorithm, Martin Guy @ UKC, June 1985. */
        int64_t a;
        for (a = (int64_t)1 << 46; a; a >>= 2, root >>= 1) {
            if (x >= a + root) {
                x -= a + root;
                root += a << 1;
            }
        }
    }
    lua_pushnumber(l, fix32_from_bits((int32_t)root));
    return 1;
}

static int pico8_abs(lua_State *l) {
    lua_pushnumber(l, fix32_abs(lua_tonumber(l, 1)));
    return 1;
}

static int pico8_sgn(lua_State *l) {
    lua_pushnumber(l, fix32_sgn(lua_tonumber(l, 1)));
    return 1;
}

static int pico8_band(lua_State *l) {
    lua_pushnumber(l, fix32_band(lua_tonumber(l, 1), lua_tonumber(l, 2)));
    return 1;
}

static int pico8_bor(lua_State *l) {
    lua_pushnumber(l, fix32_bor(lua_tonumber(l, 1), lua_tonumber(l, 2)));
    return 1;
}

static int pico8_bxor(lua_State *l) {
    lua_pushnumber(l, fix32_bxor(lua_tonumber(l, 1), lua_tonumber(l, 2)));
    return 1;
}

static int pico8_bnot(lua_State *l) {
    lua_pushnumber(l, fix32_bnot(lua_tonumber(l, 1)));
    return 1;
}

static int pico8_shl(lua_State *l) {
    lua_pushnumber(l, fix32_shl(lua_tonumber(l, 1), fix32_to_int(lua_tonumber(l, 2))));
    return 1;
}

static int pico8_lshr(lua_State *l) {
    lua_pushnumber(l, fix32_lshr(lua_tonumber(l, 1), fix32_to_int(lua_tonumber(l, 2))));
    return 1;
}

static int pico8_shr(lua_State *l) {
    lua_pushnumber(l, fix32_shr(lua_tonumber(l, 1), fix32_to_int(lua_tonumber(l, 2))));
    return 1;
}

static int pico8_rotl(lua_State *l) {
    lua_pushnumber(l, fix32_rotl(lua_tonumber(l, 1), fix32_to_int(lua_tonumber(l, 2))));
    return 1;
}

static int pico8_rotr(lua_State *l) {
    lua_pushnumber(l, fix32_rotr(lua_tonumber(l, 1), fix32_to_int(lua_tonumber(l, 2))));
    return 1;
}

static int pico8_tostr(lua_State *l) {
    char buffer[20];
    char const *s = buffer;

    uint16_t flags = 0;
    if (lua_isboolean(l, 2)) {
        flags = lua_toboolean(l, 2) ? 1 : 0;
    }
    else if (lua_isnumber(l, 2)) {
        flags = (uint16_t)lua_tointeger(l, 2);
    }

    switch (lua_type(l, 1))
    {
        case LUA_TNONE:
            /* PICO-8 0.2.2 changelog: tostr() returns "" instead of nil */
            buffer[0] = '\0';
            break;
        case LUA_TNUMBER: {
            lua_Number x = lua_tonumber(l, 1);
            if (flags) {
                uint32_t b = (uint32_t)fix32_bits(x);
                if ((flags & 0x3) == 0x3) {
                    sprintf(buffer, "0x%04x%04x", (unsigned)((b >> 16) & 0xffff), (unsigned)(b & 0xffff));
                }
                else if ((flags & 0x2) == 0x2) {
                    sprintf(buffer, "%d", (int)b);
                }
                else {
                    sprintf(buffer, "0x%04x.%04x", (unsigned)((b >> 16) & 0xffff), (unsigned)(b & 0xffff));
                }
            } else {
                lua_number2str(buffer, x);
            }
            break;
        }
        case LUA_TSTRING:
            lua_pushvalue(l, 1);
            return 1;
        case LUA_TBOOLEAN: s = lua_toboolean(l, 1) ? "true" : "false"; break;
        case LUA_TTABLE:
            /* PICO-8 0.1.12d changelog: "__tostring metatable method
             * observed by tostr() / print() / printh()" */
            if (luaL_callmeta(l, 1, "__tostring")) {
                return 1;
            }
            /* fall through */
        case LUA_TFUNCTION:
            /* PICO-8 0.1.12d changelog: "tostr(x,true) can also be used to view
             * the hex value of functions and tables (uses Lua's tostring)" */
            if (flags) {
                luaL_tolstring(l, 1, NULL);
                return 1;
            }
            /* fall through */
        default: sprintf(buffer, "[%s]", luaL_typename(l, 1)); break;
    }
    lua_pushstring(l, s);
    return 1;
}

static int pico8_tonum(lua_State *l) {
    lua_Number ret;
    switch (lua_type(l, 1))
    {
        case LUA_TSTRING: {
            char const *s = lua_tostring(l, 1);
            uint16_t flags = lua_gettop(l) >= 2 ? (uint16_t)lua_tointeger(l, 2) : 0;
            if (flags & 0x1) {
                char buf[12];
                size_t i;
                for (i = 0; s[i] != '\0' && i < 11; ++i)
                    buf[i] = isxdigit((unsigned char)s[i]) ? s[i] : '0';
                buf[i] = '\0';
                uint32_t bits = (uint32_t)strtol(buf, NULL, 16);
                if (flags & 0x2)
                    lua_pushnumber(l, fix32_from_bits((int32_t)bits));
                else
                    lua_pushnumber(l, fix32_from_int((int)(uint16_t)bits));
                return 1;
            }
            else if (flags & 0x2) {
                uint32_t bits = (uint32_t)strtol(s, NULL, 10);
                lua_pushnumber(l, fix32_from_bits((int32_t)bits));
                return 1;
            }
            /* If parsing failed, PICO-8 returns nothing */
            if (!luaO_str2d(s, strlen(s), &ret)) return 0;
            break;
        }
        case LUA_TNUMBER: ret = lua_tonumber(l, 1); break;
        /* PICO-8 0.2.3 changelog: "tonum(boolean_value) returns 1 or 0 instead of nil" */
        case LUA_TBOOLEAN: ret = lua_toboolean(l, 1) ? FIX32_ONE : FIX32_ZERO; break;
        default: return 0;
    }
    lua_pushnumber(l, ret);
    return 1;
}

static int pico8_chr(lua_State *l) {
    /* (NumPico: through a Lua buffer, not malloc) */
    luaL_Buffer b;
    int numargs = lua_gettop(l);
    luaL_buffinit(l, &b);
    for (int i = 0; i < numargs; i++)
        luaL_addchar(&b, (char)(uint8_t)fix32_to_int(lua_tonumber(l, i + 1)));
    luaL_pushresult(&b);
    return 1;
}

static int pico8_ord(lua_State *l) {
    size_t len;
    int n = 0;
    int count = 1;
    int i;
    char const *s = luaL_checklstring(l, 1, &len);
    if (!lua_isnone(l, 3)) {
        if (!lua_isnumber(l, 3)) return 0;
        count = fix32_to_int(lua_tonumber(l, 3));
    }
    if (!lua_isnone(l, 2)) {
        if (!lua_isnumber(l, 2)) return 0;
        n = fix32_to_int(lua_tonumber(l, 2)) - 1;
    }
    if (n < 0 || (size_t)n >= len || count < 1)
        return 0;
    if ((size_t)(n + count) > len)
        count = (int)(len - (size_t)n);
    /* min stack is only 20. This could be a much longer string */
    lua_checkstack(l, count);
    for (i = 0; i < count; ++i)
        lua_pushnumber(l, fix32_from_int((int)(uint8_t)s[n + i]));
    return count;
}

static int pico8_split(lua_State *l) {
    size_t count = 0, hlen;
    char const *haystack;
    int size = 0;
    char needle = ',';
    int convert;
    char const *end;
    char const *parser;

    if (lua_isnil(l, 1)) {
        return 0;
    }
    haystack = luaL_checklstring(l, 1, &hlen);
    if (!haystack)
        return 0;
    lua_newtable(l);
    /* Split either by chunk size or by needle position */
    if (lua_isnumber(l, 2)) {
        size = fix32_to_int(lua_tonumber(l, 2));
        if (size <= 0)
            size = 1;
    } else if (lua_isstring(l, 2)) {
        needle = *lua_tostring(l, 2);
    }
    convert = lua_isnone(l, 3) || lua_toboolean(l, 3);
    end = haystack + hlen + (!size && needle);
    for (parser = haystack; parser < end; ) {
        lua_Number num;
        char const *next = size ? parser + size
                         : needle ? (char const*)memchr(parser, needle, (size_t)(end - parser)) : parser + 1;
        char saved;
        if (!next || next > end)
            next = haystack + hlen;
        saved = *next; /* temporarily put a null terminator here */
        *(char *)next = '\0';
        if (convert && luaO_str2d(parser, (size_t)(next - parser), &num))
            lua_pushnumber(l, num);
        else
            lua_pushlstring(l, parser, (size_t)(next - parser));
        *(char *)next = saved;
        lua_rawseti(l, -2, (int)(++count));
        parser = next + (!size && needle);
    }
    return 1;
}

// Nil iterator - returns nothing
static int pico8_all_nil_iter(lua_State *L)
{
    (void)L;
    return 0;
}

// String iterator state: [1] = string, [2] = index
static int pico8_all_string_iter(lua_State *L)
{
    size_t len;
    const char *s;
    lua_Integer i;

    s = lua_tolstring(L, lua_upvalueindex(1), &len);
    i = lua_tointeger(L, lua_upvalueindex(2));
    i++;

    if ((size_t)i <= len) {
        lua_pushinteger(L, i);
        lua_replace(L, lua_upvalueindex(2));  // update index
        lua_pushlstring(L, s + i - 1, 1);
        return 1;
    }

    return 0;
}

// Table iterator state: [1] = table, [2] = index, [3] = cached value (r)
static int pico8_all_table_iter(lua_State *L)
{
    lua_Integer saved_i = lua_tointeger(L, lua_upvalueindex(2));
    lua_pushvalue(L, lua_upvalueindex(1)); // push table
    lua_Integer i = saved_i;

    // Stack: [table]
    lua_pushinteger(L, i); // Stack: [table, i]
    lua_rawget(L, -2); // get t[i], Stack: [t[i]]

    // Push cached value r for comparison
    lua_pushvalue(L, lua_upvalueindex(3)); // Stack: [t[i], r]

    int equal = lua_compare(L, -2, -1, LUA_OPEQ);

    if (equal) {
        // t[i] == r, so increment i
        i++;
        lua_pushinteger(L, i);
        lua_replace(L, lua_upvalueindex(2));
    }
    lua_pop(L, 2); // pop t[i] and r

    // Skip nil values
    while (1) {
        lua_pushvalue(L, lua_upvalueindex(1));
        lua_len(L, -1);
        lua_Integer len = lua_tointeger(L, -1);
        lua_pop(L, 2); // pop table and length

        if (i > len) {
            // No more elements
            return 0;
        }

        lua_pushinteger(L, i);
        lua_gettable(L, lua_upvalueindex(1));

        if (lua_isnil(L, -1)) {
            lua_pop(L, 1);
            i++;
            lua_pushinteger(L, i);
            lua_replace(L, lua_upvalueindex(2));
        } else {
            // Found non-nil value at t[i]
            // Stack: [t[i]]
            // Store t[i] in upvalue 3 for comparison on next call
            lua_pushvalue(L, -1); // duplicate t[i]
            lua_replace(L, lua_upvalueindex(3)); // r = t[i]
            // Stack: [t[i]]
            // Don't increment i here - it will be incremented on next call if t[i] == r
            return 1;
        }
    }

    return 0;
}

// all(t) - Returns an iterator function for table or string
static int pico8_all(lua_State *L)
{
    if (lua_isnil(L, 1)) {
        // Return a no-op iterator
        lua_pushcclosure(L, pico8_all_nil_iter, 0);
        return 1;
    }

    int type = lua_type(L, 1);
    if (type == LUA_TSTRING) {
        // String iteration - iterate over each character
        lua_pushvalue(L, 1); // string as upvalue 1
        lua_pushinteger(L, 0); // index i as upvalue 2

        lua_pushcclosure(L, pico8_all_string_iter, 2);
    } else if (type == LUA_TTABLE) {
        lua_pushvalue(L, 1);   // table as upvalue 1
        lua_pushinteger(L, 0); // index i as upvalue 2
        lua_pushnil(L);        // cached value r as upvalue 3

        lua_pushcclosure(L, pico8_all_table_iter, 3);
    } else {
        lua_pushnil(L);
    }
    return 1;
}

// add(t, v, i) - Add value to table at position i
static int pico8_add(lua_State *L)
{
    if (!lua_istable(L, 1))
        return 0;

    lua_len(L, 1);
    lua_Integer n = lua_tointeger(L, -1);
    lua_pop(L, 1);

    if (lua_isnoneornil(L, 3)) {
        // Add to end: t[#t+1] = v
        lua_pushvalue(L, 2);
        lua_pushinteger(L, n + 1);
        lua_insert(L, -2);
        lua_settable(L, 1);
    } else {
        // Insert at position i: shift elements
        lua_Integer i = lua_tointeger(L, 3);

        // Shift elements from end to i (from high to low)
        for (lua_Integer j = n; j >= i; --j) {
            lua_pushinteger(L, j);
            lua_gettable(L, 1);
            lua_pushinteger(L, j + 1);
            lua_insert(L, -2);
            lua_settable(L, 1);
        }

        // Insert new value
        lua_pushvalue(L, 2);
        lua_pushinteger(L, i);
        lua_insert(L, -2);
        lua_settable(L, 1);
    }

    lua_pushvalue(L, 2); // return v
    return 1;
}

// foreach(c, f) - Call f for each element in c
static int pico8_foreach(lua_State *L)
{
    if (lua_isnil(L, 1))
        return 0;

    luaL_checktype(L, 2, LUA_TFUNCTION);

    // Get iterator from all()
    lua_pushcfunction(L, pico8_all);
    lua_pushvalue(L, 1);
    lua_call(L, 1, 1);

    // Call iterator in loop
    while (1) {
        lua_pushvalue(L, -1);  // push iterator
        lua_call(L, 0, 1);     // call iterator, get result

        if (lua_isnil(L, -1)) {
            lua_pop(L, 2);     // pop result and iterator
            break;
        }

        // Call f(value)
        lua_pushvalue(L, 2);   // function f
        lua_pushvalue(L, -2);  // value
        lua_call(L, 1, 0);     // call f(value)

        lua_pop(L, 1);         // pop value
    }

    return 0;
}

// mapdraw(...) - Calls map with unpacked args
static int pico8_mapdraw(lua_State *L)
{
    int nargs = lua_gettop(L);
    if (nargs > 0) {
        // Create table from arguments
        lua_newtable(L);
        for (int i = 1; i <= nargs; i++) {
            lua_pushvalue(L, i);
            lua_pushinteger(L, i);
            lua_insert(L, -2);
            lua_settable(L, -3);
        }

        // Call map with the table
        lua_getglobal(L, "map");
        lua_pushvalue(L, -2);
        lua_call(L, 1, 0);
    } else {
        lua_getglobal(L, "map");
        lua_call(L, 0, 0);
    }
    return 0;
}

// count(t, v) - Count elements in table, or occurrences of v
static int pico8_count(lua_State *L)
{
    if (!lua_istable(L, 1))
        return 0;

    lua_len(L, 1);
    lua_Integer n = lua_tointeger(L, -1);
    lua_pop(L, 1);

    if (lua_isnoneornil(L, 2)) {
        // Return #t
        lua_pushinteger(L, n);
        return 1;
    } else {
        // Count occurrences of v
        lua_Integer c = 0;
        for (lua_Integer i = 1; i <= n; i++) {
            lua_pushinteger(L, i);
            lua_gettable(L, 1);
            if (lua_compare(L, -1, 2, LUA_OPEQ)) {
                c++;
            }
            lua_pop(L, 1);
        }
        lua_pushinteger(L, c);
    }
    return 1;
}

// del(t, v) - Delete first occurrence of v from table
static int pico8_del(lua_State *L)
{
    if (!lua_istable(L, 1))
        return 0;

    lua_len(L, 1);
    lua_Integer n = lua_tointeger(L, -1);
    lua_pop(L, 1);
    int found = 0;

    for (lua_Integer i = 1; i <= n; i++) {
        lua_pushinteger(L, i);
        lua_gettable(L, 1);

        if (!found && lua_compare(L, -1, 2, LUA_OPEQ))
            found = 1;

        lua_pop(L, 1);

        if (found) {
            lua_pushinteger(L, i + 1);
            lua_gettable(L, 1);
            lua_pushinteger(L, i);
            lua_insert(L, -2);
            lua_settable(L, 1);
        }
    }

    if (found) {
        lua_pushvalue(L, 2);
        return 1;
    }

    return 0;
}

// deli(t, i) - Delete element at index i
static int pico8_deli(lua_State *L)
{
    if (!lua_istable(L, 1))
        return 0;

    lua_len(L, 1);
    lua_Integer n = lua_tointeger(L, -1);
    lua_pop(L, 1);
    lua_Integer i;

    if (lua_isnoneornil(L, 2))
        i = n;
    else
        i = lua_tointeger(L, 2);

    if (i < 1 || i > n)
        return 0;

    // Get value at i and save it on top
    lua_pushinteger(L, i);
    lua_gettable(L, 1);

    // Shift elements left: for j from i to n, t[j] = t[j+1]
    // Note: when j == n, t[n] = t[n+1] = nil, effectively removing the last element
    for (lua_Integer j = i; j <= n; j++) {
        lua_pushinteger(L, j + 1);
        lua_gettable(L, 1);
        lua_pushinteger(L, j);
        lua_insert(L, -2);
        lua_settable(L, 1);
    }

    return 1;
}

// cocreate(f) - Create coroutine (copy from lcorolib.c)
static int pico8_cocreate(lua_State *L)
{
    luaL_checktype(L, 1, LUA_TFUNCTION);
    lua_State *NL = lua_newthread(L);
    lua_pushvalue(L, 1);  /* move function to top */
    lua_xmove(L, NL, 1);  /* move function from L to NL */
    return 1;
}

// yield(...) - Yield coroutine (copy from lcorolib.c)
static int pico8_yield_wrapper(lua_State *L)
{
    return lua_yield(L, lua_gettop(L));
}

/* auxresume - copy from lcorolib.c */
static int auxresume(lua_State *L, lua_State *co, int narg)
{
    int status;

    if (!lua_checkstack(co, narg)) {
        lua_pushliteral(L, "too many arguments to resume");
        return -1;  /* error flag */
    }

    if (lua_status(co) == LUA_OK && lua_gettop(co) == 0) {
        lua_pushliteral(L, "cannot resume dead coroutine");
        return -1;  /* error flag */
    }

    lua_xmove(L, co, narg);
    status = lua_resume(co, L, narg);

    if (status == LUA_OK || status == LUA_YIELD) {
        int nres = lua_gettop(co);
        if (!lua_checkstack(L, nres + 1)) {
            lua_pop(co, nres);  /* remove results anyway */
            lua_pushliteral(L, "too many results to resume");
            return -1;  /* error flag */
        }
        lua_xmove(co, L, nres);  /* move yielded values */
        return nres;
    } else {
        lua_xmove(co, L, 1);  /* move error message */
        return -1;  /* error flag */
    }
}

// coresume(f, ...) - Resume coroutine (copy from lcorolib.c)
static int pico8_coresume(lua_State *L)
{
    lua_State *co = lua_tothread(L, 1);
    int r;

    luaL_argcheck(L, co, 1, "coroutine expected");
    r = auxresume(L, co, lua_gettop(L) - 1);

    if (r < 0) {
        lua_pushboolean(L, 0);
        lua_insert(L, -2);
        return 2;  /* return false + error message */
    } else {
        lua_pushboolean(L, 1);
        lua_insert(L, -(r + 1));
        return r + 1;  /* return true + `resume' returns */
    }
}

// costatus(f) - Get coroutine status (copy from lcorolib.c)
static int pico8_costatus(lua_State *L)
{
    lua_State *co = lua_tothread(L, 1);
    luaL_argcheck(L, co, 1, "coroutine expected");

    if (L == co) {
        lua_pushstring(L, "running");
    } else {
        switch (lua_status(co)) {
            case LUA_YIELD:
                lua_pushstring(L, "suspended");
                break;
            case LUA_OK: {
                lua_Debug ar;
                if (lua_getstack(co, 0, &ar) > 0) {  /* does it have frames? */
                    lua_pushstring(L, "normal");  /* it is running */
                } else if (lua_gettop(co) == 0)
                    lua_pushstring(L, "dead");
                else
                    lua_pushstring(L, "suspended");  /* initial state */
                break;
            }
            default:  /* some error occurred */
                lua_pushstring(L, "dead");
                break;
        }
    }
    return 1;
}

// pack(...) - Pack arguments into table with n field
static int pico8_pack(lua_State *L)
{
    int nargs = lua_gettop(L);

    // Create table with array part
    lua_createtable(L, nargs, 1);

    for (int i = 1; i <= nargs; i++) {
        lua_pushvalue(L, i);
        lua_pushinteger(L, i);
        lua_insert(L, -2);
        lua_settable(L, -3);
    }

    // Set n field
    lua_pushinteger(L, nargs);
    lua_setfield(L, -2, "n");

    return 1;
}

static const luaL_Reg pico8lib[] = {
  {"max",   pico8_max},
  {"min",   pico8_min},
  {"mid",   pico8_mid},
  {"ceil",  pico8_ceil},
  {"flr",   pico8_flr},
  {"cos",   pico8_cos},
  {"sin",   pico8_sin},
  {"atan2", pico8_atan2},
  {"sqrt",  pico8_sqrt},
  {"abs",   pico8_abs},
  {"sgn",   pico8_sgn},
  {"band",  pico8_band},
  {"bor",   pico8_bor},
  {"bxor",  pico8_bxor},
  {"bnot",  pico8_bnot},
  {"shl",   pico8_shl},
  {"shr",   pico8_shr},
  {"lshr",  pico8_lshr},
  {"rotl",  pico8_rotl},
  {"rotr",  pico8_rotr},
  {"tostr", pico8_tostr},
  {"tonum", pico8_tonum},
  {"chr",   pico8_chr},
  {"ord",   pico8_ord},
  {"split", pico8_split},
  {"all", pico8_all},
  {"add", pico8_add},
  {"foreach", pico8_foreach},
  {"mapdraw", pico8_mapdraw},
  {"count", pico8_count},
  {"del", pico8_del},
  {"deli", pico8_deli},
  {"pack", pico8_pack},
  {"cocreate", pico8_cocreate},
  {"coresume", pico8_coresume},
  {"costatus", pico8_costatus},
  {"yield", pico8_yield_wrapper},
  {NULL, NULL}
};


/*
** Register PICO-8 functions in global table
*/
LUAMOD_API int luaopen_pico8 (lua_State *L) {
  lua_pushglobaltable(L);
  luaL_setfuncs(L, pico8lib, 0);
  return 1;
}