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.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
NumPico: PICO-8 carts on the calculator, first build
Mason36386c47b115cdf
diff --git a/games/numpico/.gitignore b/games/numpico/.gitignorenew file mode 100644index 00000000..342d9dda--- /dev/null+++ b/games/numpico/.gitignore@@ -0,0 +1,2 @@+output/+build/diff --git a/games/numpico/Makefile b/games/numpico/Makefilenew file mode 100644index 00000000..99bf62b8--- /dev/null+++ b/games/numpico/Makefile@@ -0,0 +1,105 @@+# NumPico, PICO-8 carts on the NumWorks calculator: an app of its own.+# make output/numpico.nwa with the carts in CARTS (none: it says how to add some), and+# output/module.nwa, the same without carts, for NumPlay Studio's kit+# make CARTS="a.p8 b.p8.png" with those carts in it (or CARTS_LIST=file: one a line)+# make check link it like the calculator does (output/numpico.bin), within the RAM and the app space+# make test the carts table, then carts played on this computer with random keys, with the sanitizers+# make perf carts in tools/emu.py at an N0110's speed: frames a second and Lua's memory+Q ?= @+TOOLCHAIN ?=+BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)+CC = $(BIN)arm-none-eabi-gcc+STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneeded+NWLINK ?= npx --yes -- [email protected]+BUILD_DIR = output+L = ../../launcher/src+PYTHON ?= python3+CARTS ?=+# carts to try (not in NumPlay): PICO-8's BBS carts and femto8's, in gamesrc+TEST_CARTS ?= $(HOME)/Documents/Assets/gamesrc/numpico/carts++LUA = lapi lauxlib lbaselib lcode lcorolib lctype ldebug ldo lfunc lgc linit llex lmem lobject lopcodes \+ lparser lpico8lib lstate lstring lstrlib ltable ltablib ltm lvm lzio+CORE_SRC = $(foreach f,$(LUA),src/femto8/lua/$(f).c) src/femto8/p8_lua.c src/pico.c src/heap.c+APP_SRC = src/main.c src/carts.c src/plat_eadk.c $(L)/gfx.c $(L)/font_data.c $(L)/xfont.c+HEADERS = $(wildcard src/*.h src/femto8/*.h src/femto8/lua/*.h) $(L)/gfx.h $(L)/font.h $(L)/np.h \+ ../common/epsilon_app.h ../common/epsilon_files.h++CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DPLATFORM_DEVICE=1 -DEPSILON_XL=1 -DNDEBUG -I$(L) -Isrc \+ -Isrc/femto8 -Isrc/femto8/lua+CFLAGS += -Wall -Wno-unused-parameter -Wno-unused-function -fno-math-errno -fsingle-precision-constant+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal+CFLAGS += -ffunction-sections -fdata-sections+# Lua and the drawing at -O2, the screens at -Os+CORE_OPT = -O2+APP_OPT = -Os+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel $(LDEXTRA)++# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones), and the+# calculator's app space is 2031616 bytes+RAM = 133652+APP_SPACE = 2031616++.PHONY: build check clean test perf FORCE+build: $(BUILD_DIR)/numpico.nwa $(BUILD_DIR)/module.nwa++check: $(BUILD_DIR)/numpico.nwa+ $(Q) $(NWLINK) nwa-bin --ram-length $(RAM) $< $(BUILD_DIR)/numpico.bin+ $(Q) n=$$(wc -c < $(BUILD_DIR)/numpico.bin); [ $$n -le $(APP_SPACE) ] || \+ { echo "numpico.nwa is bigger than the calculator's app space ($(APP_SPACE) bytes)"; exit 1; }; \+ echo "BIN $(BUILD_DIR)/numpico.bin: $$n bytes, RAM within $(RAM) bytes"++OBJ = $(patsubst %.c,$(BUILD_DIR)/obj/%.o,$(notdir $(CORE_SRC) $(APP_SRC)))+vpath %.c src src/femto8 src/femto8/lua $(L)+$(BUILD_DIR)/obj/%.o: %.c $(HEADERS) | $(BUILD_DIR)+ @mkdir -p $(@D)+ @echo "CC $<"+ $(Q) $(CC) $(CFLAGS) $(if $(filter $<,$(CORE_SRC)),$(CORE_OPT),$(APP_OPT)) -c $< -o $@++# the carts: tools/p8cart.py makes the table (it leaves the file alone when it would be the same)+$(BUILD_DIR)/carts.o: FORCE | $(BUILD_DIR)+ $(Q) $(PYTHON) -I tools/p8cart.py -o $@ $(CARTS) $(if $(CARTS_LIST),--list $(CARTS_LIST))++$(BUILD_DIR)/numpico-full.nwa: $(OBJ) $(BUILD_DIR)/icon.o $(BUILD_DIR)/carts.o src/carts.ld+ @echo "LD $@"+ $(Q) $(CC) $(CFLAGS) $(APP_OPT) $(LDFLAGS) -Wl,-T,src/carts.ld $(OBJ) $(BUILD_DIR)/icon.o $(BUILD_DIR)/carts.o -lm -o $@+# (stripped: what goes on the calculator; numpico-full.nwa keeps its symbols, for tools/emu.py --profile)+$(BUILD_DIR)/numpico.nwa: $(BUILD_DIR)/numpico-full.nwa+ $(Q) $(STRIP) -o $@ $<+# NumPlay Studio's kit: no carts, np_carts and the block's end (np_numpico_end) left to NumPlay's link+$(BUILD_DIR)/module.nwa: $(OBJ) $(BUILD_DIR)/icon.o+ $(Q) $(CC) $(CFLAGS) $(APP_OPT) $(LDFLAGS) $(OBJ) $(BUILD_DIR)/icon.o -lm -o $@+ $(Q) $(STRIP) $@++$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)+ @echo "ICON $<"+ $(Q) $(NWLINK) png-icon-o $< $@++$(BUILD_DIR):+ $(Q) mkdir -p $@++clean:+ $(Q) rm -rf $(BUILD_DIR) build++# ------------------------------------------------------------------ on this computer+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wno-unused-parameter -Wno-unused-function -Wno-deprecated-declarations -DHOST \+ -I$(L) -Isrc -Isrc/femto8 -Isrc/femto8/lua -fsanitize=address,undefined -fno-sanitize=shift-base \+ -fno-sanitize-recover=undefined+HOST_SRC = tests/host.c src/main.c src/carts.c $(CORE_SRC) $(L)/gfx.c $(L)/font_data.c $(L)/xfont.c+build/host: $(HOST_SRC) $(HEADERS)+ $(Q) mkdir -p build+ $(Q) cc $(HOST_FLAGS) $(HOST_SRC) -lm -o $@+ @echo "HOST $@"+test: build/host+ $(Q) $(PYTHON) -I tests/test_p8cart.py+ $(Q) $(PYTHON) tests/test_carts.py build/host $(TEST_CARTS)++# the carts in TEST_CARTS on the emulator, one at a time (PERF_CART): frames a second, Lua's memory at its most+$(BUILD_DIR)/perf-carts.o: FORCE | $(BUILD_DIR)+ $(Q) $(PYTHON) -I tools/p8cart.py -o $@ $(PERF_CART)+$(BUILD_DIR)/perf.nwa: $(OBJ) $(BUILD_DIR)/icon.o $(BUILD_DIR)/perf-carts.o src/carts.ld+ $(Q) $(CC) $(CFLAGS) $(APP_OPT) $(LDFLAGS) -Wl,-T,src/carts.ld $(OBJ) $(BUILD_DIR)/icon.o $(BUILD_DIR)/perf-carts.o -lm -o $@+perf: $(OBJ)+ $(Q) NWLINK="$(NWLINK)" $(PYTHON) tests/perf.py $(TEST_CARTS)diff --git a/games/numpico/src/carts.c b/games/numpico/src/carts.cnew file mode 100644index 00000000..59373365--- /dev/null+++ b/games/numpico/src/carts.c@@ -0,0 +1,100 @@+#include "carts.h"+#include <string.h>++static uint32_t rd32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; }++/* a comment line of the code: its text after "--", spaces trimmed, at most n - 1 bytes */+static const char *comment(const char *code, const char *end, char *out, int n) {+ out[0] = 0;+ const char *eol = code;+ while (eol < end && *eol != '\n') eol++;+ const char *p = code;+ while (p < eol && (*p == ' ' || *p == '\t')) p++;+ if (eol - p >= 2 && p[0] == '-' && p[1] == '-' && !(eol - p >= 4 && p[2] == '[' && p[3] == '[')) {+ p += 2;+ while (p < eol && (*p == ' ' || *p == '\t' || *p == '-')) p++;+ const char *q = eol;+ while (q > p && (q[-1] == ' ' || q[-1] == '\t' || q[-1] == '\r')) q--;+ int k = 0;+ for (; p < q && k < n - 1; p++) out[k++] = *p;+ out[k] = 0;+ }+ return eol < end ? eol + 1 : end;+}++int carts_read(const uint8_t *t, uint32_t limit, p8_cart_t *out, int max) {+ if (!t || limit < 12 || rd32(t) != P8_CARTS_MAGIC || rd32(t + 4) != P8_CARTS_VERSION) return -1;+ uint32_t count = rd32(t + 8);+ if (count > (limit - 12) / P8_CARTS_ENTRY) return -1;+ int n = 0;+ for (uint32_t i = 0; i < count && n < max; i++) {+ const uint8_t *e = t + 12 + P8_CARTS_ENTRY * i;+ uint32_t rom = rd32(e), code = rd32(e + 4), len = rd32(e + 8), label = rd32(e + 12);+ if (rom & 3 || rom < 12 || rom > limit || limit - rom < P8_ROM_SIZE) continue;+ if (code > limit || len > limit - code || len > 0x30000) continue;+ if (label && (label > limit || limit - label < P8_LABEL_SIZE)) continue;+ p8_cart_t *c = &out[n++];+ c->rom = t + rom;+ c->code = (const char *)t + code;+ c->code_len = len;+ c->label = label ? t + label : NULL;+ c->name = e + 16;+ }+ return n;+}++void carts_name(const p8_cart_t *c, char *out, int n) {+ int k = 0;+ for (int i = 0; i < P8_CARTS_NAME && c->name[i] && k < n - 1; i++) {+ uint8_t b = c->name[i];+ if ((b & 0xC0) == 0x80) continue; /* (the rest of a letter) */+ out[k++] = b >= 0x20 && b < 0x7F ? (char)b : '?';+ }+ out[k] = 0;+}++void carts_title(const p8_cart_t *c, char *title, int tn, char *author, int an) {+ const char *p = c->code, *end = c->code + c->code_len;+ p = comment(p, end, title, tn);+ author[0] = 0;+ if (title[0]) comment(p, end, author, an);+}++static char lower(char c) { return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c; }++/* the name as load() gives it: after any path or "#", without .p8 or .p8.png */+static int base_len(const char **s) {+ const char *p = *s;+ for (const char *q = p; *q; q++)+ if (*q == '/' || *q == '\\' || *q == '#') p = q + 1;+ int n = (int)strlen(p);+ if (n >= 7 && lower(p[n - 7]) == '.' && lower(p[n - 6]) == 'p' && p[n - 5] == '8' && p[n - 4] == '.' &&+ lower(p[n - 3]) == 'p' && lower(p[n - 2]) == 'n' && lower(p[n - 1]) == 'g')+ n -= 7;+ else if (n >= 3 && p[n - 3] == '.' && lower(p[n - 2]) == 'p' && p[n - 1] == '8')+ n -= 3;+ *s = p;+ return n;+}++int carts_find(const p8_cart_t *carts, int n, const char *name) {+ if (!name) return -1;+ int len = base_len(&name);+ if (len <= 0) return -1;+ /* the same name, else the BBS's file for it ("#poom_1" is poom_1-0.p8.png when downloaded) */+ for (int pass = 0; pass < 2; pass++)+ for (int i = 0; i < n; i++) {+ char c[P8_CARTS_NAME + 1];+ carts_name(&carts[i], c, sizeof c);+ int k = 0;+ while (k < len && c[k] && lower(c[k]) == lower(name[k])) k++;+ if (k != len) continue;+ if (!c[k]) return i;+ if (pass == 1 && c[k] == '-' && c[k + 1]) {+ k++;+ while (c[k] >= '0' && c[k] <= '9') k++;+ if (!c[k]) return i;+ }+ }+ return -1;+}diff --git a/games/numpico/src/carts.h b/games/numpico/src/carts.hnew file mode 100644index 00000000..f4047fe0--- /dev/null+++ b/games/numpico/src/carts.h@@ -0,0 +1,41 @@+/* NumPico's carts: the table np_carts in the app's flash, read in place. tools/p8cart.py and NumPlay+ * Studio make it from .p8 and .p8.png files, with the code already unpacked and in P8SCII:+ * u32 magic "NPP8" (0x3850504E), u32 version 1, u32 count;+ * count entries of 64 bytes:+ * u32 rom from np_carts to the cart's 0x4300 bytes (sprites, map, flags, music, sound);+ * u32 code from np_carts to its Lua code, u32 code_len its bytes;+ * u32 label from np_carts to its label, or 0: 16 colours (0..15, or 128..143 for the+ * secondary ones), then 128 x 128 pixels, 4 bits each, the left one low;+ * char name[48] the file's name without .p8 or .p8.png (UTF-8, zero-padded);+ * then the carts' parts, each 4-byte aligned.+ * All numbers little-endian. */+#ifndef NP8_CARTS_H+#define NP8_CARTS_H+#include <stdbool.h>+#include <stdint.h>++#define P8_CARTS_MAGIC 0x3850504Eu+#define P8_CARTS_VERSION 1+#define P8_CARTS_ENTRY 64+#define P8_CARTS_NAME 48+#define P8_MAX_CARTS 64+#define P8_ROM_SIZE 0x4300+#define P8_LABEL_SIZE (16 + 128 * 64)++typedef struct {+ const uint8_t *rom, *label, *name; /* (name: P8_CARTS_NAME bytes, zero-padded, maybe not ended) */+ const char *code;+ uint32_t code_len;+} p8_cart_t;++/* The carts of a table of which `limit` bytes can be read, at most `max`, in the table's order;+ entries that don't hold together are left out. -1 when it isn't a table at all. */+int carts_read(const uint8_t *table, uint32_t limit, p8_cart_t *out, int max);+/* the cart called `name` (any case, with or without .p8 or .p8.png, a path or a "#" before it), or -1 */+int carts_find(const p8_cart_t *carts, int n, const char *name);+/* its file's name, ASCII ('?' for other letters), at most n - 1 bytes */+void carts_name(const p8_cart_t *c, char *out, int n);+/* its title and author: the code's first two comment lines (as PICO-8 writes them: lowercase shows+ as its capitals), or "" */+void carts_title(const p8_cart_t *c, char *title, int tn, char *author, int an);+#endifdiff --git a/games/numpico/src/carts.ld b/games/numpico/src/carts.ldnew file mode 100644index 00000000..75da31b7--- /dev/null+++ b/games/numpico/src/carts.ld@@ -0,0 +1,5 @@+/* NumPico.nwa on its own: the table of carts keeps its own section, and np_numpico_end marks its end,+ as NumPlay's numplay.ld marks the end of NumPico's block (main.c reads no cart past it). */+SECTIONS {+ .rodata.np_carts : { KEEP(*(.rodata.np_carts)) np_numpico_end = .; }+}diff --git a/games/numpico/src/femto8/LICENSE b/games/numpico/src/femto8/LICENSEnew file mode 100644index 00000000..a30963ea--- /dev/null+++ b/games/numpico/src/femto8/LICENSE@@ -0,0 +1,7 @@+Copyright 2023 Ben Baker++Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.diff --git a/games/numpico/src/femto8/lua/fix32.h b/games/numpico/src/femto8/lua/fix32.hnew file mode 100644index 00000000..5c98a45d--- /dev/null+++ b/games/numpico/src/femto8/lua/fix32.h@@ -0,0 +1,158 @@+/*+ * fix32.h - Pure C 16.16 fixed-point arithmetic+ *+ * Port of z8::fix32 from femto8 (C++ operator overloads -> C inline functions).+ * All PICO-8 numbers are stored as int32_t with 16 integer bits and 16 fractional bits.+ */++#ifndef FIX32_H+#define FIX32_H++#include <stdint.h>+#include <math.h>++typedef int32_t fix32_t;++/* Constants */+#define FIX32_ZERO ((fix32_t)0)+#define FIX32_ONE ((fix32_t)0x00010000)+#define FIX32_HALF ((fix32_t)0x00008000)+#define FIX32_NEG_ONE ((fix32_t)0xFFFF0000)+#define FIX32_MAX ((fix32_t)0x7FFFFFFF)+#define FIX32_MIN ((fix32_t)0x80000001) /* not 0x80000000, per PICO-8 */++/* Construction */+static inline fix32_t fix32_from_int(int x) { return (fix32_t)x << 16; }+static inline fix32_t fix32_from_double(double d) { return (fix32_t)(int64_t)(d * 65536.0); }+static inline fix32_t fix32_from_bits(int32_t b) { return b; }++/* Conversion */+static inline int fix32_to_int(fix32_t x) { return x >> 16; }+static inline double fix32_to_double(fix32_t x) { return (double)x / 65536.0; }+static inline int32_t fix32_bits(fix32_t x) { return x; }++/* Comparisons */+static inline int fix32_eq(fix32_t a, fix32_t b) { return a == b; }+static inline int fix32_ne(fix32_t a, fix32_t b) { return a != b; }+static inline int fix32_lt(fix32_t a, fix32_t b) { return a < b; }+static inline int fix32_gt(fix32_t a, fix32_t b) { return a > b; }+static inline int fix32_le(fix32_t a, fix32_t b) { return a <= b; }+static inline int fix32_ge(fix32_t a, fix32_t b) { return a >= b; }+static inline int fix32_bool(fix32_t a) { return a != 0; }++/* Basic arithmetic - use unsigned to avoid signed overflow UB */+static inline fix32_t fix32_add(fix32_t a, fix32_t b) { return (fix32_t)((uint32_t)a + (uint32_t)b); }+static inline fix32_t fix32_sub(fix32_t a, fix32_t b) { return (fix32_t)((uint32_t)a - (uint32_t)b); }+static inline fix32_t fix32_neg(fix32_t a) { return (fix32_t)(-(uint32_t)a); }++static inline fix32_t fix32_mul(fix32_t a, fix32_t b) {+ return (fix32_t)((int64_t)a * b >> 16);+}++static inline fix32_t fix32_div(fix32_t a, fix32_t b) {+ /* Special case: 0x8000/0x1 = 0x8000, not 0x8000.0001 */+ if (b == FIX32_ONE)+ return a;++ if (b) {+ int64_t result = (int64_t)a * 0x10000 / b;+ int64_t abs_result = result < 0 ? -result : result;+ if (abs_result <= (int64_t)0x7FFFFFFFU)+ return (fix32_t)result;+ }++ /* Return 0x8000.0001 (not 0x8000.0000) for -Inf, just like PICO-8 */+ return (a ^ b) >= 0 ? (fix32_t)0x7FFFFFFFU : (fix32_t)0x80000001U;+}++static inline fix32_t fix32_mod(fix32_t a, fix32_t b) {+ /* PICO-8 always returns positive values */+ fix32_t abs_b = b < 0 ? -b : b;+ /* PICO-8 0.2.5f: x % 0 gives 0 */+ if (!abs_b) return 0;+ int32_t result = a % abs_b;+ return result >= 0 ? result : result + abs_b;+}++static inline fix32_t fix32_idiv(fix32_t a, fix32_t b) {+ fix32_t d = fix32_div(a, b);+ return d & (fix32_t)0xFFFF0000; /* floor = mask off fraction */+}++/* Bitwise */+static inline fix32_t fix32_band(fix32_t a, fix32_t b) { return a & b; }+static inline fix32_t fix32_bor(fix32_t a, fix32_t b) { return a | b; }+static inline fix32_t fix32_bxor(fix32_t a, fix32_t b) { return a ^ b; }+static inline fix32_t fix32_bnot(fix32_t a) { return ~a; }++/* Forward declaration for mutual recursion */+static inline fix32_t fix32_lshr(fix32_t x, int y);++static inline fix32_t fix32_shl(fix32_t x, int y) {+ /* Negative y = lshr instead */+ if (y < 0) return fix32_lshr(x, -y);+ return y >= 32 ? 0 : x << y;+}++static inline fix32_t fix32_shr(fix32_t x, int y) {+ /* Arithmetic right shift. Negative y = left shift */+ if (y < 0) return fix32_shl(x, -y);+ int shift = y < 31 ? y : 31;+ return x >> shift;+}++static inline fix32_t fix32_lshr(fix32_t x, int y) {+ /* Logical (unsigned) right shift. Negative y = left shift */+ if (y < 0) return fix32_shl(x, -y);+ return y >= 32 ? 0 : (fix32_t)((uint32_t)x >> y);+}++static inline fix32_t fix32_rotl(fix32_t x, int y) {+ y &= 0x1f;+ return (x << y) | (fix32_t)((uint32_t)x >> (32 - y));+}++static inline fix32_t fix32_rotr(fix32_t x, int y) {+ y &= 0x1f;+ return (fix32_t)((uint32_t)x >> y) | (x << (32 - y));+}++/* Math functions */++/* PICO-8 0.2.3: abs(0x8000) should be 0x7fff.ffff */+static inline fix32_t fix32_abs(fix32_t a) {+ if (a >= 0) return a;+ if ((a << 1) == 0) return ~a; /* 0x80000000 -> 0x7FFFFFFF */+ return -a;+}++static inline fix32_t fix32_min(fix32_t a, fix32_t b) { return a < b ? a : b; }+static inline fix32_t fix32_max(fix32_t a, fix32_t b) { return a > b ? a : b; }++static inline fix32_t fix32_mid(fix32_t a, fix32_t b, fix32_t c) {+ if (a > b) { fix32_t t = a; a = b; b = t; }+ /* now a <= b */+ if (c <= a) return a;+ if (c >= b) return b;+ return c;+}++static inline fix32_t fix32_flr(fix32_t x) {+ return x & (fix32_t)0xFFFF0000;+}++static inline fix32_t fix32_ceil(fix32_t x) {+ return fix32_neg(fix32_flr(fix32_neg(x)));+}++static inline fix32_t fix32_sgn(fix32_t x) {+ if (x > 0) return FIX32_ONE;+ if (x < 0) return FIX32_NEG_ONE;+ return FIX32_ONE; /* PICO-8: sgn(0) = 1 */+}++static inline fix32_t fix32_pow(fix32_t x, fix32_t y) {+ return fix32_from_double(pow(fix32_to_double(x), fix32_to_double(y)));+}++#endif /* FIX32_H */diff --git a/games/numpico/src/femto8/lua/lapi.c b/games/numpico/src/femto8/lua/lapi.cnew file mode 100644index 00000000..c860040b--- /dev/null+++ b/games/numpico/src/femto8/lua/lapi.c@@ -0,0 +1,1292 @@+/*+** $Id: lapi.c,v 2.171 2013/03/16 21:10:18 roberto Exp $+** Lua API+** See Copyright Notice in lua.h+** Changed for NumPico: lua_dump dumps nothing (no luaU_dump).+*/+++#include <stdarg.h>+#include <string.h>++#define lapi_c+#define LUA_CORE++#include "lua.h"++#include "lapi.h"+#include "ldebug.h"+#include "ldo.h"+#include "lfunc.h"+#include "lgc.h"+#include "lmem.h"+#include "lobject.h"+#include "lstate.h"+#include "lstring.h"+#include "ltable.h"+#include "ltm.h"+#include "lundump.h"+#include "lvm.h"++++const char lua_ident[] =+ "$LuaVersion: " LUA_COPYRIGHT " $"+ "$LuaAuthors: " LUA_AUTHORS " $";+++/* value at a non-valid index */+#define NONVALIDVALUE cast(TValue *, luaO_nilobject)++/* corresponding test */+#define isvalid(o) ((o) != luaO_nilobject)++/* test for pseudo index */+#define ispseudo(i) ((i) <= LUA_REGISTRYINDEX)++/* test for valid but not pseudo index */+#define isstackindex(i, o) (isvalid(o) && !ispseudo(i))++#define api_checkvalidindex(L, o) api_check(L, isvalid(o), "invalid index")++#define api_checkstackindex(L, i, o) \+ api_check(L, isstackindex(i, o), "index not in the stack")+++static TValue *index2addr (lua_State *L, int idx) {+ CallInfo *ci = L->ci;+ if (idx > 0) {+ TValue *o = ci->func + idx;+ api_check(L, idx <= ci->top - (ci->func + 1), "unacceptable index");+ if (o >= L->top) return NONVALIDVALUE;+ else return o;+ }+ else if (!ispseudo(idx)) { /* negative index */+ api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index");+ return L->top + idx;+ }+ else if (idx == LUA_REGISTRYINDEX)+ return &G(L)->l_registry;+ else { /* upvalues */+ idx = LUA_REGISTRYINDEX - idx;+ api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large");+ if (ttislcf(ci->func)) /* light C function? */+ return NONVALIDVALUE; /* it has no upvalues */+ else {+ CClosure *func = clCvalue(ci->func);+ return (idx <= func->nupvalues) ? &func->upvalue[idx-1] : NONVALIDVALUE;+ }+ }+}+++/*+** to be called by 'lua_checkstack' in protected mode, to grow stack+** capturing memory errors+*/+static void growstack (lua_State *L, void *ud) {+ int size = *(int *)ud;+ luaD_growstack(L, size);+}+++LUA_API int lua_checkstack (lua_State *L, int size) {+ int res;+ CallInfo *ci = L->ci;+ lua_lock(L);+ if (L->stack_last - L->top > size) /* stack large enough? */+ res = 1; /* yes; check is OK */+ else { /* no; need to grow stack */+ int inuse = cast_int(L->top - L->stack) + EXTRA_STACK;+ if (inuse > LUAI_MAXSTACK - size) /* can grow without overflow? */+ res = 0; /* no */+ else /* try to grow stack */+ res = (luaD_rawrunprotected(L, &growstack, &size) == LUA_OK);+ }+ if (res && ci->top < L->top + size)+ ci->top = L->top + size; /* adjust frame top */+ lua_unlock(L);+ return res;+}+++LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {+ int i;+ if (from == to) return;+ lua_lock(to);+ api_checknelems(from, n);+ api_check(from, G(from) == G(to), "moving among independent states");+ api_check(from, to->ci->top - to->top >= n, "not enough elements to move");+ from->top -= n;+ for (i = 0; i < n; i++) {+ setobj2s(to, to->top++, from->top + i);+ }+ lua_unlock(to);+}+++LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) {+ lua_CFunction old;+ lua_lock(L);+ old = G(L)->panic;+ G(L)->panic = panicf;+ lua_unlock(L);+ return old;+}+++LUA_API void lua_setpico8memory (lua_State *L, unsigned char const *p) {+ lua_lock(L);+ G(L)->pico8memory = p;+ lua_unlock(L);+}+++LUA_API const lua_Number *lua_version (lua_State *L) {+ static lua_Number version;+ version = LUA_VERSION_NUM;+ if (L == NULL) return &version;+ else return G(L)->version;+}++++/*+** basic stack manipulation+*/+++/*+** convert an acceptable stack index into an absolute index+*/+LUA_API int lua_absindex (lua_State *L, int idx) {+ return (idx > 0 || ispseudo(idx))+ ? idx+ : cast_int(L->top - L->ci->func + idx);+}+++LUA_API int lua_gettop (lua_State *L) {+ return cast_int(L->top - (L->ci->func + 1));+}+++LUA_API void lua_settop (lua_State *L, int idx) {+ StkId func = L->ci->func;+ lua_lock(L);+ if (idx >= 0) {+ api_check(L, idx <= L->stack_last - (func + 1), "new top too large");+ while (L->top < (func + 1) + idx)+ setnilvalue(L->top++);+ L->top = (func + 1) + idx;+ }+ else {+ api_check(L, -(idx+1) <= (L->top - (func + 1)), "invalid new top");+ L->top += idx+1; /* `subtract' index (index is negative) */+ }+ lua_unlock(L);+}+++LUA_API void lua_remove (lua_State *L, int idx) {+ StkId p;+ lua_lock(L);+ p = index2addr(L, idx);+ api_checkstackindex(L, idx, p);+ while (++p < L->top) setobjs2s(L, p-1, p);+ L->top--;+ lua_unlock(L);+}+++LUA_API void lua_insert (lua_State *L, int idx) {+ StkId p;+ StkId q;+ lua_lock(L);+ p = index2addr(L, idx);+ api_checkstackindex(L, idx, p);+ for (q = L->top; q > p; q--) /* use L->top as a temporary */+ setobjs2s(L, q, q - 1);+ setobjs2s(L, p, L->top);+ lua_unlock(L);+}+++static void moveto (lua_State *L, TValue *fr, int idx) {+ TValue *to = index2addr(L, idx);+ api_checkvalidindex(L, to);+ setobj(L, to, fr);+ if (idx < LUA_REGISTRYINDEX) /* function upvalue? */+ luaC_barrier(L, clCvalue(L->ci->func), fr);+ /* LUA_REGISTRYINDEX does not need gc barrier+ (collector revisits it before finishing collection) */+}+++LUA_API void lua_replace (lua_State *L, int idx) {+ lua_lock(L);+ api_checknelems(L, 1);+ moveto(L, L->top - 1, idx);+ L->top--;+ lua_unlock(L);+}+++LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) {+ TValue *fr;+ lua_lock(L);+ fr = index2addr(L, fromidx);+ moveto(L, fr, toidx);+ lua_unlock(L);+}+++LUA_API void lua_pushvalue (lua_State *L, int idx) {+ lua_lock(L);+ setobj2s(L, L->top, index2addr(L, idx));+ api_incr_top(L);+ lua_unlock(L);+}++++/*+** access functions (stack -> C)+*/+++LUA_API int lua_type (lua_State *L, int idx) {+ StkId o = index2addr(L, idx);+ return (isvalid(o) ? ttypenv(o) : LUA_TNONE);+}+++LUA_API const char *lua_typename (lua_State *L, int t) {+ UNUSED(L);+ return ttypename(t);+}+++LUA_API int lua_iscfunction (lua_State *L, int idx) {+ StkId o = index2addr(L, idx);+ return (ttislcf(o) || (ttisCclosure(o)));+}+++LUA_API int lua_isnumber (lua_State *L, int idx) {+ TValue n;+ const TValue *o = index2addr(L, idx);+ return tonumber(o, &n);+}+++LUA_API int lua_isstring (lua_State *L, int idx) {+ int t = lua_type(L, idx);+ return (t == LUA_TSTRING || t == LUA_TNUMBER);+}+++LUA_API int lua_isuserdata (lua_State *L, int idx) {+ const TValue *o = index2addr(L, idx);+ return (ttisuserdata(o) || ttislightuserdata(o));+}+++LUA_API int lua_rawequal (lua_State *L, int index1, int index2) {+ StkId o1 = index2addr(L, index1);+ StkId o2 = index2addr(L, index2);+ return (isvalid(o1) && isvalid(o2)) ? luaV_rawequalobj(o1, o2) : 0;+}+++LUA_API void lua_arith (lua_State *L, int op) {+ StkId o1; /* 1st operand */+ StkId o2; /* 2nd operand */+ lua_lock(L);+ if (op != LUA_OPUNM && op != LUA_OPBNOT && op != LUA_OPPEEK &&+ op != LUA_OPPEEK2 && op != LUA_OPPEEK4) /* all other operations expect two operands */+ api_checknelems(L, 2);+ else { /* for unary minus, add fake 2nd operand */+ api_checknelems(L, 1);+ setobjs2s(L, L->top, L->top - 1);+ L->top++;+ }+ o1 = L->top - 2;+ o2 = L->top - 1;+ if (ttisnumber(o1) && ttisnumber(o2)) {+ setnvalue(o1, luaO_arith(L, op, nvalue(o1), nvalue(o2)));+ }+ else+ luaV_arith(L, o1, o1, o2, cast(TMS, op - LUA_OPADD + TM_ADD));+ L->top--;+ lua_unlock(L);+}+++LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) {+ StkId o1, o2;+ int i = 0;+ lua_lock(L); /* may call tag method */+ o1 = index2addr(L, index1);+ o2 = index2addr(L, index2);+ if (isvalid(o1) && isvalid(o2)) {+ switch (op) {+ case LUA_OPEQ: i = equalobj(L, o1, o2); break;+ case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break;+ case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break;+ default: api_check(L, 0, "invalid option");+ }+ }+ lua_unlock(L);+ return i;+}+++LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *isnum) {+ TValue n;+ const TValue *o = index2addr(L, idx);+ if (tonumber(o, &n)) {+ if (isnum) *isnum = 1;+ return nvalue(o);+ }+ else {+ if (isnum) *isnum = 0;+ return 0;+ }+}+++LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *isnum) {+ TValue n;+ const TValue *o = index2addr(L, idx);+ if (tonumber(o, &n)) {+ lua_Integer res;+ lua_Number num = nvalue(o);+ lua_number2integer(res, num);+ if (isnum) *isnum = 1;+ return res;+ }+ else {+ if (isnum) *isnum = 0;+ return 0;+ }+}+++LUA_API lua_Unsigned lua_tounsignedx (lua_State *L, int idx, int *isnum) {+ TValue n;+ const TValue *o = index2addr(L, idx);+ if (tonumber(o, &n)) {+ lua_Unsigned res;+ lua_Number num = nvalue(o);+ lua_number2unsigned(res, num);+ if (isnum) *isnum = 1;+ return res;+ }+ else {+ if (isnum) *isnum = 0;+ return 0;+ }+}+++LUA_API int lua_toboolean (lua_State *L, int idx) {+ const TValue *o = index2addr(L, idx);+ return !l_isfalse(o);+}+++LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {+ StkId o = index2addr(L, idx);+ if (!ttisstring(o)) {+ lua_lock(L); /* `luaV_tostring' may create a new string */+ if (!luaV_tostring(L, o)) { /* conversion failed? */+ if (len != NULL) *len = 0;+ lua_unlock(L);+ return NULL;+ }+ luaC_checkGC(L);+ o = index2addr(L, idx); /* previous call may reallocate the stack */+ lua_unlock(L);+ }+ if (len != NULL) *len = tsvalue(o)->len;+ return svalue(o);+}+++LUA_API size_t lua_rawlen (lua_State *L, int idx) {+ StkId o = index2addr(L, idx);+ switch (ttypenv(o)) {+ case LUA_TSTRING: return tsvalue(o)->len;+ case LUA_TUSERDATA: return uvalue(o)->len;+ case LUA_TTABLE: return luaH_getn(hvalue(o));+ default: return 0;+ }+}+++LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {+ StkId o = index2addr(L, idx);+ if (ttislcf(o)) return fvalue(o);+ else if (ttisCclosure(o))+ return clCvalue(o)->f;+ else return NULL; /* not a C function */+}+++LUA_API void *lua_touserdata (lua_State *L, int idx) {+ StkId o = index2addr(L, idx);+ switch (ttypenv(o)) {+ case LUA_TUSERDATA: return (rawuvalue(o) + 1);+ case LUA_TLIGHTUSERDATA: return pvalue(o);+ default: return NULL;+ }+}+++LUA_API lua_State *lua_tothread (lua_State *L, int idx) {+ StkId o = index2addr(L, idx);+ return (!ttisthread(o)) ? NULL : thvalue(o);+}+++LUA_API const void *lua_topointer (lua_State *L, int idx) {+ StkId o = index2addr(L, idx);+ switch (ttype(o)) {+ case LUA_TTABLE: return hvalue(o);+ case LUA_TLCL: return clLvalue(o);+ case LUA_TCCL: return clCvalue(o);+ case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o)));+ case LUA_TTHREAD: return thvalue(o);+ case LUA_TUSERDATA:+ case LUA_TLIGHTUSERDATA:+ return lua_touserdata(L, idx);+ default: return NULL;+ }+}++++/*+** push functions (C -> stack)+*/+++LUA_API void lua_pushnil (lua_State *L) {+ lua_lock(L);+ setnilvalue(L->top);+ api_incr_top(L);+ lua_unlock(L);+}+++LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {+ lua_lock(L);+ setnvalue(L->top, n);+ luai_checknum(L, L->top,+ luaG_runerror(L, "C API - attempt to push a signaling NaN"));+ api_incr_top(L);+ lua_unlock(L);+}+++LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {+ lua_lock(L);+ setnvalue(L->top, cast_num(n));+ api_incr_top(L);+ lua_unlock(L);+}+++LUA_API void lua_pushunsigned (lua_State *L, lua_Unsigned u) {+ lua_Number n;+ lua_lock(L);+ n = lua_unsigned2number(u);+ setnvalue(L->top, n);+ api_incr_top(L);+ lua_unlock(L);+}+++LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) {+ TString *ts;+ lua_lock(L);+ luaC_checkGC(L);+ ts = luaS_newlstr(L, s, len);+ setsvalue2s(L, L->top, ts);+ api_incr_top(L);+ lua_unlock(L);+ return getstr(ts);+}+++LUA_API const char *lua_pushstring (lua_State *L, const char *s) {+ if (s == NULL) {+ lua_pushnil(L);+ return NULL;+ }+ else {+ TString *ts;+ lua_lock(L);+ luaC_checkGC(L);+ ts = luaS_new(L, s);+ setsvalue2s(L, L->top, ts);+ api_incr_top(L);+ lua_unlock(L);+ return getstr(ts);+ }+}+++LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt,+ va_list argp) {+ const char *ret;+ lua_lock(L);+ luaC_checkGC(L);+ ret = luaO_pushvfstring(L, fmt, argp);+ lua_unlock(L);+ return ret;+}+++LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) {+ const char *ret;+ va_list argp;+ lua_lock(L);+ luaC_checkGC(L);+ va_start(argp, fmt);+ ret = luaO_pushvfstring(L, fmt, argp);+ va_end(argp);+ lua_unlock(L);+ return ret;+}+++LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {+ lua_lock(L);+ if (n == 0) {+ setfvalue(L->top, fn);+ }+ else {+ Closure *cl;+ api_checknelems(L, n);+ api_check(L, n <= MAXUPVAL, "upvalue index too large");+ luaC_checkGC(L);+ cl = luaF_newCclosure(L, n);+ cl->c.f = fn;+ L->top -= n;+ while (n--)+ setobj2n(L, &cl->c.upvalue[n], L->top + n);+ setclCvalue(L, L->top, cl);+ }+ api_incr_top(L);+ lua_unlock(L);+}+++LUA_API void lua_pushboolean (lua_State *L, int b) {+ lua_lock(L);+ setbvalue(L->top, (b != 0)); /* ensure that true is 1 */+ api_incr_top(L);+ lua_unlock(L);+}+++LUA_API void lua_pushlightuserdata (lua_State *L, void *p) {+ lua_lock(L);+ setpvalue(L->top, p);+ api_incr_top(L);+ lua_unlock(L);+}+++LUA_API int lua_pushthread (lua_State *L) {+ lua_lock(L);+ setthvalue(L, L->top, L);+ api_incr_top(L);+ lua_unlock(L);+ return (G(L)->mainthread == L);+}++++/*+** get functions (Lua -> stack)+*/+++LUA_API void lua_getglobal (lua_State *L, const char *var) {+ Table *reg = hvalue(&G(L)->l_registry);+ const TValue *gt; /* global table */+ lua_lock(L);+ gt = luaH_getint(reg, LUA_RIDX_GLOBALS);+ setsvalue2s(L, L->top++, luaS_new(L, var));+ luaV_gettable(L, gt, L->top - 1, L->top - 1);+ lua_unlock(L);+}+++LUA_API void lua_gettable (lua_State *L, int idx) {+ StkId t;+ lua_lock(L);+ t = index2addr(L, idx);+ luaV_gettable(L, t, L->top - 1, L->top - 1);+ lua_unlock(L);+}+++LUA_API void lua_getfield (lua_State *L, int idx, const char *k) {+ StkId t;+ lua_lock(L);+ t = index2addr(L, idx);+ setsvalue2s(L, L->top, luaS_new(L, k));+ api_incr_top(L);+ luaV_gettable(L, t, L->top - 1, L->top - 1);+ lua_unlock(L);+}+++LUA_API void lua_rawget (lua_State *L, int idx) {+ StkId t;+ lua_lock(L);+ t = index2addr(L, idx);+ api_check(L, ttistable(t), "table expected");+ setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1));+ lua_unlock(L);+}+++LUA_API void lua_rawgeti (lua_State *L, int idx, int n) {+ StkId t;+ lua_lock(L);+ t = index2addr(L, idx);+ api_check(L, ttistable(t), "table expected");+ setobj2s(L, L->top, luaH_getint(hvalue(t), n));+ api_incr_top(L);+ lua_unlock(L);+}+++LUA_API void lua_rawgetp (lua_State *L, int idx, const void *p) {+ StkId t;+ TValue k;+ lua_lock(L);+ t = index2addr(L, idx);+ api_check(L, ttistable(t), "table expected");+ setpvalue(&k, cast(void *, p));+ setobj2s(L, L->top, luaH_get(hvalue(t), &k));+ api_incr_top(L);+ lua_unlock(L);+}+++LUA_API void lua_createtable (lua_State *L, int narray, int nrec) {+ Table *t;+ lua_lock(L);+ luaC_checkGC(L);+ t = luaH_new(L);+ sethvalue(L, L->top, t);+ api_incr_top(L);+ if (narray > 0 || nrec > 0)+ luaH_resize(L, t, narray, nrec);+ lua_unlock(L);+}+++LUA_API int lua_getmetatable (lua_State *L, int objindex) {+ const TValue *obj;+ Table *mt = NULL;+ int res;+ lua_lock(L);+ obj = index2addr(L, objindex);+ switch (ttypenv(obj)) {+ case LUA_TTABLE:+ mt = hvalue(obj)->metatable;+ break;+ case LUA_TUSERDATA:+ mt = uvalue(obj)->metatable;+ break;+ default:+ mt = G(L)->mt[ttypenv(obj)];+ break;+ }+ if (mt == NULL)+ res = 0;+ else {+ sethvalue(L, L->top, mt);+ api_incr_top(L);+ res = 1;+ }+ lua_unlock(L);+ return res;+}+++LUA_API void lua_getuservalue (lua_State *L, int idx) {+ StkId o;+ lua_lock(L);+ o = index2addr(L, idx);+ api_check(L, ttisuserdata(o), "userdata expected");+ if (uvalue(o)->env) {+ sethvalue(L, L->top, uvalue(o)->env);+ } else+ setnilvalue(L->top);+ api_incr_top(L);+ lua_unlock(L);+}+++/*+** set functions (stack -> Lua)+*/+++LUA_API void lua_setglobal (lua_State *L, const char *var) {+ Table *reg = hvalue(&G(L)->l_registry);+ const TValue *gt; /* global table */+ lua_lock(L);+ api_checknelems(L, 1);+ gt = luaH_getint(reg, LUA_RIDX_GLOBALS);+ setsvalue2s(L, L->top++, luaS_new(L, var));+ luaV_settable(L, gt, L->top - 1, L->top - 2);+ L->top -= 2; /* pop value and key */+ lua_unlock(L);+}+++LUA_API void lua_settable (lua_State *L, int idx) {+ StkId t;+ lua_lock(L);+ api_checknelems(L, 2);+ t = index2addr(L, idx);+ luaV_settable(L, t, L->top - 2, L->top - 1);+ L->top -= 2; /* pop index and value */+ lua_unlock(L);+}+++LUA_API void lua_setfield (lua_State *L, int idx, const char *k) {+ StkId t;+ lua_lock(L);+ api_checknelems(L, 1);+ t = index2addr(L, idx);+ setsvalue2s(L, L->top++, luaS_new(L, k));+ luaV_settable(L, t, L->top - 1, L->top - 2);+ L->top -= 2; /* pop value and key */+ lua_unlock(L);+}+++LUA_API void lua_rawset (lua_State *L, int idx) {+ StkId t;+ lua_lock(L);+ api_checknelems(L, 2);+ t = index2addr(L, idx);+ api_check(L, ttistable(t), "table expected");+ setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1);+ invalidateTMcache(hvalue(t));+ luaC_barrierback(L, gcvalue(t), L->top-1);+ L->top -= 2;+ lua_unlock(L);+}+++LUA_API void lua_rawseti (lua_State *L, int idx, int n) {+ StkId t;+ lua_lock(L);+ api_checknelems(L, 1);+ t = index2addr(L, idx);+ api_check(L, ttistable(t), "table expected");+ luaH_setint(L, hvalue(t), n, L->top - 1);+ luaC_barrierback(L, gcvalue(t), L->top-1);+ L->top--;+ lua_unlock(L);+}+++LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {+ StkId t;+ TValue k;+ lua_lock(L);+ api_checknelems(L, 1);+ t = index2addr(L, idx);+ api_check(L, ttistable(t), "table expected");+ setpvalue(&k, cast(void *, p));+ setobj2t(L, luaH_set(L, hvalue(t), &k), L->top - 1);+ luaC_barrierback(L, gcvalue(t), L->top - 1);+ L->top--;+ lua_unlock(L);+}+++LUA_API int lua_setmetatable (lua_State *L, int objindex) {+ TValue *obj;+ Table *mt;+ lua_lock(L);+ api_checknelems(L, 1);+ obj = index2addr(L, objindex);+ if (ttisnil(L->top - 1))+ mt = NULL;+ else {+ api_check(L, ttistable(L->top - 1), "table expected");+ mt = hvalue(L->top - 1);+ }+ switch (ttypenv(obj)) {+ case LUA_TTABLE: {+ hvalue(obj)->metatable = mt;+ if (mt) {+ luaC_objbarrierback(L, gcvalue(obj), mt);+ luaC_checkfinalizer(L, gcvalue(obj), mt);+ }+ break;+ }+ case LUA_TUSERDATA: {+ uvalue(obj)->metatable = mt;+ if (mt) {+ luaC_objbarrier(L, rawuvalue(obj), mt);+ luaC_checkfinalizer(L, gcvalue(obj), mt);+ }+ break;+ }+ default: {+ G(L)->mt[ttypenv(obj)] = mt;+ break;+ }+ }+ L->top--;+ lua_unlock(L);+ return 1;+}+++LUA_API void lua_setuservalue (lua_State *L, int idx) {+ StkId o;+ lua_lock(L);+ api_checknelems(L, 1);+ o = index2addr(L, idx);+ api_check(L, ttisuserdata(o), "userdata expected");+ if (ttisnil(L->top - 1))+ uvalue(o)->env = NULL;+ else {+ api_check(L, ttistable(L->top - 1), "table expected");+ uvalue(o)->env = hvalue(L->top - 1);+ luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1));+ }+ L->top--;+ lua_unlock(L);+}+++/*+** `load' and `call' functions (run Lua code)+*/+++#define checkresults(L,na,nr) \+ api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \+ "results from function overflow current stack size")+++LUA_API int lua_getctx (lua_State *L, int *ctx) {+ if (L->ci->callstatus & CIST_YIELDED) {+ if (ctx) *ctx = L->ci->u.c.ctx;+ return L->ci->u.c.status;+ }+ else return LUA_OK;+}+++LUA_API void lua_callk (lua_State *L, int nargs, int nresults, int ctx,+ lua_CFunction k) {+ StkId func;+ lua_lock(L);+ api_check(L, k == NULL || !isLua(L->ci),+ "cannot use continuations inside hooks");+ api_checknelems(L, nargs+1);+ api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");+ checkresults(L, nargs, nresults);+ func = L->top - (nargs+1);+ if (k != NULL && L->nny == 0) { /* need to prepare continuation? */+ L->ci->u.c.k = k; /* save continuation */+ L->ci->u.c.ctx = ctx; /* save context */+ luaD_call(L, func, nresults, 1); /* do the call */+ }+ else /* no continuation or no yieldable */+ luaD_call(L, func, nresults, 0); /* just do the call */+ adjustresults(L, nresults);+ lua_unlock(L);+}++++/*+** Execute a protected call.+*/+struct CallS { /* data to `f_call' */+ StkId func;+ int nresults;+};+++static void f_call (lua_State *L, void *ud) {+ struct CallS *c = cast(struct CallS *, ud);+ luaD_call(L, c->func, c->nresults, 0);+}++++LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc,+ int ctx, lua_CFunction k) {+ struct CallS c;+ int status;+ ptrdiff_t func;+ lua_lock(L);+ api_check(L, k == NULL || !isLua(L->ci),+ "cannot use continuations inside hooks");+ api_checknelems(L, nargs+1);+ api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");+ checkresults(L, nargs, nresults);+ if (errfunc == 0)+ func = 0;+ else {+ StkId o = index2addr(L, errfunc);+ api_checkstackindex(L, errfunc, o);+ func = savestack(L, o);+ }+ c.func = L->top - (nargs+1); /* function to be called */+ if (k == NULL || L->nny > 0) { /* no continuation or no yieldable? */+ c.nresults = nresults; /* do a 'conventional' protected call */+ status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);+ }+ else { /* prepare continuation (call is already protected by 'resume') */+ CallInfo *ci = L->ci;+ ci->u.c.k = k; /* save continuation */+ ci->u.c.ctx = ctx; /* save context */+ /* save information for error recovery */+ ci->extra = savestack(L, c.func);+ ci->u.c.old_allowhook = L->allowhook;+ ci->u.c.old_errfunc = L->errfunc;+ L->errfunc = func;+ /* mark that function may do error recovery */+ ci->callstatus |= CIST_YPCALL;+ luaD_call(L, c.func, nresults, 1); /* do the call */+ ci->callstatus &= ~CIST_YPCALL;+ L->errfunc = ci->u.c.old_errfunc;+ status = LUA_OK; /* if it is here, there were no errors */+ }+ adjustresults(L, nresults);+ lua_unlock(L);+ return status;+}+++LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,+ const char *chunkname, const char *mode) {+ ZIO z;+ int status;+ lua_lock(L);+ if (!chunkname) chunkname = "?";+ luaZ_init(L, &z, reader, data);+ status = luaD_protectedparser(L, &z, chunkname, mode);+ if (status == LUA_OK) { /* no errors? */+ LClosure *f = clLvalue(L->top - 1); /* get newly created function */+ if (f->nupvalues == 1) { /* does it have one upvalue? */+ /* get global table from registry */+ Table *reg = hvalue(&G(L)->l_registry);+ const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);+ /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */+ setobj(L, f->upvals[0]->v, gt);+ luaC_barrier(L, f->upvals[0], gt);+ }+ }+ lua_unlock(L);+ return status;+}+++LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) {+ int status;+ TValue *o;+ lua_lock(L);+ api_checknelems(L, 1);+ o = L->top - 1;+ (void)o; (void)writer; (void)data;+ status = 1; /* (NumPico: no luaU_dump) */+ lua_unlock(L);+ return status;+}+++LUA_API int lua_status (lua_State *L) {+ return L->status;+}+++/*+** Garbage-collection function+*/++LUA_API int lua_gc (lua_State *L, int what, int data) {+ int res = 0;+ global_State *g;+ lua_lock(L);+ g = G(L);+ switch (what) {+ case LUA_GCSTOP: {+ g->gcrunning = 0;+ break;+ }+ case LUA_GCRESTART: {+ luaE_setdebt(g, 0);+ g->gcrunning = 1;+ break;+ }+ case LUA_GCCOLLECT: {+ luaC_fullgc(L, 0);+ break;+ }+ case LUA_GCCOUNT: {+ /* GC values are expressed in Kbytes: #bytes/2^10 */+ res = cast_int(gettotalbytes(g) >> 10);+ break;+ }+ case LUA_GCCOUNTB: {+ res = cast_int(gettotalbytes(g) & 0x3ff);+ break;+ }+ case LUA_GCSTEP: {+ if (g->gckind == KGC_GEN) { /* generational mode? */+ res = (g->GCestimate == 0); /* true if it will do major collection */+ luaC_forcestep(L); /* do a single step */+ }+ else {+ lu_mem debt = cast(lu_mem, data) * 1024 - GCSTEPSIZE;+ if (g->gcrunning)+ debt += g->GCdebt; /* include current debt */+ luaE_setdebt(g, debt);+ luaC_forcestep(L);+ if (g->gcstate == GCSpause) /* end of cycle? */+ res = 1; /* signal it */+ }+ break;+ }+ case LUA_GCSETPAUSE: {+ res = g->gcpause;+ g->gcpause = data;+ break;+ }+ case LUA_GCSETMAJORINC: {+ res = g->gcmajorinc;+ g->gcmajorinc = data;+ break;+ }+ case LUA_GCSETSTEPMUL: {+ res = g->gcstepmul;+ g->gcstepmul = data;+ break;+ }+ case LUA_GCISRUNNING: {+ res = g->gcrunning;+ break;+ }+ case LUA_GCGEN: { /* change collector to generational mode */+ luaC_changemode(L, KGC_GEN);+ break;+ }+ case LUA_GCINC: { /* change collector to incremental mode */+ luaC_changemode(L, KGC_NORMAL);+ break;+ }+ default: res = -1; /* invalid option */+ }+ lua_unlock(L);+ return res;+}++++/*+** miscellaneous functions+*/+++LUA_API int lua_error (lua_State *L) {+ lua_lock(L);+ api_checknelems(L, 1);+ luaG_errormsg(L);+ /* code unreachable; will unlock when control actually leaves the kernel */+ return 0; /* to avoid warnings */+}+++LUA_API int lua_next (lua_State *L, int idx) {+ StkId t;+ int more;+ lua_lock(L);+ t = index2addr(L, idx);+ api_check(L, ttistable(t), "table expected");+ more = luaH_next(L, hvalue(t), L->top - 1);+ if (more) {+ api_incr_top(L);+ }+ else /* no more elements */+ L->top -= 1; /* remove key */+ lua_unlock(L);+ return more;+}+++LUA_API void lua_concat (lua_State *L, int n) {+ lua_lock(L);+ api_checknelems(L, n);+ if (n >= 2) {+ luaC_checkGC(L);+ luaV_concat(L, n);+ }+ else if (n == 0) { /* push empty string */+ setsvalue2s(L, L->top, luaS_newlstr(L, "", 0));+ api_incr_top(L);+ }+ /* else n == 1; nothing to do */+ lua_unlock(L);+}+++LUA_API void lua_len (lua_State *L, int idx) {+ StkId t;+ lua_lock(L);+ t = index2addr(L, idx);+ luaV_objlen(L, L->top, t);+ api_incr_top(L);+ lua_unlock(L);+}+++LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) {+ lua_Alloc f;+ lua_lock(L);+ if (ud) *ud = G(L)->ud;+ f = G(L)->frealloc;+ lua_unlock(L);+ return f;+}+++LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) {+ lua_lock(L);+ G(L)->ud = ud;+ G(L)->frealloc = f;+ lua_unlock(L);+}+++LUA_API void *lua_newuserdata (lua_State *L, size_t size) {+ Udata *u;+ lua_lock(L);+ luaC_checkGC(L);+ u = luaS_newudata(L, size, NULL);+ setuvalue(L, L->top, u);+ api_incr_top(L);+ lua_unlock(L);+ return u + 1;+}++++static const char *aux_upvalue (StkId fi, int n, TValue **val,+ GCObject **owner) {+ switch (ttype(fi)) {+ case LUA_TCCL: { /* C closure */+ CClosure *f = clCvalue(fi);+ if (!(1 <= n && n <= f->nupvalues)) return NULL;+ *val = &f->upvalue[n-1];+ if (owner) *owner = obj2gco(f);+ return "";+ }+ case LUA_TLCL: { /* Lua closure */+ LClosure *f = clLvalue(fi);+ TString *name;+ Proto *p = f->p;+ if (!(1 <= n && n <= p->sizeupvalues)) return NULL;+ *val = f->upvals[n-1]->v;+ if (owner) *owner = obj2gco(f->upvals[n - 1]);+ name = p->upvalues[n-1].name;+ return (name == NULL) ? "" : getstr(name);+ }+ default: return NULL; /* not a closure */+ }+}+++LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {+ const char *name;+ TValue *val = NULL; /* to avoid warnings */+ lua_lock(L);+ name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL);+ if (name) {+ setobj2s(L, L->top, val);+ api_incr_top(L);+ }+ lua_unlock(L);+ return name;+}+++LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {+ const char *name;+ TValue *val = NULL; /* to avoid warnings */+ GCObject *owner = NULL; /* to avoid warnings */+ StkId fi;+ lua_lock(L);+ fi = index2addr(L, funcindex);+ api_checknelems(L, 1);+ name = aux_upvalue(fi, n, &val, &owner);+ if (name) {+ L->top--;+ setobj(L, val, L->top);+ luaC_barrier(L, owner, L->top);+ }+ lua_unlock(L);+ return name;+}+++static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {+ LClosure *f;+ StkId fi = index2addr(L, fidx);+ api_check(L, ttisLclosure(fi), "Lua function expected");+ f = clLvalue(fi);+ api_check(L, (1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index");+ if (pf) *pf = f;+ return &f->upvals[n - 1]; /* get its upvalue pointer */+}+++LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {+ StkId fi = index2addr(L, fidx);+ switch (ttype(fi)) {+ case LUA_TLCL: { /* lua closure */+ return *getupvalref(L, fidx, n, NULL);+ }+ case LUA_TCCL: { /* C closure */+ CClosure *f = clCvalue(fi);+ api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index");+ return &f->upvalue[n - 1];+ }+ default: {+ api_check(L, 0, "closure expected");+ return NULL;+ }+ }+}+++LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1,+ int fidx2, int n2) {+ LClosure *f1;+ UpVal **up1 = getupvalref(L, fidx1, n1, &f1);+ UpVal **up2 = getupvalref(L, fidx2, n2, NULL);+ *up1 = *up2;+ luaC_objbarrier(L, f1, *up2);+}+diff --git a/games/numpico/src/femto8/lua/lapi.h b/games/numpico/src/femto8/lua/lapi.hnew file mode 100644index 00000000..0909a391--- /dev/null+++ b/games/numpico/src/femto8/lua/lapi.h@@ -0,0 +1,24 @@+/*+** $Id: lapi.h,v 2.7 2009/11/27 15:37:59 roberto Exp $+** Auxiliary functions from Lua API+** See Copyright Notice in lua.h+*/++#ifndef lapi_h+#define lapi_h+++#include "llimits.h"+#include "lstate.h"++#define api_incr_top(L) {L->top++; api_check(L, L->top <= L->ci->top, \+ "stack overflow");}++#define adjustresults(L,nres) \+ { if ((nres) == LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; }++#define api_checknelems(L,n) api_check(L, (n) < (L->top - L->ci->func), \+ "not enough elements in the stack")+++#endifdiff --git a/games/numpico/src/femto8/lua/lauxlib.c b/games/numpico/src/femto8/lua/lauxlib.cnew file mode 100644index 00000000..39aa5987--- /dev/null+++ b/games/numpico/src/femto8/lua/lauxlib.c@@ -0,0 +1,781 @@+/*+** $Id: lauxlib.c,v 1.248 2013/03/21 13:54:57 roberto Exp $+** Auxiliary functions for building Lua libraries+** See Copyright Notice in lua.h+** Changed for NumPico: no files, no stdio, no malloc (see the notes below).+*/+++#include <errno.h>+#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+++/* This file uses only the official API of Lua.+** Any function declared here could be written as an application function.+*/++#define lauxlib_c+#define LUA_LIB++#include "lua.h"++#include "lauxlib.h"+++/*+** {======================================================+** Traceback+** =======================================================+*/+++#define LEVELS1 12 /* size of the first part of the stack */+#define LEVELS2 10 /* size of the second part of the stack */++++/*+** search for 'objidx' in table at index -1.+** return 1 + string at top if find a good name.+*/+static int findfield (lua_State *L, int objidx, int level) {+ if (level == 0 || !lua_istable(L, -1))+ return 0; /* not found */+ lua_pushnil(L); /* start 'next' loop */+ while (lua_next(L, -2)) { /* for each pair in table */+ if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */+ if (lua_rawequal(L, objidx, -1)) { /* found object? */+ lua_pop(L, 1); /* remove value (but keep name) */+ return 1;+ }+ else if (findfield(L, objidx, level - 1)) { /* try recursively */+ lua_remove(L, -2); /* remove table (but keep name) */+ lua_pushliteral(L, ".");+ lua_insert(L, -2); /* place '.' between the two names */+ lua_concat(L, 3);+ return 1;+ }+ }+ lua_pop(L, 1); /* remove value */+ }+ return 0; /* not found */+}+++static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {+ int top = lua_gettop(L);+ lua_getinfo(L, "f", ar); /* push function */+ lua_pushglobaltable(L);+ if (findfield(L, top + 1, 2)) {+ lua_copy(L, -1, top + 1); /* move name to proper place */+ lua_pop(L, 2); /* remove pushed values */+ return 1;+ }+ else {+ lua_settop(L, top); /* remove function and global table */+ return 0;+ }+}+++static void pushfuncname (lua_State *L, lua_Debug *ar) {+ if (*ar->namewhat != '\0') /* is there a name? */+ lua_pushfstring(L, "function " LUA_QS, ar->name);+ else if (*ar->what == 'm') /* main? */+ lua_pushliteral(L, "main chunk");+ else if (*ar->what == 'C') {+ if (pushglobalfuncname(L, ar)) {+ lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1));+ lua_remove(L, -2); /* remove name */+ }+ else+ lua_pushliteral(L, "?");+ }+ else+ lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);+}+++static int countlevels (lua_State *L) {+ lua_Debug ar;+ int li = 1, le = 1;+ /* find an upper bound */+ while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }+ /* do a binary search */+ while (li < le) {+ int m = (li + le)/2;+ if (lua_getstack(L, m, &ar)) li = m + 1;+ else le = m;+ }+ return le - 1;+}+++LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,+ const char *msg, int level) {+ lua_Debug ar;+ int top = lua_gettop(L);+ int numlevels = countlevels(L1);+ int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0;+ if (msg) lua_pushfstring(L, "%s\n", msg);+ lua_pushliteral(L, "stack traceback:");+ while (lua_getstack(L1, level++, &ar)) {+ if (level == mark) { /* too many levels? */+ lua_pushliteral(L, "\n\t..."); /* add a '...' */+ level = numlevels - LEVELS2; /* and skip to last ones */+ }+ else {+ lua_getinfo(L1, "Slnt", &ar);+ lua_pushfstring(L, "\n\t%s:", ar.short_src);+ if (ar.currentline > 0)+ lua_pushfstring(L, "%d:", ar.currentline);+ lua_pushliteral(L, " in ");+ pushfuncname(L, &ar);+ if (ar.istailcall)+ lua_pushliteral(L, "\n\t(...tail calls...)");+ lua_concat(L, lua_gettop(L) - top);+ }+ }+ lua_concat(L, lua_gettop(L) - top);+}++/* }====================================================== */+++/*+** {======================================================+** Error-report functions+** =======================================================+*/++LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {+ lua_Debug ar;+ if (!lua_getstack(L, 0, &ar)) /* no stack frame? */+ return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);+ lua_getinfo(L, "n", &ar);+ if (strcmp(ar.namewhat, "method") == 0) {+ narg--; /* do not count `self' */+ if (narg == 0) /* error is in the self argument itself? */+ return luaL_error(L, "calling " LUA_QS " on bad self (%s)",+ ar.name, extramsg);+ }+ if (ar.name == NULL)+ ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";+ return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",+ narg, ar.name, extramsg);+}+++static int typeerror (lua_State *L, int narg, const char *tname) {+ const char *msg = lua_pushfstring(L, "%s expected, got %s",+ tname, luaL_typename(L, narg));+ return luaL_argerror(L, narg, msg);+}+++static void tag_error (lua_State *L, int narg, int tag) {+ typeerror(L, narg, lua_typename(L, tag));+}+++LUALIB_API void luaL_where (lua_State *L, int level) {+ lua_Debug ar;+ if (lua_getstack(L, level, &ar)) { /* check function at level */+ lua_getinfo(L, "Sl", &ar); /* get info about it */+ if (ar.currentline > 0) { /* is there info? */+ lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);+ return;+ }+ }+ lua_pushliteral(L, ""); /* else, no information available... */+}+++LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {+ va_list argp;+ va_start(argp, fmt);+ luaL_where(L, 1);+ lua_pushvfstring(L, fmt, argp);+ va_end(argp);+ lua_concat(L, 2);+ return lua_error(L);+}+++/* (NumPico: luaL_fileresult and luaL_execresult left out: no files, no programs to run) */+++/*+** {======================================================+** Userdata's metatable manipulation+** =======================================================+*/++LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {+ luaL_getmetatable(L, tname); /* try to get metatable */+ if (!lua_isnil(L, -1)) /* name already in use? */+ return 0; /* leave previous value on top, but return 0 */+ lua_pop(L, 1);+ lua_newtable(L); /* create metatable */+ lua_pushvalue(L, -1);+ lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */+ return 1;+}+++LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {+ luaL_getmetatable(L, tname);+ lua_setmetatable(L, -2);+}+++LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {+ void *p = lua_touserdata(L, ud);+ if (p != NULL) { /* value is a userdata? */+ if (lua_getmetatable(L, ud)) { /* does it have a metatable? */+ luaL_getmetatable(L, tname); /* get correct metatable */+ if (!lua_rawequal(L, -1, -2)) /* not the same? */+ p = NULL; /* value is a userdata with wrong metatable */+ lua_pop(L, 2); /* remove both metatables */+ return p;+ }+ }+ return NULL; /* value is not a userdata with a metatable */+}+++LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {+ void *p = luaL_testudata(L, ud, tname);+ if (p == NULL) typeerror(L, ud, tname);+ return p;+}++/* }====================================================== */+++/*+** {======================================================+** Argument check functions+** =======================================================+*/++LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,+ const char *const lst[]) {+ const char *name = (def) ? luaL_optstring(L, narg, def) :+ luaL_checkstring(L, narg);+ int i;+ for (i=0; lst[i]; i++)+ if (strcmp(lst[i], name) == 0)+ return i;+ return luaL_argerror(L, narg,+ lua_pushfstring(L, "invalid option " LUA_QS, name));+}+++LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {+ /* keep some extra space to run error routines, if needed */+ const int extra = LUA_MINSTACK;+ if (!lua_checkstack(L, space + extra)) {+ if (msg)+ luaL_error(L, "stack overflow (%s)", msg);+ else+ luaL_error(L, "stack overflow");+ }+}+++LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {+ if (lua_type(L, narg) != t)+ tag_error(L, narg, t);+}+++LUALIB_API void luaL_checkany (lua_State *L, int narg) {+ if (lua_type(L, narg) == LUA_TNONE)+ luaL_argerror(L, narg, "value expected");+}+++LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {+ const char *s = lua_tolstring(L, narg, len);+ if (!s) tag_error(L, narg, LUA_TSTRING);+ return s;+}+++LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,+ const char *def, size_t *len) {+ if (lua_isnoneornil(L, narg)) {+ if (len)+ *len = (def ? strlen(def) : 0);+ return def;+ }+ else return luaL_checklstring(L, narg, len);+}+++LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {+ int isnum;+ lua_Number d = lua_tonumberx(L, narg, &isnum);+ if (!isnum)+ tag_error(L, narg, LUA_TNUMBER);+ return d;+}+++LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {+ return luaL_opt(L, luaL_checknumber, narg, def);+}+++LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {+ int isnum;+ lua_Integer d = lua_tointegerx(L, narg, &isnum);+ if (!isnum)+ tag_error(L, narg, LUA_TNUMBER);+ return d;+}+++LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int narg) {+ int isnum;+ lua_Unsigned d = lua_tounsignedx(L, narg, &isnum);+ if (!isnum)+ tag_error(L, narg, LUA_TNUMBER);+ return d;+}+++LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,+ lua_Integer def) {+ return luaL_opt(L, luaL_checkinteger, narg, def);+}+++LUALIB_API lua_Unsigned luaL_optunsigned (lua_State *L, int narg,+ lua_Unsigned def) {+ return luaL_opt(L, luaL_checkunsigned, narg, def);+}++/* }====================================================== */+++/*+** {======================================================+** Generic Buffer manipulation+** =======================================================+*/++/*+** check whether buffer is using a userdata on the stack as a temporary+** buffer+*/+#define buffonstack(B) ((B)->b != (B)->initb)+++/*+** returns a pointer to a free area with at least 'sz' bytes+*/+LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {+ lua_State *L = B->L;+ if (B->size - B->n < sz) { /* not enough space? */+ char *newbuff;+ size_t newsize = B->size * 2; /* double buffer size */+ if (newsize - B->n < sz) /* not big enough? */+ newsize = B->n + sz;+ if (newsize < B->n || newsize - B->n < sz)+ luaL_error(L, "buffer too large");+ /* create larger buffer */+ newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char));+ /* move content to new buffer */+ memcpy(newbuff, B->b, B->n * sizeof(char));+ if (buffonstack(B))+ lua_remove(L, -2); /* remove old buffer */+ B->b = newbuff;+ B->size = newsize;+ }+ return &B->b[B->n];+}+++LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {+ char *b = luaL_prepbuffsize(B, l);+ memcpy(b, s, l * sizeof(char));+ luaL_addsize(B, l);+}+++LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {+ luaL_addlstring(B, s, strlen(s));+}+++LUALIB_API void luaL_pushresult (luaL_Buffer *B) {+ lua_State *L = B->L;+ lua_pushlstring(L, B->b, B->n);+ if (buffonstack(B))+ lua_remove(L, -2); /* remove old buffer */+}+++LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {+ luaL_addsize(B, sz);+ luaL_pushresult(B);+}+++LUALIB_API void luaL_addvalue (luaL_Buffer *B) {+ lua_State *L = B->L;+ size_t l;+ const char *s = lua_tolstring(L, -1, &l);+ if (buffonstack(B))+ lua_insert(L, -2); /* put value below buffer */+ luaL_addlstring(B, s, l);+ lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */+}+++LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {+ B->L = L;+ B->b = B->initb;+ B->n = 0;+ B->size = LUAL_BUFFERSIZE;+}+++LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {+ luaL_buffinit(L, B);+ return luaL_prepbuffsize(B, sz);+}++/* }====================================================== */+++/*+** {======================================================+** Reference system+** =======================================================+*/++/* index of free-list header */+#define freelist 0+++LUALIB_API int luaL_ref (lua_State *L, int t) {+ int ref;+ if (lua_isnil(L, -1)) {+ lua_pop(L, 1); /* remove from stack */+ return LUA_REFNIL; /* `nil' has a unique fixed reference */+ }+ t = lua_absindex(L, t);+ lua_rawgeti(L, t, freelist); /* get first free element */+ ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */+ lua_pop(L, 1); /* remove it from stack */+ if (ref != 0) { /* any free element? */+ lua_rawgeti(L, t, ref); /* remove it from list */+ lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */+ }+ else /* no free elements */+ ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */+ lua_rawseti(L, t, ref);+ return ref;+}+++LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {+ if (ref >= 0) {+ t = lua_absindex(L, t);+ lua_rawgeti(L, t, freelist);+ lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */+ lua_pushinteger(L, ref);+ lua_rawseti(L, t, freelist); /* t[freelist] = ref */+ }+}++/* }====================================================== */+++/*+** {======================================================+** Load functions+** =======================================================+*/++/* (NumPico: luaL_loadfilex left out: no files) */+++typedef struct LoadS {+ const char *s;+ size_t size;+} LoadS;+++static const char *getS (lua_State *L, void *ud, size_t *size) {+ LoadS *ls = (LoadS *)ud;+ (void)L; /* not used */+ if (ls->size == 0) return NULL;+ *size = ls->size;+ ls->size = 0;+ return ls->s;+}+++LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,+ const char *name, const char *mode) {+ LoadS ls;+ ls.s = buff;+ ls.size = size;+ return lua_load(L, getS, &ls, name, mode);+}+++LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {+ return luaL_loadbuffer(L, s, strlen(s), s);+}++/* }====================================================== */++++LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {+ if (!lua_getmetatable(L, obj)) /* no metatable? */+ return 0;+ lua_pushstring(L, event);+ lua_rawget(L, -2);+ if (lua_isnil(L, -1)) {+ lua_pop(L, 2); /* remove metatable and metafield */+ return 0;+ }+ else {+ lua_remove(L, -2); /* remove only metatable */+ return 1;+ }+}+++LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {+ obj = lua_absindex(L, obj);+ if (!luaL_getmetafield(L, obj, event)) /* no metafield? */+ return 0;+ lua_pushvalue(L, obj);+ lua_call(L, 1, 1);+ return 1;+}+++LUALIB_API int luaL_len (lua_State *L, int idx) {+ int l;+ int isnum;+ lua_len(L, idx);+ l = (int)lua_tointegerx(L, -1, &isnum);+ if (!isnum)+ luaL_error(L, "object length is not a number");+ lua_pop(L, 1); /* remove object */+ return l;+}+++LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {+ if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */+ switch (lua_type(L, idx)) {+ case LUA_TNUMBER:+ case LUA_TSTRING:+ lua_pushvalue(L, idx);+ break;+ case LUA_TBOOLEAN:+ lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));+ break;+ case LUA_TNIL:+ lua_pushliteral(L, "nil");+ break;+ default:+ lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),+ lua_topointer(L, idx));+ break;+ }+ }+ return lua_tolstring(L, -1, len);+}+++/*+** {======================================================+** Compatibility with 5.1 module functions+** =======================================================+*/+#if defined(LUA_COMPAT_MODULE)++static const char *luaL_findtable (lua_State *L, int idx,+ const char *fname, int szhint) {+ const char *e;+ if (idx) lua_pushvalue(L, idx);+ do {+ e = strchr(fname, '.');+ if (e == NULL) e = fname + strlen(fname);+ lua_pushlstring(L, fname, e - fname);+ lua_rawget(L, -2);+ if (lua_isnil(L, -1)) { /* no such field? */+ lua_pop(L, 1); /* remove this nil */+ lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */+ lua_pushlstring(L, fname, e - fname);+ lua_pushvalue(L, -2);+ lua_settable(L, -4); /* set new table into field */+ }+ else if (!lua_istable(L, -1)) { /* field has a non-table value? */+ lua_pop(L, 2); /* remove table and value */+ return fname; /* return problematic part of the name */+ }+ lua_remove(L, -2); /* remove previous table */+ fname = e + 1;+ } while (*e == '.');+ return NULL;+}+++/*+** Count number of elements in a luaL_Reg list.+*/+static int libsize (const luaL_Reg *l) {+ int size = 0;+ for (; l && l->name; l++) size++;+ return size;+}+++/*+** Find or create a module table with a given name. The function+** first looks at the _LOADED table and, if that fails, try a+** global variable with that name. In any case, leaves on the stack+** the module table.+*/+LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,+ int sizehint) {+ luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */+ lua_getfield(L, -1, modname); /* get _LOADED[modname] */+ if (!lua_istable(L, -1)) { /* not found? */+ lua_pop(L, 1); /* remove previous result */+ /* try global variable (and create one if it does not exist) */+ lua_pushglobaltable(L);+ if (luaL_findtable(L, 0, modname, sizehint) != NULL)+ luaL_error(L, "name conflict for module " LUA_QS, modname);+ lua_pushvalue(L, -1);+ lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */+ }+ lua_remove(L, -2); /* remove _LOADED table */+}+++LUALIB_API void luaL_openlib (lua_State *L, const char *libname,+ const luaL_Reg *l, int nup) {+ luaL_checkversion(L);+ if (libname) {+ luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */+ lua_insert(L, -(nup + 1)); /* move library table to below upvalues */+ }+ if (l)+ luaL_setfuncs(L, l, nup);+ else+ lua_pop(L, nup); /* remove upvalues */+}++#endif+/* }====================================================== */++/*+** set functions from list 'l' into table at top - 'nup'; each+** function gets the 'nup' elements at the top as upvalues.+** Returns with only the table at the stack.+*/+LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {+ luaL_checkversion(L);+ luaL_checkstack(L, nup, "too many upvalues");+ for (; l->name != NULL; l++) { /* fill the table with given functions */+ int i;+ for (i = 0; i < nup; i++) /* copy upvalues to the top */+ lua_pushvalue(L, -nup);+ lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */+ lua_setfield(L, -(nup + 2), l->name);+ }+ lua_pop(L, nup); /* remove upvalues */+}+++/*+** ensure that stack[idx][fname] has a table and push that table+** into the stack+*/+LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {+ lua_getfield(L, idx, fname);+ if (lua_istable(L, -1)) return 1; /* table already there */+ else {+ lua_pop(L, 1); /* remove previous result */+ idx = lua_absindex(L, idx);+ lua_newtable(L);+ lua_pushvalue(L, -1); /* copy to be left at top */+ lua_setfield(L, idx, fname); /* assign new table to field */+ return 0; /* false, because did not find table there */+ }+}+++/*+** stripped-down 'require'. Calls 'openf' to open a module,+** registers the result in 'package.loaded' table and, if 'glb'+** is true, also registers the result in the global table.+** Leaves resulting module on the top.+*/+LUALIB_API void luaL_requiref (lua_State *L, const char *modname,+ lua_CFunction openf, int glb) {+ lua_pushcfunction(L, openf);+ lua_pushstring(L, modname); /* argument to open function */+ lua_call(L, 1, 1); /* open module */+ luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");+ lua_pushvalue(L, -2); /* make copy of module (call result) */+ lua_setfield(L, -2, modname); /* _LOADED[modname] = module */+ lua_pop(L, 1); /* remove _LOADED table */+ if (glb) {+ lua_pushvalue(L, -1); /* copy of 'mod' */+ lua_setglobal(L, modname); /* _G[modname] = module */+ }+}+++LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,+ const char *r) {+ const char *wild;+ size_t l = strlen(p);+ luaL_Buffer b;+ luaL_buffinit(L, &b);+ while ((wild = strstr(s, p)) != NULL) {+ luaL_addlstring(&b, s, wild - s); /* push prefix */+ luaL_addstring(&b, r); /* push replacement in place of pattern */+ s = wild + l; /* continue after `p' */+ }+ luaL_addstring(&b, s); /* push last suffix */+ luaL_pushresult(&b);+ return lua_tostring(L, -1);+}+++/* (NumPico: luaL_newstate left out: the calculator's state has its own memory and panic, pico.c) */+++LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver) {+ const lua_Number *v = lua_version(L);+ if (v != lua_version(NULL))+ luaL_error(L, "multiple Lua VMs detected");+ else if (*v != ver)+ luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",+ ver, *v);+ /* check conversions number -> integer types */+ lua_pushnumber(L, fix32_neg(fix32_from_int(0x1234)));+ if (lua_tointeger(L, -1) != -0x1234 ||+ lua_tounsigned(L, -1) != (lua_Unsigned)-0x1234)+ luaL_error(L, "bad conversion number->int;"+ " must recompile Lua with proper settings");+ lua_pop(L, 1);+}+diff --git a/games/numpico/src/femto8/lua/lauxlib.h b/games/numpico/src/femto8/lua/lauxlib.hnew file mode 100644index 00000000..ac4d15fb--- /dev/null+++ b/games/numpico/src/femto8/lua/lauxlib.h@@ -0,0 +1,212 @@+/*+** $Id: lauxlib.h,v 1.120 2011/11/29 15:55:08 roberto Exp $+** Auxiliary functions for building Lua libraries+** See Copyright Notice in lua.h+*/+++#ifndef lauxlib_h+#define lauxlib_h+++#include <stddef.h>+#include <stdio.h>++#include "lua.h"++++/* extra error code for `luaL_load' */+#define LUA_ERRFILE (LUA_ERRERR+1)+++typedef struct luaL_Reg {+ const char *name;+ lua_CFunction func;+} luaL_Reg;+++LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver);+#define luaL_checkversion(L) luaL_checkversion_(L, LUA_VERSION_NUM)++LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e);+LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e);+LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len);+LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg);+LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg,+ size_t *l);+LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg,+ const char *def, size_t *l);+LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int numArg);+LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int nArg, lua_Number def);++LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg);+LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg,+ lua_Integer def);+LUALIB_API lua_Unsigned (luaL_checkunsigned) (lua_State *L, int numArg);+LUALIB_API lua_Unsigned (luaL_optunsigned) (lua_State *L, int numArg,+ lua_Unsigned def);++LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg);+LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t);+LUALIB_API void (luaL_checkany) (lua_State *L, int narg);++LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname);+LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname);+LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname);+LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname);++LUALIB_API void (luaL_where) (lua_State *L, int lvl);+LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...);++LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def,+ const char *const lst[]);++LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname);+LUALIB_API int (luaL_execresult) (lua_State *L, int stat);++/* pre-defined references */+#define LUA_NOREF (-2)+#define LUA_REFNIL (-1)++LUALIB_API int (luaL_ref) (lua_State *L, int t);+LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref);++LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename,+ const char *mode);++#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL)++LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz,+ const char *name, const char *mode);+LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s);++LUALIB_API lua_State *(luaL_newstate) (void);++LUALIB_API int (luaL_len) (lua_State *L, int idx);++LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p,+ const char *r);++LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup);++LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname);++LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1,+ const char *msg, int level);++LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname,+ lua_CFunction openf, int glb);++/*+** ===============================================================+** some useful macros+** ===============================================================+*/+++#define luaL_newlibtable(L,l) \+ lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1)++#define luaL_newlib(L,l) (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))++#define luaL_argcheck(L, cond,numarg,extramsg) \+ ((void)((cond) || luaL_argerror(L, (numarg), (extramsg))))+#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL))+#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL))+#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n)))+#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d)))+#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n)))+#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d)))++#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i)))++#define luaL_dofile(L, fn) \+ (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0))++#define luaL_dostring(L, s) \+ (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0))++#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n)))++#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n)))++#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL)+++/*+** {======================================================+** Generic Buffer manipulation+** =======================================================+*/++typedef struct luaL_Buffer {+ char *b; /* buffer address */+ size_t size; /* buffer size */+ size_t n; /* number of characters in buffer */+ lua_State *L;+ char initb[LUAL_BUFFERSIZE]; /* initial buffer */+} luaL_Buffer;+++#define luaL_addchar(B,c) \+ ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \+ ((B)->b[(B)->n++] = (c)))++#define luaL_addsize(B,s) ((B)->n += (s))++LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);+LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz);+LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l);+LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s);+LUALIB_API void (luaL_addvalue) (luaL_Buffer *B);+LUALIB_API void (luaL_pushresult) (luaL_Buffer *B);+LUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz);+LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz);++#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE)++/* }====================================================== */++++/*+** {======================================================+** File handles for IO library+** =======================================================+*/++/*+** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and+** initial structure 'luaL_Stream' (it may contain other fields+** after that initial structure).+*/++#define LUA_FILEHANDLE "FILE*"+++typedef struct luaL_Stream {+ FILE *f; /* stream (NULL for incompletely created streams) */+ lua_CFunction closef; /* to close stream (NULL for closed streams) */+} luaL_Stream;++/* }====================================================== */++++/* compatibility with old module system */+#if defined(LUA_COMPAT_MODULE)++LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname,+ int sizehint);+LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname,+ const luaL_Reg *l, int nup);++#define luaL_register(L,n,l) (luaL_openlib(L,(n),(l),0))++#endif+++#endif++diff --git a/games/numpico/src/femto8/lua/lbaselib.c b/games/numpico/src/femto8/lua/lbaselib.cnew file mode 100644index 00000000..8d849612--- /dev/null+++ b/games/numpico/src/femto8/lua/lbaselib.c@@ -0,0 +1,485 @@+/*+** $Id: lbaselib.c,v 1.276 2013/02/21 13:44:53 roberto Exp $+** Basic library+** See Copyright Notice in lua.h+** Changed for NumPico: no files and no console: dofile, loadfile and print (PICO-8's print is the cart's API's).+*/++++#include <ctype.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#define lbaselib_c+#define LUA_LIB++#include "lua.h"++#include "lauxlib.h"+#include "lualib.h"+++static int luaB_print (lua_State *L) {+ int n = lua_gettop(L); /* number of arguments */+ int i;+ lua_getglobal(L, "tostring");+ for (i=1; i<=n; i++) {+ const char *s;+ size_t l;+ lua_pushvalue(L, -1); /* function to be called */+ lua_pushvalue(L, i); /* value to print */+ lua_call(L, 1, 1);+ s = lua_tolstring(L, -1, &l); /* get result */+ if (s == NULL)+ return luaL_error(L,+ LUA_QL("tostring") " must return a string to " LUA_QL("print"));+ if (i>1) luai_writestring("\t", 1);+ luai_writestring(s, l);+ lua_pop(L, 1); /* pop result */+ }+ luai_writeline();+ return 0;+}+++#define SPACECHARS " \f\n\r\t\v"++static int luaB_tonumber (lua_State *L) {+ if (lua_isnoneornil(L, 2)) { /* standard conversion */+ int isnum;+ lua_Number n = lua_tonumberx(L, 1, &isnum);+ if (isnum) {+ lua_pushnumber(L, n);+ return 1;+ } /* else not a number; must be something */+ luaL_checkany(L, 1);+ }+ else {+ size_t l;+ const char *s = luaL_checklstring(L, 1, &l);+ const char *e = s + l; /* end point for 's' */+ int base = luaL_checkint(L, 2);+ int neg = 0;+ luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");+ s += strspn(s, SPACECHARS); /* skip initial spaces */+ if (*s == '-') { s++; neg = 1; } /* handle signal */+ else if (*s == '+') s++;+ if (isalnum((unsigned char)*s)) {+ lua_Number n = 0;+ do {+ int digit = (isdigit((unsigned char)*s)) ? *s - '0'+ : toupper((unsigned char)*s) - 'A' + 10;+ if (digit >= base) break; /* invalid numeral; force a fail */+ n = n * (lua_Number)base + (lua_Number)digit;+ s++;+ } while (isalnum((unsigned char)*s));+ s += strspn(s, SPACECHARS); /* skip trailing spaces */+ if (s == e) { /* no invalid trailing characters? */+ lua_pushnumber(L, (neg) ? -n : n);+ return 1;+ } /* else not a number */+ } /* else not a number */+ }+ lua_pushnil(L); /* not a number */+ return 1;+}+++static int luaB_error (lua_State *L) {+ int level = luaL_optint(L, 2, 1);+ lua_settop(L, 1);+ if (lua_isstring(L, 1) && level > 0) { /* add extra information? */+ luaL_where(L, level);+ lua_pushvalue(L, 1);+ lua_concat(L, 2);+ }+ return lua_error(L);+}+++static int luaB_getmetatable (lua_State *L) {+ luaL_checkany(L, 1);+ if (!lua_getmetatable(L, 1)) {+ lua_pushnil(L);+ return 1; /* no metatable */+ }+ luaL_getmetafield(L, 1, "__metatable");+ return 1; /* returns either __metatable field (if present) or metatable */+}+++static int luaB_setmetatable (lua_State *L) {+ int t = lua_type(L, 2);+ luaL_checktype(L, 1, LUA_TTABLE);+ luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,+ "nil or table expected");+ if (luaL_getmetafield(L, 1, "__metatable"))+ return luaL_error(L, "cannot change a protected metatable");+ lua_settop(L, 2);+ lua_setmetatable(L, 1);+ return 1;+}+++static int luaB_rawequal (lua_State *L) {+ luaL_checkany(L, 1);+ luaL_checkany(L, 2);+ lua_pushboolean(L, lua_rawequal(L, 1, 2));+ return 1;+}+++static int luaB_rawlen (lua_State *L) {+ int t = lua_type(L, 1);+ luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,+ "table or string expected");+ lua_pushinteger(L, lua_rawlen(L, 1));+ return 1;+}+++static int luaB_rawget (lua_State *L) {+ luaL_checktype(L, 1, LUA_TTABLE);+ luaL_checkany(L, 2);+ lua_settop(L, 2);+ lua_rawget(L, 1);+ return 1;+}++static int luaB_rawset (lua_State *L) {+ luaL_checktype(L, 1, LUA_TTABLE);+ luaL_checkany(L, 2);+ luaL_checkany(L, 3);+ lua_settop(L, 3);+ lua_rawset(L, 1);+ return 1;+}+++static int luaB_collectgarbage (lua_State *L) {+ static const char *const opts[] = {"stop", "restart", "collect",+ "count", "step", "setpause", "setstepmul",+ "setmajorinc", "isrunning", "generational", "incremental", NULL};+ static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,+ LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,+ LUA_GCSETMAJORINC, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC};+ int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];+ int ex = luaL_optint(L, 2, 0);+ int res = lua_gc(L, o, ex);+ switch (o) {+ case LUA_GCCOUNT: {+ int b = lua_gc(L, LUA_GCCOUNTB, 0);+ lua_pushnumber(L, res + ((lua_Number)b/1024));+ lua_pushinteger(L, b);+ return 2;+ }+ case LUA_GCSTEP: case LUA_GCISRUNNING: {+ lua_pushboolean(L, res);+ return 1;+ }+ default: {+ lua_pushinteger(L, res);+ return 1;+ }+ }+}+++static int luaB_type (lua_State *L) {+ // PICO-8: type() returns nothing instead of causing a runtime error+ if (lua_isnone(L, 1))+ return 0;+ lua_pushstring(L, luaL_typename(L, 1));+ return 1;+}+++static int _empty(lua_State *L) { return 0; }+++static int pairsmeta (lua_State *L, const char *method, int iszero,+ lua_CFunction iter) {+ // PICO-8 0.2.0 changelog: pairs(nil) returns an empty function+ if (lua_isnil(L, 1)) {+ lua_pushcfunction(L, _empty);+ return 1;+ }++ if (!luaL_getmetafield(L, 1, method)) { /* no metamethod? */+ luaL_checktype(L, 1, LUA_TTABLE); /* argument must be a table */+ lua_pushcfunction(L, iter); /* will return generator, */+ lua_pushvalue(L, 1); /* state, */+ if (iszero) lua_pushinteger(L, 0); /* and initial value */+ else lua_pushnil(L);+ }+ else {+ lua_pushvalue(L, 1); /* argument 'self' to metamethod */+ lua_call(L, 1, 3); /* get 3 values from metamethod */+ }+ return 3;+}+++static int luaB_next (lua_State *L) {+ luaL_checktype(L, 1, LUA_TTABLE);+ lua_settop(L, 2); /* create a 2nd argument if there isn't one */+ if (lua_next(L, 1))+ return 2;+ else {+ lua_pushnil(L);+ return 1;+ }+}+++static int luaB_pairs (lua_State *L) {+ return pairsmeta(L, "__pairs", 0, luaB_next);+}+++static int ipairsaux (lua_State *L) {+ int i = luaL_checkint(L, 2);+ luaL_checktype(L, 1, LUA_TTABLE);+ i++; /* next value */+ lua_pushinteger(L, i);+ lua_rawgeti(L, 1, i);+ return (lua_isnil(L, -1)) ? 1 : 2;+}+++static int luaB_ipairs (lua_State *L) {+ return pairsmeta(L, "__ipairs", 1, ipairsaux);+}+++static int luaB_inext (lua_State *L) {+ int i;+ luaL_checktype(L, 1, LUA_TTABLE);++ if (lua_isnoneornil(L, 2)) {+ i = 0;+ } else {+ i = luaL_checkint(L, 2);+ }++ lua_settop(L, 1);+ lua_pushinteger(L, i);++ return ipairsaux(L);+}+++static int load_aux (lua_State *L, int status, int envidx) {+ if (status == LUA_OK) {+ if (envidx != 0) { /* 'env' parameter? */+ lua_pushvalue(L, envidx); /* environment for loaded function */+ if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */+ lua_pop(L, 1); /* remove 'env' if not used by previous call */+ }+ return 1;+ }+ else { /* error (message is on top of the stack) */+ lua_pushnil(L);+ lua_insert(L, -2); /* put before error message */+ return 2; /* return nil plus error message */+ }+}+++static int luaB_loadfile (lua_State *L) {+ const char *fname = luaL_optstring(L, 1, NULL);+ const char *mode = luaL_optstring(L, 2, NULL);+ int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */+ int status = luaL_loadfilex(L, fname, mode);+ return load_aux(L, status, env);+}+++/*+** {======================================================+** Generic Read function+** =======================================================+*/+++/*+** reserved slot, above all arguments, to hold a copy of the returned+** string to avoid it being collected while parsed. 'load' has four+** optional arguments (chunk, source name, mode, and environment).+*/+#define RESERVEDSLOT 5+++/*+** Reader for generic `load' function: `lua_load' uses the+** stack for internal stuff, so the reader cannot change the+** stack top. Instead, it keeps its resulting string in a+** reserved slot inside the stack.+*/+static const char *generic_reader (lua_State *L, void *ud, size_t *size) {+ (void)(ud); /* not used */+ luaL_checkstack(L, 2, "too many nested functions");+ lua_pushvalue(L, 1); /* get function */+ lua_call(L, 0, 1); /* call it */+ if (lua_isnil(L, -1)) {+ lua_pop(L, 1); /* pop result */+ *size = 0;+ return NULL;+ }+ else if (!lua_isstring(L, -1))+ luaL_error(L, "reader function must return a string");+ lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */+ return lua_tolstring(L, RESERVEDSLOT, size);+}+++static int luaB_load (lua_State *L) {+ int status;+ size_t l;+ const char *s = lua_tolstring(L, 1, &l);+ const char *mode = luaL_optstring(L, 3, "bt");+ int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */+ if (s != NULL) { /* loading a string? */+ const char *chunkname = luaL_optstring(L, 2, s);+ status = luaL_loadbufferx(L, s, l, chunkname, mode);+ }+ else { /* loading from a reader function */+ const char *chunkname = luaL_optstring(L, 2, "=(load)");+ luaL_checktype(L, 1, LUA_TFUNCTION);+ lua_settop(L, RESERVEDSLOT); /* create reserved slot */+ status = lua_load(L, generic_reader, NULL, chunkname, mode);+ }+ return load_aux(L, status, env);+}++/* }====================================================== */+++static int dofilecont (lua_State *L) {+ return lua_gettop(L) - 1;+}+++static int luaB_dofile (lua_State *L) {+ const char *fname = luaL_optstring(L, 1, NULL);+ lua_settop(L, 1);+ if (luaL_loadfile(L, fname) != LUA_OK)+ return lua_error(L);+ lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);+ return dofilecont(L);+}+++static int luaB_assert (lua_State *L) {+ if (!lua_toboolean(L, 1))+ return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));+ return lua_gettop(L);+}+++static int luaB_select (lua_State *L) {+ int n = lua_gettop(L);+ if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {+ lua_pushinteger(L, n-1);+ return 1;+ }+ else {+ int i = luaL_checkint(L, 1);+ if (i < 0) i = n + i;+ else if (i > n) i = n;+ luaL_argcheck(L, 1 <= i, 1, "index out of range");+ return n - i;+ }+}+++static int finishpcall (lua_State *L, int status) {+ if (!lua_checkstack(L, 1)) { /* no space for extra boolean? */+ lua_settop(L, 0); /* create space for return values */+ lua_pushboolean(L, 0);+ lua_pushstring(L, "stack overflow");+ return 2; /* return false, msg */+ }+ lua_pushboolean(L, status); /* first result (status) */+ lua_replace(L, 1); /* put first result in first slot */+ return lua_gettop(L);+}+++static int pcallcont (lua_State *L) {+ int status = lua_getctx(L, NULL);+ return finishpcall(L, (status == LUA_YIELD));+}+++static int luaB_pcall (lua_State *L) {+ int status;+ luaL_checkany(L, 1);+ lua_pushnil(L);+ lua_insert(L, 1); /* create space for status result */+ status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, pcallcont);+ return finishpcall(L, (status == LUA_OK));+}+++static int luaB_xpcall (lua_State *L) {+ int status;+ int n = lua_gettop(L);+ luaL_argcheck(L, n >= 2, 2, "value expected");+ lua_pushvalue(L, 1); /* exchange function... */+ lua_copy(L, 2, 1); /* ...and error handler */+ lua_replace(L, 2);+ status = lua_pcallk(L, n - 2, LUA_MULTRET, 1, 0, pcallcont);+ return finishpcall(L, (status == LUA_OK));+}+++static int luaB_tostring (lua_State *L) {+ luaL_checkany(L, 1);+ luaL_tolstring(L, 1, NULL);+ return 1;+}+++static const luaL_Reg base_funcs[] = {+ {"assert", luaB_assert},+ {"collectgarbage", luaB_collectgarbage},+ {"error", luaB_error},+ {"getmetatable", luaB_getmetatable},+ {"inext", luaB_inext},+ {"ipairs", luaB_ipairs},+ {"load", luaB_load},+#if defined(LUA_COMPAT_LOADSTRING)+ {"loadstring", luaB_load},+#endif+ {"next", luaB_next},+ {"pairs", luaB_pairs},+ {"pcall", luaB_pcall},+ {"rawequal", luaB_rawequal},+ {"rawlen", luaB_rawlen},+ {"rawget", luaB_rawget},+ {"rawset", luaB_rawset},+ {"select", luaB_select},+ {"setmetatable", luaB_setmetatable},+ {"tonumber", luaB_tonumber},+ {"tostring", luaB_tostring},+ {"type", luaB_type},+ {"xpcall", luaB_xpcall},+ {NULL, NULL}+};+++LUAMOD_API int luaopen_base (lua_State *L) {+ /* set global _G */+ lua_pushglobaltable(L);+ lua_pushglobaltable(L);+ lua_setfield(L, -2, "_G");+ /* open lib into global table */+ luaL_setfuncs(L, base_funcs, 0);+ lua_pushliteral(L, LUA_VERSION);+ lua_setfield(L, -2, "_VERSION"); /* set global _VERSION */+ return 1;+}+diff --git a/games/numpico/src/femto8/lua/lcode.c b/games/numpico/src/femto8/lua/lcode.cnew file mode 100644index 00000000..68dde538--- /dev/null+++ b/games/numpico/src/femto8/lua/lcode.c@@ -0,0 +1,912 @@+/*+** $Id: lcode.c,v 2.62 2012/08/16 17:34:28 roberto Exp $+** Code generator for Lua+** See Copyright Notice in lua.h+*/+++#include <stdlib.h>++#define lcode_c+#define LUA_CORE++#include "lua.h"++#include "lcode.h"+#include "ldebug.h"+#include "ldo.h"+#include "lgc.h"+#include "llex.h"+#include "lmem.h"+#include "lobject.h"+#include "lopcodes.h"+#include "lparser.h"+#include "lstring.h"+#include "ltable.h"+#include "lvm.h"+++#define hasjumps(e) ((e)->t != (e)->f)+++static int isnumeral(expdesc *e) {+ return (e->k == VKNUM && e->t == NO_JUMP && e->f == NO_JUMP);+}+++void luaK_nil (FuncState *fs, int from, int n) {+ Instruction *previous;+ int l = from + n - 1; /* last register to set nil */+ if (fs->pc > fs->lasttarget) { /* no jumps to current position? */+ previous = &fs->f->code[fs->pc-1];+ if (GET_OPCODE(*previous) == OP_LOADNIL) {+ int pfrom = GETARG_A(*previous);+ int pl = pfrom + GETARG_B(*previous);+ if ((pfrom <= from && from <= pl + 1) ||+ (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */+ if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */+ if (pl > l) l = pl; /* l = max(l, pl) */+ SETARG_A(*previous, from);+ SETARG_B(*previous, l - from);+ return;+ }+ } /* else go through */+ }+ luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */+}+++int luaK_jump (FuncState *fs) {+ int jpc = fs->jpc; /* save list of jumps to here */+ int j;+ fs->jpc = NO_JUMP;+ j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP);+ luaK_concat(fs, &j, jpc); /* keep them on hold */+ return j;+}+++void luaK_ret (FuncState *fs, int first, int nret) {+ luaK_codeABC(fs, OP_RETURN, first, nret+1, 0);+}+++static int condjump (FuncState *fs, OpCode op, int A, int B, int C) {+ luaK_codeABC(fs, op, A, B, C);+ return luaK_jump(fs);+}+++static void fixjump (FuncState *fs, int pc, int dest) {+ Instruction *jmp = &fs->f->code[pc];+ int offset = dest-(pc+1);+ lua_assert(dest != NO_JUMP);+ if (abs(offset) > MAXARG_sBx)+ luaX_syntaxerror(fs->ls, "control structure too long");+ SETARG_sBx(*jmp, offset);+}+++/*+** returns current `pc' and marks it as a jump target (to avoid wrong+** optimizations with consecutive instructions not in the same basic block).+*/+int luaK_getlabel (FuncState *fs) {+ fs->lasttarget = fs->pc;+ return fs->pc;+}+++static int getjump (FuncState *fs, int pc) {+ int offset = GETARG_sBx(fs->f->code[pc]);+ if (offset == NO_JUMP) /* point to itself represents end of list */+ return NO_JUMP; /* end of list */+ else+ return (pc+1)+offset; /* turn offset into absolute position */+}+++static Instruction *getjumpcontrol (FuncState *fs, int pc) {+ Instruction *pi = &fs->f->code[pc];+ if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1))))+ return pi-1;+ else+ return pi;+}+++/*+** check whether list has any jump that do not produce a value+** (or produce an inverted value)+*/+static int need_value (FuncState *fs, int list) {+ for (; list != NO_JUMP; list = getjump(fs, list)) {+ Instruction i = *getjumpcontrol(fs, list);+ if (GET_OPCODE(i) != OP_TESTSET) return 1;+ }+ return 0; /* not found */+}+++static int patchtestreg (FuncState *fs, int node, int reg) {+ Instruction *i = getjumpcontrol(fs, node);+ if (GET_OPCODE(*i) != OP_TESTSET)+ return 0; /* cannot patch other instructions */+ if (reg != NO_REG && reg != GETARG_B(*i))+ SETARG_A(*i, reg);+ else /* no register to put value or register already has the value */+ *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i));++ return 1;+}+++static void removevalues (FuncState *fs, int list) {+ for (; list != NO_JUMP; list = getjump(fs, list))+ patchtestreg(fs, list, NO_REG);+}+++static void patchlistaux (FuncState *fs, int list, int vtarget, int reg,+ int dtarget) {+ while (list != NO_JUMP) {+ int next = getjump(fs, list);+ if (patchtestreg(fs, list, reg))+ fixjump(fs, list, vtarget);+ else+ fixjump(fs, list, dtarget); /* jump to default target */+ list = next;+ }+}+++static void dischargejpc (FuncState *fs) {+ patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc);+ fs->jpc = NO_JUMP;+}+++void luaK_patchlist (FuncState *fs, int list, int target) {+ if (target == fs->pc)+ luaK_patchtohere(fs, list);+ else {+ lua_assert(target < fs->pc);+ patchlistaux(fs, list, target, NO_REG, target);+ }+}+++LUAI_FUNC void luaK_patchclose (FuncState *fs, int list, int level) {+ level++; /* argument is +1 to reserve 0 as non-op */+ while (list != NO_JUMP) {+ int next = getjump(fs, list);+ lua_assert(GET_OPCODE(fs->f->code[list]) == OP_JMP &&+ (GETARG_A(fs->f->code[list]) == 0 ||+ GETARG_A(fs->f->code[list]) >= level));+ SETARG_A(fs->f->code[list], level);+ list = next;+ }+}+++void luaK_patchtohere (FuncState *fs, int list) {+ luaK_getlabel(fs);+ luaK_concat(fs, &fs->jpc, list);+}+++void luaK_concat (FuncState *fs, int *l1, int l2) {+ if (l2 == NO_JUMP) return;+ else if (*l1 == NO_JUMP)+ *l1 = l2;+ else {+ int list = *l1;+ int next;+ while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */+ list = next;+ fixjump(fs, list, l2);+ }+}+++static int luaK_code (FuncState *fs, Instruction i) {+ Proto *f = fs->f;+ dischargejpc(fs); /* `pc' will change */+ /* put new instruction in code array */+ luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,+ MAX_INT, "opcodes");+ f->code[fs->pc] = i;+ /* save corresponding line information */+ luaM_growvector(fs->ls->L, f->lineinfo, fs->pc, f->sizelineinfo, int,+ MAX_INT, "opcodes");+ f->lineinfo[fs->pc] = fs->ls->lastline;+ return fs->pc++;+}+++int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) {+ lua_assert(getOpMode(o) == iABC);+ lua_assert(getBMode(o) != OpArgN || b == 0);+ lua_assert(getCMode(o) != OpArgN || c == 0);+ lua_assert(a <= MAXARG_A && b <= MAXARG_B && c <= MAXARG_C);+ return luaK_code(fs, CREATE_ABC(o, a, b, c));+}+++int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) {+ lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx);+ lua_assert(getCMode(o) == OpArgN);+ lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx);+ return luaK_code(fs, CREATE_ABx(o, a, bc));+}+++static int codeextraarg (FuncState *fs, int a) {+ lua_assert(a <= MAXARG_Ax);+ return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a));+}+++int luaK_codek (FuncState *fs, int reg, int k) {+ if (k <= MAXARG_Bx)+ return luaK_codeABx(fs, OP_LOADK, reg, k);+ else {+ int p = luaK_codeABx(fs, OP_LOADKX, reg, 0);+ codeextraarg(fs, k);+ return p;+ }+}+++void luaK_checkstack (FuncState *fs, int n) {+ int newstack = fs->freereg + n;+ if (newstack > fs->f->maxstacksize) {+ if (newstack >= MAXSTACK)+ luaX_syntaxerror(fs->ls, "function or expression too complex");+ fs->f->maxstacksize = cast_byte(newstack);+ }+}+++void luaK_reserveregs (FuncState *fs, int n) {+ luaK_checkstack(fs, n);+ fs->freereg += n;+}+++static void freereg (FuncState *fs, int reg) {+ if (!ISK(reg) && reg >= fs->nactvar) {+ fs->freereg--;+ lua_assert(reg == fs->freereg);+ }+}+++static void freeexp (FuncState *fs, expdesc *e) {+ if (e->k == VNONRELOC)+ freereg(fs, e->u.info);+}+++static int addk (FuncState *fs, TValue *key, TValue *v) {+ lua_State *L = fs->ls->L;+ TValue *idx = luaH_set(L, fs->h, key);+ Proto *f = fs->f;+ int k, oldsize;+ if (ttisnumber(idx)) {+ lua_Number n = nvalue(idx);+ lua_number2int(k, n);+ if (luaV_rawequalobj(&f->k[k], v))+ return k;+ /* else may be a collision (e.g., between 0.0 and "\0\0\0\0\0\0\0\0");+ go through and create a new entry for this value */+ }+ /* constant not found; create a new entry */+ oldsize = f->sizek;+ k = fs->nk;+ /* numerical value does not need GC barrier;+ table has no metatable, so it does not need to invalidate cache */+ setnvalue(idx, cast_num(k));+ luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants");+ while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);+ setobj(L, &f->k[k], v);+ fs->nk++;+ luaC_barrier(L, f, v);+ return k;+}+++int luaK_stringK (FuncState *fs, TString *s) {+ TValue o;+ setsvalue(fs->ls->L, &o, s);+ return addk(fs, &o, &o);+}+++int luaK_numberK (FuncState *fs, lua_Number r) {+ int n;+ lua_State *L = fs->ls->L;+ TValue o;+ setnvalue(&o, r);+ if (r == 0 || luai_numisnan(NULL, r)) { /* handle -0 and NaN */+ /* use raw representation as key to avoid numeric problems */+ setsvalue(L, L->top++, luaS_newlstr(L, (char *)&r, sizeof(r)));+ n = addk(fs, L->top - 1, &o);+ L->top--;+ }+ else+ n = addk(fs, &o, &o); /* regular case */+ return n;+}+++static int boolK (FuncState *fs, int b) {+ TValue o;+ setbvalue(&o, b);+ return addk(fs, &o, &o);+}+++static int nilK (FuncState *fs) {+ TValue k, v;+ setnilvalue(&v);+ /* cannot use nil as key; instead use table itself to represent nil */+ sethvalue(fs->ls->L, &k, fs->h);+ return addk(fs, &k, &v);+}+++void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {+ if (e->k == VCALL) { /* expression is an open function call? */+ SETARG_C(getcode(fs, e), nresults+1);+ }+ else if (e->k == VVARARG) {+ SETARG_B(getcode(fs, e), nresults+1);+ SETARG_A(getcode(fs, e), fs->freereg);+ luaK_reserveregs(fs, 1);+ }+}+++void luaK_setoneret (FuncState *fs, expdesc *e) {+ if (e->k == VCALL) { /* expression is an open function call? */+ e->k = VNONRELOC;+ e->u.info = GETARG_A(getcode(fs, e));+ }+ else if (e->k == VVARARG) {+ SETARG_B(getcode(fs, e), 2);+ e->k = VRELOCABLE; /* can relocate its simple result */+ }+}+++void luaK_dischargevars (FuncState *fs, expdesc *e) {+ switch (e->k) {+ case VLOCAL: {+ e->k = VNONRELOC;+ break;+ }+ case VUPVAL: {+ e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0);+ e->k = VRELOCABLE;+ break;+ }+ case VINDEXED: {+ OpCode op = OP_GETTABUP; /* assume 't' is in an upvalue */+ freereg(fs, e->u.ind.idx);+ if (e->u.ind.vt == VLOCAL) { /* 't' is in a register? */+ freereg(fs, e->u.ind.t);+ op = OP_GETTABLE;+ }+ e->u.info = luaK_codeABC(fs, op, 0, e->u.ind.t, e->u.ind.idx);+ e->k = VRELOCABLE;+ break;+ }+ case VGLOBAL: {+ e->u.info = luaK_codeABC(fs, OP_GETGLOBALTABLE, 0, e->u.glb.idx, 0);+ e->k = VRELOCABLE;+ break;+ }+ case VVARARG:+ case VCALL: {+ luaK_setoneret(fs, e);+ break;+ }+ default: break; /* there is one value available (somewhere) */+ }+}+++static int code_label (FuncState *fs, int A, int b, int jump) {+ luaK_getlabel(fs); /* those instructions may be jump targets */+ return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump);+}+++static void discharge2reg (FuncState *fs, expdesc *e, int reg) {+ luaK_dischargevars(fs, e);+ switch (e->k) {+ case VNIL: {+ luaK_nil(fs, reg, 1);+ break;+ }+ case VFALSE: case VTRUE: {+ luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0);+ break;+ }+ case VK: {+ luaK_codek(fs, reg, e->u.info);+ break;+ }+ case VKNUM: {+ luaK_codek(fs, reg, luaK_numberK(fs, e->u.nval));+ break;+ }+ case VRELOCABLE: {+ Instruction *pc = &getcode(fs, e);+ SETARG_A(*pc, reg);+ break;+ }+ case VNONRELOC: {+ if (reg != e->u.info)+ luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0);+ break;+ }+ default: {+ lua_assert(e->k == VVOID || e->k == VJMP);+ return; /* nothing to do... */+ }+ }+ e->u.info = reg;+ e->k = VNONRELOC;+}+++static void discharge2anyreg (FuncState *fs, expdesc *e) {+ if (e->k != VNONRELOC) {+ luaK_reserveregs(fs, 1);+ discharge2reg(fs, e, fs->freereg-1);+ }+}+++static void exp2reg (FuncState *fs, expdesc *e, int reg) {+ discharge2reg(fs, e, reg);+ if (e->k == VJMP)+ luaK_concat(fs, &e->t, e->u.info); /* put this jump in `t' list */+ if (hasjumps(e)) {+ int final; /* position after whole expression */+ int p_f = NO_JUMP; /* position of an eventual LOAD false */+ int p_t = NO_JUMP; /* position of an eventual LOAD true */+ if (need_value(fs, e->t) || need_value(fs, e->f)) {+ int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);+ p_f = code_label(fs, reg, 0, 1);+ p_t = code_label(fs, reg, 1, 0);+ luaK_patchtohere(fs, fj);+ }+ final = luaK_getlabel(fs);+ patchlistaux(fs, e->f, final, reg, p_f);+ patchlistaux(fs, e->t, final, reg, p_t);+ }+ e->f = e->t = NO_JUMP;+ e->u.info = reg;+ e->k = VNONRELOC;+}+++void luaK_exp2nextreg (FuncState *fs, expdesc *e) {+ luaK_dischargevars(fs, e);+ freeexp(fs, e);+ luaK_reserveregs(fs, 1);+ exp2reg(fs, e, fs->freereg - 1);+}+++int luaK_exp2anyreg (FuncState *fs, expdesc *e) {+ luaK_dischargevars(fs, e);+ if (e->k == VNONRELOC) {+ if (!hasjumps(e)) return e->u.info; /* exp is already in a register */+ if (e->u.info >= fs->nactvar) { /* reg. is not a local? */+ exp2reg(fs, e, e->u.info); /* put value on it */+ return e->u.info;+ }+ }+ luaK_exp2nextreg(fs, e); /* default */+ return e->u.info;+}+++void luaK_exp2anyregup (FuncState *fs, expdesc *e) {+ if (e->k != VUPVAL || hasjumps(e))+ luaK_exp2anyreg(fs, e);+}+++void luaK_exp2val (FuncState *fs, expdesc *e) {+ if (hasjumps(e))+ luaK_exp2anyreg(fs, e);+ else+ luaK_dischargevars(fs, e);+}+++int luaK_exp2RK (FuncState *fs, expdesc *e) {+ luaK_exp2val(fs, e);+ switch (e->k) {+ case VTRUE:+ case VFALSE:+ case VNIL: {+ if (fs->nk <= MAXINDEXRK) { /* constant fits in RK operand? */+ e->u.info = (e->k == VNIL) ? nilK(fs) : boolK(fs, (e->k == VTRUE));+ e->k = VK;+ return RKASK(e->u.info);+ }+ else break;+ }+ case VKNUM: {+ e->u.info = luaK_numberK(fs, e->u.nval);+ e->k = VK;+ /* go through */+ }+ case VK: {+ if (e->u.info <= MAXINDEXRK) /* constant fits in argC? */+ return RKASK(e->u.info);+ else break;+ }+ default: break;+ }+ /* not a constant in the right range: put it in a register */+ return luaK_exp2anyreg(fs, e);+}+++void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {+ switch (var->k) {+ case VLOCAL: {+ freeexp(fs, ex);+ exp2reg(fs, ex, var->u.info);+ return;+ }+ case VUPVAL: {+ int e = luaK_exp2anyreg(fs, ex);+ luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0);+ break;+ }+ case VINDEXED: {+ OpCode op = (var->u.ind.vt == VLOCAL) ? OP_SETTABLE : OP_SETTABUP;+ int e = luaK_exp2RK(fs, ex);+ luaK_codeABC(fs, op, var->u.ind.t, var->u.ind.idx, e);+ break;+ }+ case VGLOBAL: {+ int e = luaK_exp2RK(fs, ex);+ luaK_codeABC(fs, OP_SETGLOBALTABLE, e, var->u.glb.idx, 0);+ break;+ }+ default: {+ lua_assert(0); /* invalid var kind to store */+ break;+ }+ }+ freeexp(fs, ex);+}+++void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {+ int ereg;+ luaK_exp2anyreg(fs, e);+ ereg = e->u.info; /* register where 'e' was placed */+ freeexp(fs, e);+ e->u.info = fs->freereg; /* base register for op_self */+ e->k = VNONRELOC;+ luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */+ luaK_codeABC(fs, OP_SELF, e->u.info, ereg, luaK_exp2RK(fs, key));+ freeexp(fs, key);+}+++static void invertjump (FuncState *fs, expdesc *e) {+ Instruction *pc = getjumpcontrol(fs, e->u.info);+ lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&+ GET_OPCODE(*pc) != OP_TEST);+ SETARG_A(*pc, !(GETARG_A(*pc)));+}+++static int jumponcond (FuncState *fs, expdesc *e, int cond) {+ if (e->k == VRELOCABLE) {+ Instruction ie = getcode(fs, e);+ if (GET_OPCODE(ie) == OP_NOT) {+ fs->pc--; /* remove previous OP_NOT */+ return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond);+ }+ /* else go through */+ }+ discharge2anyreg(fs, e);+ freeexp(fs, e);+ return condjump(fs, OP_TESTSET, NO_REG, e->u.info, cond);+}+++void luaK_goiftrue (FuncState *fs, expdesc *e) {+ int pc; /* pc of last jump */+ luaK_dischargevars(fs, e);+ switch (e->k) {+ case VJMP: {+ invertjump(fs, e);+ pc = e->u.info;+ break;+ }+ case VK: case VKNUM: case VTRUE: {+ pc = NO_JUMP; /* always true; do nothing */+ break;+ }+ default: {+ pc = jumponcond(fs, e, 0);+ break;+ }+ }+ luaK_concat(fs, &e->f, pc); /* insert last jump in `f' list */+ luaK_patchtohere(fs, e->t);+ e->t = NO_JUMP;+}+++void luaK_goiffalse (FuncState *fs, expdesc *e) {+ int pc; /* pc of last jump */+ luaK_dischargevars(fs, e);+ switch (e->k) {+ case VJMP: {+ pc = e->u.info;+ break;+ }+ case VNIL: case VFALSE: {+ pc = NO_JUMP; /* always false; do nothing */+ break;+ }+ default: {+ pc = jumponcond(fs, e, 1);+ break;+ }+ }+ luaK_concat(fs, &e->t, pc); /* insert last jump in `t' list */+ luaK_patchtohere(fs, e->f);+ e->f = NO_JUMP;+}+++static void codenot (FuncState *fs, expdesc *e) {+ luaK_dischargevars(fs, e);+ switch (e->k) {+ case VNIL: case VFALSE: {+ e->k = VTRUE;+ break;+ }+ case VK: case VKNUM: case VTRUE: {+ e->k = VFALSE;+ break;+ }+ case VJMP: {+ invertjump(fs, e);+ break;+ }+ case VRELOCABLE:+ case VNONRELOC: {+ discharge2anyreg(fs, e);+ freeexp(fs, e);+ e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0);+ e->k = VRELOCABLE;+ break;+ }+ default: {+ lua_assert(0); /* cannot happen */+ break;+ }+ }+ /* interchange true and false lists */+ { int temp = e->f; e->f = e->t; e->t = temp; }+ removevalues(fs, e->f);+ removevalues(fs, e->t);+}+++void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {+ lua_assert(!hasjumps(t));+ t->u.ind.t = t->u.info;+ t->u.ind.idx = luaK_exp2RK(fs, k);+ t->u.ind.vt = (t->k == VUPVAL) ? VUPVAL+ : check_exp(vkisinreg(t->k), VLOCAL);+ t->k = VINDEXED;+}+++static int constfolding (OpCode op, expdesc *e1, expdesc *e2) {+ lua_Number r;+ if (!isnumeral(e1) || !isnumeral(e2)) return 0;+ if ((op == OP_DIV || op == OP_MOD) && e2->u.nval == 0)+ return 0; /* do not attempt to divide by 0 */+ if (op == OP_PEEK || op == OP_PEEK2 || op == OP_PEEK4)+ return 0; /* const folding cannot work with peek */+ r = luaO_arith(NULL, op - OP_ADD + LUA_OPADD, e1->u.nval, e2->u.nval);+ e1->u.nval = r;+ return 1;+}+++static void codearith (FuncState *fs, OpCode op,+ expdesc *e1, expdesc *e2, int line) {+ if (constfolding(op, e1, e2))+ return;+ else {+ int o2 = (op != OP_UNM && op != OP_BNOT && op != OP_LEN) ?+ luaK_exp2RK(fs, e2) : 0;+ int o1 = luaK_exp2RK(fs, e1);+ if (o1 > o2) {+ freeexp(fs, e1);+ freeexp(fs, e2);+ }+ else {+ freeexp(fs, e2);+ freeexp(fs, e1);+ }+ e1->u.info = luaK_codeABC(fs, op, 0, o1, o2);+ e1->k = VRELOCABLE;+ luaK_fixline(fs, line);+ }+}+++static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1,+ expdesc *e2) {+ int o1 = luaK_exp2RK(fs, e1);+ int o2 = luaK_exp2RK(fs, e2);+ freeexp(fs, e2);+ freeexp(fs, e1);+ if (cond == 0 && op != OP_EQ) {+ int temp; /* exchange args to replace by `<' or `<=' */+ temp = o1; o1 = o2; o2 = temp; /* o1 <==> o2 */+ cond = 1;+ }+ e1->u.info = condjump(fs, op, cond, o1, o2);+ e1->k = VJMP;+}+++void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {+ expdesc e2;+ e2.t = e2.f = NO_JUMP; e2.k = VKNUM; e2.u.nval = 0;+ switch (op) {+ case OPR_MINUS: {+ if (isnumeral(e)) /* minus constant? */+ e->u.nval = luai_numunm(NULL, e->u.nval); /* fold it */+ else {+ luaK_exp2anyreg(fs, e);+ codearith(fs, OP_UNM, e, &e2, line);+ }+ break;+ }+ case OPR_BNOT: {+ if (isnumeral(e)) /* bnot constant? */+ e->u.nval = luai_numbnot(NULL, e->u.nval); /* fold it */+ else {+ luaK_exp2anyreg(fs, e);+ codearith(fs, OP_BNOT, e, &e2, line);+ }+ break;+ }+ case OPR_PEEK: case OPR_PEEK2: case OPR_PEEK4: {+ luaK_exp2anyreg(fs, e); /* cannot operate on constants */+ codearith(fs, (OpCode)(op - OPR_PEEK + OP_PEEK), e, &e2, line);+ break;+ }+ case OPR_NOT: codenot(fs, e); break;+ case OPR_LEN: {+ luaK_exp2anyreg(fs, e); /* cannot operate on constants */+ codearith(fs, OP_LEN, e, &e2, line);+ break;+ }+ default: lua_assert(0);+ }+}+++void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {+ switch (op) {+ case OPR_AND: {+ luaK_goiftrue(fs, v);+ break;+ }+ case OPR_OR: {+ luaK_goiffalse(fs, v);+ break;+ }+ case OPR_CONCAT: {+ luaK_exp2nextreg(fs, v); /* operand must be on the `stack' */+ break;+ }+ case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:+ case OPR_MOD: case OPR_POW: case OPR_IDIV: case OPR_BAND:+ case OPR_BOR: case OPR_BXOR: case OPR_SHL: case OPR_SHR:+ case OPR_LSHR: case OPR_ROTL: case OPR_ROTR: {+ if (!isnumeral(v)) luaK_exp2RK(fs, v);+ break;+ }+ default: {+ luaK_exp2RK(fs, v);+ break;+ }+ }+}+++void luaK_posfix (FuncState *fs, BinOpr op,+ expdesc *e1, expdesc *e2, int line) {+ switch (op) {+ case OPR_AND: {+ lua_assert(e1->t == NO_JUMP); /* list must be closed */+ luaK_dischargevars(fs, e2);+ luaK_concat(fs, &e2->f, e1->f);+ *e1 = *e2;+ break;+ }+ case OPR_OR: {+ lua_assert(e1->f == NO_JUMP); /* list must be closed */+ luaK_dischargevars(fs, e2);+ luaK_concat(fs, &e2->t, e1->t);+ *e1 = *e2;+ break;+ }+ case OPR_CONCAT: {+ luaK_exp2val(fs, e2);+ if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) {+ lua_assert(e1->u.info == GETARG_B(getcode(fs, e2))-1);+ freeexp(fs, e1);+ SETARG_B(getcode(fs, e2), e1->u.info);+ e1->k = VRELOCABLE; e1->u.info = e2->u.info;+ }+ else {+ luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */+ codearith(fs, OP_CONCAT, e1, e2, line);+ }+ break;+ }+ case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:+ case OPR_MOD: case OPR_POW: case OPR_IDIV: case OPR_BAND:+ case OPR_BOR: case OPR_BXOR: case OPR_SHL: case OPR_SHR:+ case OPR_LSHR: case OPR_ROTL: case OPR_ROTR: {+ codearith(fs, cast(OpCode, op - OPR_ADD + OP_ADD), e1, e2, line);+ break;+ }+ case OPR_EQ: case OPR_LT: case OPR_LE: {+ codecomp(fs, cast(OpCode, op - OPR_EQ + OP_EQ), 1, e1, e2);+ break;+ }+ case OPR_NE: case OPR_GT: case OPR_GE: {+ codecomp(fs, cast(OpCode, op - OPR_NE + OP_EQ), 0, e1, e2);+ break;+ }+ default: lua_assert(0);+ }+}+++void luaK_fixline (FuncState *fs, int line) {+ fs->f->lineinfo[fs->pc - 1] = line;+}+++void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {+ int c = (nelems - 1)/LFIELDS_PER_FLUSH + 1;+ int b = (tostore == LUA_MULTRET) ? 0 : tostore;+ lua_assert(tostore != 0);+ if (c <= MAXARG_C)+ luaK_codeABC(fs, OP_SETLIST, base, b, c);+ else if (c <= MAXARG_Ax) {+ luaK_codeABC(fs, OP_SETLIST, base, b, 0);+ codeextraarg(fs, c);+ }+ else+ luaX_syntaxerror(fs->ls, "constructor too long");+ fs->freereg = base + 1; /* free registers with list values */+}+diff --git a/games/numpico/src/femto8/lua/lcode.h b/games/numpico/src/femto8/lua/lcode.hnew file mode 100644index 00000000..25e1bfdd--- /dev/null+++ b/games/numpico/src/femto8/lua/lcode.h@@ -0,0 +1,88 @@+/*+** $Id: lcode.h,v 1.58 2011/08/30 16:26:41 roberto Exp $+** Code generator for Lua+** See Copyright Notice in lua.h+*/++#ifndef lcode_h+#define lcode_h++#include "llex.h"+#include "lobject.h"+#include "lopcodes.h"+#include "lparser.h"+++/*+** Marks the end of a patch list. It is an invalid value both as an absolute+** address, and as a list link (would link an element to itself).+*/+#define NO_JUMP (-1)+++/*+** grep "ORDER OPR" if you change these enums (ORDER OP)+*/+typedef enum BinOpr {+ OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW,+ OPR_IDIV, OPR_BAND, OPR_BOR, OPR_BXOR, OPR_SHL, OPR_SHR,+ OPR_LSHR, OPR_ROTL, OPR_ROTR,+ OPR_CONCAT,+ OPR_EQ, OPR_LT, OPR_LE,+ OPR_NE, OPR_GT, OPR_GE,+ OPR_AND, OPR_OR,+ OPR_NOBINOPR+} BinOpr;+++typedef enum UnOpr {+ OPR_MINUS, OPR_NOT, OPR_BNOT, OPR_PEEK, OPR_PEEK2, OPR_PEEK4, OPR_LEN,+ OPR_NOUNOPR+} UnOpr;+++#define getcode(fs,e) ((fs)->f->code[(e)->u.info])++#define luaK_codeAsBx(fs,o,A,sBx) luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx)++#define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET)++#define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t)++LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx);+LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C);+LUAI_FUNC int luaK_codek (FuncState *fs, int reg, int k);+LUAI_FUNC void luaK_fixline (FuncState *fs, int line);+LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n);+LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);+LUAI_FUNC void luaK_checkstack (FuncState *fs, int n);+LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s);+LUAI_FUNC int luaK_numberK (FuncState *fs, lua_Number r);+LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e);+LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e);+LUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e);+LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e);+LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e);+LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e);+LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key);+LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k);+LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e);+LUAI_FUNC void luaK_goiffalse (FuncState *fs, expdesc *e);+LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e);+LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults);+LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e);+LUAI_FUNC int luaK_jump (FuncState *fs);+LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret);+LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target);+LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list);+LUAI_FUNC void luaK_patchclose (FuncState *fs, int list, int level);+LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2);+LUAI_FUNC int luaK_getlabel (FuncState *fs);+LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line);+LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v);+LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1,+ expdesc *v2, int line);+LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore);+++#endifdiff --git a/games/numpico/src/femto8/lua/lcorolib.c b/games/numpico/src/femto8/lua/lcorolib.cnew file mode 100644index 00000000..1326c814--- /dev/null+++ b/games/numpico/src/femto8/lua/lcorolib.c@@ -0,0 +1,155 @@+/*+** $Id: lcorolib.c,v 1.5 2013/02/21 13:44:53 roberto Exp $+** Coroutine Library+** See Copyright Notice in lua.h+*/+++#include <stdlib.h>+++#define lcorolib_c+#define LUA_LIB++#include "lua.h"++#include "lauxlib.h"+#include "lualib.h"+++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 */+ }+}+++static int luaB_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 */+ }+}+++static int luaB_auxwrap (lua_State *L) {+ lua_State *co = lua_tothread(L, lua_upvalueindex(1));+ int r = auxresume(L, co, lua_gettop(L));+ if (r < 0) {+ if (lua_isstring(L, -1)) { /* error object is a string? */+ luaL_where(L, 1); /* add extra info */+ lua_insert(L, -2);+ lua_concat(L, 2);+ }+ return lua_error(L); /* propagate error */+ }+ return r;+}+++static int luaB_cocreate (lua_State *L) {+ lua_State *NL;+ luaL_checktype(L, 1, LUA_TFUNCTION);+ 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;+}+++static int luaB_cowrap (lua_State *L) {+ luaB_cocreate(L);+ lua_pushcclosure(L, luaB_auxwrap, 1);+ return 1;+}+++static int luaB_yield (lua_State *L) {+ return lua_yield(L, lua_gettop(L));+}+++static int luaB_costatus (lua_State *L) {+ lua_State *co = lua_tothread(L, 1);+ luaL_argcheck(L, co, 1, "coroutine expected");+ if (L == co) lua_pushliteral(L, "running");+ else {+ switch (lua_status(co)) {+ case LUA_YIELD:+ lua_pushliteral(L, "suspended");+ break;+ case LUA_OK: {+ lua_Debug ar;+ if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */+ lua_pushliteral(L, "normal"); /* it is running */+ else if (lua_gettop(co) == 0)+ lua_pushliteral(L, "dead");+ else+ lua_pushliteral(L, "suspended"); /* initial state */+ break;+ }+ default: /* some error occurred */+ lua_pushliteral(L, "dead");+ break;+ }+ }+ return 1;+}+++static int luaB_corunning (lua_State *L) {+ int ismain = lua_pushthread(L);+ lua_pushboolean(L, ismain);+ return 2;+}+++static const luaL_Reg co_funcs[] = {+ {"create", luaB_cocreate},+ {"resume", luaB_coresume},+ {"running", luaB_corunning},+ {"status", luaB_costatus},+ {"wrap", luaB_cowrap},+ {"yield", luaB_yield},+ {NULL, NULL}+};++++LUAMOD_API int luaopen_coroutine (lua_State *L) {+ luaL_newlib(L, co_funcs);+ return 1;+}+diff --git a/games/numpico/src/femto8/lua/lctype.c b/games/numpico/src/femto8/lua/lctype.cnew file mode 100644index 00000000..78ecd77c--- /dev/null+++ b/games/numpico/src/femto8/lua/lctype.c@@ -0,0 +1,52 @@+/*+** $Id: lctype.c,v 1.11 2011/10/03 16:19:23 roberto Exp $+** 'ctype' functions for Lua+** See Copyright Notice in lua.h+*/++#define lctype_c+#define LUA_CORE++#include "lctype.h"++#if !LUA_USE_CTYPE /* { */++#include <limits.h>++LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = {+ 0x00, /* EOZ */+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0. */+ 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00,+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 1. */+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,+ 0x0c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, /* 2. */+ 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,+ 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, /* 3. */+ 0x16, 0x16, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,+ 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 4. */+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 5. */+ 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x05,+ 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 6. */+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 7. */+ 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x05,+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 8. */+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 9. */+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* a. */+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* b. */+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* c. */+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* d. */+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* e. */+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* f. */+ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,+};++#endif /* } */diff --git a/games/numpico/src/femto8/lua/lctype.h b/games/numpico/src/femto8/lua/lctype.hnew file mode 100644index 00000000..12a97548--- /dev/null+++ b/games/numpico/src/femto8/lua/lctype.h@@ -0,0 +1,96 @@+/*+** $Id: lctype.h,v 1.12 2011/07/15 12:50:29 roberto Exp $+** 'ctype' functions for Lua+** See Copyright Notice in lua.h+*/++#ifndef lctype_h+#define lctype_h++#include "lua.h"+++/*+** WARNING: the functions defined here do not necessarily correspond+** to the similar functions in the standard C ctype.h. They are+** optimized for the specific needs of Lua+*/++#if !defined(LUA_USE_CTYPE)++#if 'A' == 65 && '0' == 48+/* ASCII case: can use its own tables; faster and fixed */+#define LUA_USE_CTYPE 0+#else+/* must use standard C ctype */+#define LUA_USE_CTYPE 1+#endif++#endif+++#if !LUA_USE_CTYPE /* { */++#include <limits.h>++#include "llimits.h"+++#define ALPHABIT 0+#define DIGITBIT 1+#define PRINTBIT 2+#define SPACEBIT 3+#define XDIGITBIT 4+++#define MASK(B) (1 << (B))+++/*+** add 1 to char to allow index -1 (EOZ)+*/+#define testprop(c,p) (luai_ctype_[(c)+1] & (p))++/*+** 'lalpha' (Lua alphabetic) and 'lalnum' (Lua alphanumeric) both include '_'+*/+#define lislalpha(c) testprop(c, MASK(ALPHABIT))+#define lislalnum(c) testprop(c, (MASK(ALPHABIT) | MASK(DIGITBIT)))+#define lisdigit(c) testprop(c, MASK(DIGITBIT))+#define lisspace(c) testprop(c, MASK(SPACEBIT))+#define lisprint(c) testprop(c, MASK(PRINTBIT))+#define lisxdigit(c) testprop(c, MASK(XDIGITBIT))++/*+** this 'ltolower' only works for alphabetic characters+*/+#define ltolower(c) ((c) | ('A' ^ 'a'))+++/* two more entries for 0 and -1 (EOZ) */+LUAI_DDEC const lu_byte luai_ctype_[UCHAR_MAX + 2];+++#else /* }{ */++/*+** use standard C ctypes+*/++#include <ctype.h>+++#define lisspecial(c) (((int)(c) >= 0x10 && (int)(c) < 0x20) || (int)(c) >= 0x7f)+#define lislalpha(c) (isalpha(c) || (c) == '_' || lisspecial(c))+#define lislalnum(c) (isalnum(c) || (c) == '_' || lisspecial(c))+#define lisdigit(c) (isdigit(c))+#define lisspace(c) (isspace(c))+#define lisprint(c) (isprint(c))+#define lisxdigit(c) (isxdigit(c))++#define ltolower(c) (tolower(c))++#endif /* } */++#endif+diff --git a/games/numpico/src/femto8/lua/ldebug.c b/games/numpico/src/femto8/lua/ldebug.cnew file mode 100644index 00000000..7868d0fe--- /dev/null+++ b/games/numpico/src/femto8/lua/ldebug.c@@ -0,0 +1,620 @@+/*+** $Id: ldebug.c,v 2.90.1.3 2013/05/16 16:04:15 roberto Exp roberto $+** Debug Interface+** See Copyright Notice in lua.h+*/+++#include <stdarg.h>+#include <stddef.h>+#include <string.h>+++#define ldebug_c+#define LUA_CORE++#include "lua.h"++#include "lapi.h"+#include "lcode.h"+#include "ldebug.h"+#include "ldo.h"+#include "lfunc.h"+#include "lobject.h"+#include "lopcodes.h"+#include "lstate.h"+#include "lstring.h"+#include "ltable.h"+#include "ltm.h"+#include "lvm.h"++++#define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_TCCL)+++static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name);+++static int currentpc (CallInfo *ci) {+ lua_assert(isLua(ci));+ return pcRel(ci->u.l.savedpc, ci_func(ci)->p);+}+++static int currentline (CallInfo *ci) {+ return getfuncline(ci_func(ci)->p, currentpc(ci));+}+++static void swapextra (lua_State *L) {+ if (L->status == LUA_YIELD) {+ CallInfo *ci = L->ci; /* get function that yielded */+ StkId temp = ci->func; /* exchange its 'func' and 'extra' values */+ ci->func = restorestack(L, ci->extra);+ ci->extra = savestack(L, temp);+ }+}+++/*+** this function can be called asynchronous (e.g. during a signal)+*/+LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {+ if (func == NULL || mask == 0) { /* turn off hooks? */+ mask = 0;+ func = NULL;+ }+ if (isLua(L->ci))+ L->oldpc = L->ci->u.l.savedpc;+ L->hook = func;+ L->basehookcount = count;+ resethookcount(L);+ L->hookmask = cast_byte(mask);+ return 1;+}+++LUA_API lua_Hook lua_gethook (lua_State *L) {+ return L->hook;+}+++LUA_API int lua_gethookmask (lua_State *L) {+ return L->hookmask;+}+++LUA_API int lua_gethookcount (lua_State *L) {+ return L->basehookcount;+}+++LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {+ int status;+ CallInfo *ci;+ if (level < 0) return 0; /* invalid (negative) level */+ lua_lock(L);+ for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous)+ level--;+ if (level == 0 && ci != &L->base_ci) { /* level found? */+ status = 1;+ ar->i_ci = ci;+ }+ else status = 0; /* no such level */+ lua_unlock(L);+ return status;+}+++static const char *upvalname (Proto *p, int uv) {+ TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name);+ if (s == NULL) return "?";+ else return getstr(s);+}+++static const char *findvararg (CallInfo *ci, int n, StkId *pos) {+ int nparams = clLvalue(ci->func)->p->numparams;+ if (n >= ci->u.l.base - ci->func - nparams)+ return NULL; /* no such vararg */+ else {+ *pos = ci->func + nparams + n;+ return "(*vararg)"; /* generic name for any vararg */+ }+}+++static const char *findlocal (lua_State *L, CallInfo *ci, int n,+ StkId *pos) {+ const char *name = NULL;+ StkId base;+ if (isLua(ci)) {+ if (n < 0) /* access to vararg values? */+ return findvararg(ci, -n, pos);+ else {+ base = ci->u.l.base;+ name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));+ }+ }+ else+ base = ci->func + 1;+ if (name == NULL) { /* no 'standard' name? */+ StkId limit = (ci == L->ci) ? L->top : ci->next->func;+ if (limit - base >= n && n > 0) /* is 'n' inside 'ci' stack? */+ name = "(*temporary)"; /* generic name for any valid slot */+ else+ return NULL; /* no name */+ }+ *pos = base + (n - 1);+ return name;+}+++LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {+ const char *name;+ lua_lock(L);+ swapextra(L);+ if (ar == NULL) { /* information about non-active function? */+ if (!isLfunction(L->top - 1)) /* not a Lua function? */+ name = NULL;+ else /* consider live variables at function start (parameters) */+ name = luaF_getlocalname(clLvalue(L->top - 1)->p, n, 0);+ }+ else { /* active function; get information through 'ar' */+ StkId pos = 0; /* to avoid warnings */+ name = findlocal(L, ar->i_ci, n, &pos);+ if (name) {+ setobj2s(L, L->top, pos);+ api_incr_top(L);+ }+ }+ swapextra(L);+ lua_unlock(L);+ return name;+}+++LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {+ StkId pos = 0; /* to avoid warnings */+ const char *name;+ lua_lock(L);+ swapextra(L);+ name = findlocal(L, ar->i_ci, n, &pos);+ if (name)+ setobjs2s(L, pos, L->top - 1);+ L->top--; /* pop value */+ swapextra(L);+ lua_unlock(L);+ return name;+}+++static void funcinfo (lua_Debug *ar, Closure *cl) {+ if (noLuaClosure(cl)) {+ ar->source = "=[C]";+ ar->linedefined = -1;+ ar->lastlinedefined = -1;+ ar->what = "C";+ }+ else {+ Proto *p = cl->l.p;+ ar->source = p->source ? getstr(p->source) : "=?";+ ar->linedefined = p->linedefined;+ ar->lastlinedefined = p->lastlinedefined;+ ar->what = (ar->linedefined == 0) ? "main" : "Lua";+ }+ luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE);+}+++static void collectvalidlines (lua_State *L, Closure *f) {+ if (noLuaClosure(f)) {+ setnilvalue(L->top);+ api_incr_top(L);+ }+ else {+ int i;+ TValue v;+ int *lineinfo = f->l.p->lineinfo;+ Table *t = luaH_new(L); /* new table to store active lines */+ sethvalue(L, L->top, t); /* push it on stack */+ api_incr_top(L);+ setbvalue(&v, 1); /* boolean 'true' to be the value of all indices */+ for (i = 0; i < f->l.p->sizelineinfo; i++) /* for all lines with code */+ luaH_setint(L, t, lineinfo[i], &v); /* table[line] = true */+ }+}+++static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,+ Closure *f, CallInfo *ci) {+ int status = 1;+ for (; *what; what++) {+ switch (*what) {+ case 'S': {+ funcinfo(ar, f);+ break;+ }+ case 'l': {+ ar->currentline = (ci && isLua(ci)) ? currentline(ci) : -1;+ break;+ }+ case 'u': {+ ar->nups = (f == NULL) ? 0 : f->c.nupvalues;+ if (noLuaClosure(f)) {+ ar->isvararg = 1;+ ar->nparams = 0;+ }+ else {+ ar->isvararg = f->l.p->is_vararg;+ ar->nparams = f->l.p->numparams;+ }+ break;+ }+ case 't': {+ ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0;+ break;+ }+ case 'n': {+ /* calling function is a known Lua function? */+ if (ci && !(ci->callstatus & CIST_TAIL) && isLua(ci->previous))+ ar->namewhat = getfuncname(L, ci->previous, &ar->name);+ else+ ar->namewhat = NULL;+ if (ar->namewhat == NULL) {+ ar->namewhat = ""; /* not found */+ ar->name = NULL;+ }+ break;+ }+ case 'L':+ case 'f': /* handled by lua_getinfo */+ break;+ default: status = 0; /* invalid option */+ }+ }+ return status;+}+++LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {+ int status;+ Closure *cl;+ CallInfo *ci;+ StkId func;+ lua_lock(L);+ swapextra(L);+ if (*what == '>') {+ ci = NULL;+ func = L->top - 1;+ api_check(L, ttisfunction(func), "function expected");+ what++; /* skip the '>' */+ L->top--; /* pop function */+ }+ else {+ ci = ar->i_ci;+ func = ci->func;+ lua_assert(ttisfunction(ci->func));+ }+ cl = ttisclosure(func) ? clvalue(func) : NULL;+ status = auxgetinfo(L, what, ar, cl, ci);+ if (strchr(what, 'f')) {+ setobjs2s(L, L->top, func);+ api_incr_top(L);+ }+ swapextra(L);+ if (strchr(what, 'L'))+ collectvalidlines(L, cl);+ lua_unlock(L);+ return status;+}+++/*+** {======================================================+** Symbolic Execution+** =======================================================+*/++static const char *getobjname (Proto *p, int lastpc, int reg,+ const char **name);+++/*+** find a "name" for the RK value 'c'+*/+static void kname (Proto *p, int pc, int c, const char **name) {+ if (ISK(c)) { /* is 'c' a constant? */+ TValue *kvalue = &p->k[INDEXK(c)];+ if (ttisstring(kvalue)) { /* literal constant? */+ *name = svalue(kvalue); /* it is its own name */+ return;+ }+ /* else no reasonable name found */+ }+ else { /* 'c' is a register */+ const char *what = getobjname(p, pc, c, name); /* search for 'c' */+ if (what && *what == 'c') { /* found a constant name? */+ return; /* 'name' already filled */+ }+ /* else no reasonable name found */+ }+ *name = "?"; /* no reasonable name found */+}+++static int filterpc (int pc, int jmptarget) {+ if (pc < jmptarget) /* is code conditional (inside a jump)? */+ return -1; /* cannot know who sets that register */+ else return pc; /* current position sets that register */+}+++/*+** try to find last instruction before 'lastpc' that modified register 'reg'+*/+static int findsetreg (Proto *p, int lastpc, int reg) {+ int pc;+ int setreg = -1; /* keep last instruction that changed 'reg' */+ int jmptarget = 0; /* any code before this address is conditional */+ for (pc = 0; pc < lastpc; pc++) {+ Instruction i = p->code[pc];+ OpCode op = GET_OPCODE(i);+ int a = GETARG_A(i);+ switch (op) {+ case OP_LOADNIL: {+ int b = GETARG_B(i);+ if (a <= reg && reg <= a + b) /* set registers from 'a' to 'a+b' */+ setreg = filterpc(pc, jmptarget);+ break;+ }+ case OP_TFORCALL: {+ if (reg >= a + 2) /* affect all regs above its base */+ setreg = filterpc(pc, jmptarget);+ break;+ }+ case OP_CALL:+ case OP_TAILCALL: {+ if (reg >= a) /* affect all registers above base */+ setreg = filterpc(pc, jmptarget);+ break;+ }+ case OP_JMP: {+ int b = GETARG_sBx(i);+ int dest = pc + 1 + b;+ /* jump is forward and do not skip `lastpc'? */+ if (pc < dest && dest <= lastpc) {+ if (dest > jmptarget)+ jmptarget = dest; /* update 'jmptarget' */+ }+ break;+ }+ case OP_TEST: {+ if (reg == a) /* jumped code can change 'a' */+ setreg = filterpc(pc, jmptarget);+ break;+ }+ default:+ if (testAMode(op) && reg == a) /* any instruction that set A */+ setreg = filterpc(pc, jmptarget);+ break;+ }+ }+ return setreg;+}+++static const char *getobjname (Proto *p, int lastpc, int reg,+ const char **name) {+ int pc;+ *name = luaF_getlocalname(p, reg + 1, lastpc);+ if (*name) /* is a local? */+ return "local";+ /* else try symbolic execution */+ pc = findsetreg(p, lastpc, reg);+ if (pc != -1) { /* could find instruction? */+ Instruction i = p->code[pc];+ OpCode op = GET_OPCODE(i);+ switch (op) {+ case OP_MOVE: {+ int b = GETARG_B(i); /* move from 'b' to 'a' */+ if (b < GETARG_A(i))+ return getobjname(p, pc, b, name); /* get name for 'b' */+ break;+ }+ case OP_GETTABUP:+ case OP_GETTABLE: {+ int k = GETARG_C(i); /* key index */+ int t = GETARG_B(i); /* table index */+ const char *vn = (op == OP_GETTABLE) /* name of indexed variable */+ ? luaF_getlocalname(p, t + 1, pc)+ : upvalname(p, t);+ kname(p, pc, k, name);+ return (vn && strcmp(vn, LUA_ENV) == 0) ? "global" : "field";+ }+ case OP_GETUPVAL: {+ *name = upvalname(p, GETARG_B(i));+ return "upvalue";+ }+ case OP_LOADK:+ case OP_LOADKX: {+ int b = (op == OP_LOADK) ? GETARG_Bx(i)+ : GETARG_Ax(p->code[pc + 1]);+ if (ttisstring(&p->k[b])) {+ *name = svalue(&p->k[b]);+ return "constant";+ }+ break;+ }+ case OP_SELF: {+ int k = GETARG_C(i); /* key index */+ kname(p, pc, k, name);+ return "method";+ }+ default: break; /* go through to return NULL */+ }+ }+ return NULL; /* could not find reasonable name */+}+++static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {+ TMS tm;+ Proto *p = ci_func(ci)->p; /* calling function */+ int pc = currentpc(ci); /* calling instruction index */+ Instruction i = p->code[pc]; /* calling instruction */+ switch (GET_OPCODE(i)) {+ case OP_CALL:+ case OP_TAILCALL: /* get function name */+ return getobjname(p, pc, GETARG_A(i), name);+ case OP_TFORCALL: { /* for iterator */+ *name = "for iterator";+ return "for iterator";+ }+ /* all other instructions can call only through metamethods */+ case OP_SELF:+ case OP_GETTABUP:+ case OP_GETTABLE: tm = TM_INDEX; break;+ case OP_SETTABUP:+ case OP_SETTABLE: tm = TM_NEWINDEX; break;+ case OP_EQ: tm = TM_EQ; break;+ case OP_ADD: tm = TM_ADD; break;+ case OP_SUB: tm = TM_SUB; break;+ case OP_MUL: tm = TM_MUL; break;+ case OP_DIV: tm = TM_DIV; break;+ case OP_MOD: tm = TM_MOD; break;+ case OP_POW: tm = TM_POW; break;+ case OP_IDIV: tm = TM_IDIV; break;+ case OP_BAND: tm = TM_BAND; break;+ case OP_BOR: tm = TM_BOR; break;+ case OP_BXOR: tm = TM_BXOR; break;+ case OP_SHL: tm = TM_SHL; break;+ case OP_SHR: tm = TM_SHR; break;+ case OP_LSHR: tm = TM_LSHR; break;+ case OP_ROTL: tm = TM_ROTL; break;+ case OP_ROTR: tm = TM_ROTR; break;+ case OP_UNM: tm = TM_UNM; break;+ case OP_BNOT: tm = TM_BNOT; break;+ case OP_LEN: tm = TM_LEN; break;+ case OP_LT: tm = TM_LT; break;+ case OP_LE: tm = TM_LE; break;+ case OP_CONCAT: tm = TM_CONCAT; break;+ default:+ return NULL; /* else no useful name can be found */+ }+ *name = getstr(G(L)->tmname[tm]);+ return "metamethod";+}++/* }====================================================== */++++/*+** only ANSI way to check whether a pointer points to an array+** (used only for error messages, so efficiency is not a big concern)+*/+static int isinstack (CallInfo *ci, const TValue *o) {+ StkId p;+ for (p = ci->u.l.base; p < ci->top; p++)+ if (o == p) return 1;+ return 0;+}+++static const char *getupvalname (CallInfo *ci, const TValue *o,+ const char **name) {+ LClosure *c = ci_func(ci);+ int i;+ for (i = 0; i < c->nupvalues; i++) {+ if (c->upvals[i]->v == o) {+ *name = upvalname(c->p, i);+ return "upvalue";+ }+ }+ return NULL;+}+++l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {+ CallInfo *ci = L->ci;+ const char *name = NULL;+ const char *t = objtypename(o);+ const char *kind = NULL;+ if (isLua(ci)) {+ kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */+ if (!kind && isinstack(ci, o)) /* no? try a register */+ kind = getobjname(ci_func(ci)->p, currentpc(ci),+ cast_int(o - ci->u.l.base), &name);+ }+ if (kind)+ luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)",+ op, kind, name, t);+ else+ luaG_runerror(L, "attempt to %s a %s value", op, t);+}+++l_noret luaG_concaterror (lua_State *L, StkId p1, StkId p2) {+ if (ttisstring(p1) || ttisnumber(p1)) p1 = p2;+ lua_assert(!ttisstring(p1) && !ttisnumber(p1));+ luaG_typeerror(L, p1, "concatenate");+}+++l_noret luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) {+ TValue temp;+ if (luaV_tonumber(p1, &temp) == NULL)+ p2 = p1; /* first operand is wrong */+ luaG_typeerror(L, p2, "perform arithmetic on");+}+++l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {+ const char *t1 = objtypename(p1);+ const char *t2 = objtypename(p2);+ if (t1 == t2)+ luaG_runerror(L, "attempt to compare two %s values", t1);+ else+ luaG_runerror(L, "attempt to compare %s with %s", t1, t2);+}+++static void addinfo (lua_State *L, const char *msg) {+ CallInfo *ci = L->ci;+ if (isLua(ci)) { /* is Lua code? */+ char buff[LUA_IDSIZE]; /* add file:line information */+ int line = currentline(ci);+ TString *src = ci_func(ci)->p->source;+ if (src)+ luaO_chunkid(buff, getstr(src), LUA_IDSIZE);+ else { /* no source available; use "?" instead */+ buff[0] = '?'; buff[1] = '\0';+ }+ luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);+ }+}+++l_noret luaG_errormsg (lua_State *L) {+ if (L->errfunc != 0) { /* is there an error handling function? */+ StkId errfunc = restorestack(L, L->errfunc);+ if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR);+ setobjs2s(L, L->top, L->top - 1); /* move argument */+ setobjs2s(L, L->top - 1, errfunc); /* push function */+ L->top++;+ luaD_call(L, L->top - 2, 1, 0); /* call it */+ }+ luaD_throw(L, LUA_ERRRUN);+}+++l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {+ va_list argp;+ va_start(argp, fmt);+ addinfo(L, luaO_pushvfstring(L, fmt, argp));+ va_end(argp);+ luaG_errormsg(L);+}+diff --git a/games/numpico/src/femto8/lua/ldebug.h b/games/numpico/src/femto8/lua/ldebug.hnew file mode 100644index 00000000..fe39556b--- /dev/null+++ b/games/numpico/src/femto8/lua/ldebug.h@@ -0,0 +1,34 @@+/*+** $Id: ldebug.h,v 2.7 2011/10/07 20:45:19 roberto Exp $+** Auxiliary functions from Debug Interface module+** See Copyright Notice in lua.h+*/++#ifndef ldebug_h+#define ldebug_h+++#include "lstate.h"+++#define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1)++#define getfuncline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : 0)++#define resethookcount(L) (L->hookcount = L->basehookcount)++/* Active Lua function (given call info) */+#define ci_func(ci) (clLvalue((ci)->func))+++LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o,+ const char *opname);+LUAI_FUNC l_noret luaG_concaterror (lua_State *L, StkId p1, StkId p2);+LUAI_FUNC l_noret luaG_aritherror (lua_State *L, const TValue *p1,+ const TValue *p2);+LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1,+ const TValue *p2);+LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...);+LUAI_FUNC l_noret luaG_errormsg (lua_State *L);++#endifdiff --git a/games/numpico/src/femto8/lua/ldo.c b/games/numpico/src/femto8/lua/ldo.cnew file mode 100644index 00000000..5826b38f--- /dev/null+++ b/games/numpico/src/femto8/lua/ldo.c@@ -0,0 +1,682 @@+/*+** $Id: ldo.c,v 2.108.1.2 2013/04/19 21:03:23 roberto Exp roberto $+** Stack and Call structure of Lua+** See Copyright Notice in lua.h+** Changed for NumPico: no binary chunks (no luaU_undump).+*/+++#include <setjmp.h>+#include <stdlib.h>+#include <string.h>++#define ldo_c+#define LUA_CORE++#include "lua.h"++#include "lapi.h"+#include "ldebug.h"+#include "ldo.h"+#include "lfunc.h"+#include "lgc.h"+#include "lmem.h"+#include "lobject.h"+#include "lopcodes.h"+#include "lparser.h"+#include "lstate.h"+#include "lstring.h"+#include "ltable.h"+#include "ltm.h"+#include "lundump.h"+#include "lvm.h"+#include "lzio.h"+++++/*+** {======================================================+** Error-recovery functions+** =======================================================+*/++/*+** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By+** default, Lua handles errors with exceptions when compiling as+** C++ code, with _longjmp/_setjmp when asked to use them, and with+** longjmp/setjmp otherwise.+*/+#if !defined(LUAI_THROW)++#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP)+/* C++ exceptions */+#define LUAI_THROW(L,c) throw(c)+#define LUAI_TRY(L,c,a) \+ try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }+#define luai_jmpbuf int /* dummy variable */++#elif defined(LUA_USE_ULONGJMP)+/* in Unix, try _longjmp/_setjmp (more efficient) */+#define LUAI_THROW(L,c) _longjmp((c)->b, 1)+#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a }+#define luai_jmpbuf jmp_buf++#else+/* default handling with long jumps */+#define LUAI_THROW(L,c) longjmp((c)->b, 1)+#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }+#define luai_jmpbuf jmp_buf++#endif++#endif++++/* chain list of long jump buffers */+struct lua_longjmp {+ struct lua_longjmp *previous;+ luai_jmpbuf b;+ volatile int status; /* error code */+};+++static void seterrorobj (lua_State *L, int errcode, StkId oldtop) {+ switch (errcode) {+ case LUA_ERRMEM: { /* memory error? */+ setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */+ break;+ }+ case LUA_ERRERR: {+ setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));+ break;+ }+ default: {+ setobjs2s(L, oldtop, L->top - 1); /* error message on current top */+ break;+ }+ }+ L->top = oldtop + 1;+}+++l_noret luaD_throw (lua_State *L, int errcode) {+ if (L->errorJmp) { /* thread has an error handler? */+ L->errorJmp->status = errcode; /* set status */+ LUAI_THROW(L, L->errorJmp); /* jump to it */+ }+ else { /* thread has no error handler */+ L->status = cast_byte(errcode); /* mark it as dead */+ if (G(L)->mainthread->errorJmp) { /* main thread has a handler? */+ setobjs2s(L, G(L)->mainthread->top++, L->top - 1); /* copy error obj. */+ luaD_throw(G(L)->mainthread, errcode); /* re-throw in main thread */+ }+ else { /* no handler at all; abort */+ if (G(L)->panic) { /* panic function? */+ lua_unlock(L);+ G(L)->panic(L); /* call it (last chance to jump out) */+ }+ abort();+ }+ }+}+++int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {+ unsigned short oldnCcalls = L->nCcalls;+ struct lua_longjmp lj;+ lj.status = LUA_OK;+ lj.previous = L->errorJmp; /* chain new error handler */+ L->errorJmp = &lj;+ LUAI_TRY(L, &lj,+ (*f)(L, ud);+ );+ L->errorJmp = lj.previous; /* restore old error handler */+ L->nCcalls = oldnCcalls;+ return lj.status;+}++/* }====================================================== */+++static void correctstack (lua_State *L, TValue *oldstack) {+ CallInfo *ci;+ GCObject *up;+ L->top = (L->top - oldstack) + L->stack;+ for (up = L->openupval; up != NULL; up = up->gch.next)+ gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack;+ for (ci = L->ci; ci != NULL; ci = ci->previous) {+ ci->top = (ci->top - oldstack) + L->stack;+ ci->func = (ci->func - oldstack) + L->stack;+ if (isLua(ci))+ ci->u.l.base = (ci->u.l.base - oldstack) + L->stack;+ }+}+++/* some space for error handling */+#define ERRORSTACKSIZE (LUAI_MAXSTACK + 200)+++void luaD_reallocstack (lua_State *L, int newsize) {+ TValue *oldstack = L->stack;+ int lim = L->stacksize;+ lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);+ lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK);+ luaM_reallocvector(L, L->stack, L->stacksize, newsize, TValue);+ for (; lim < newsize; lim++)+ setnilvalue(L->stack + lim); /* erase new segment */+ L->stacksize = newsize;+ L->stack_last = L->stack + newsize - EXTRA_STACK;+ correctstack(L, oldstack);+}+++void luaD_growstack (lua_State *L, int n) {+ int size = L->stacksize;+ if (size > LUAI_MAXSTACK) /* error after extra size? */+ luaD_throw(L, LUA_ERRERR);+ else {+ int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK;+ int newsize = 2 * size;+ if (newsize > LUAI_MAXSTACK) newsize = LUAI_MAXSTACK;+ if (newsize < needed) newsize = needed;+ if (newsize > LUAI_MAXSTACK) { /* stack overflow? */+ luaD_reallocstack(L, ERRORSTACKSIZE);+ luaG_runerror(L, "stack overflow");+ }+ else+ luaD_reallocstack(L, newsize);+ }+}+++static int stackinuse (lua_State *L) {+ CallInfo *ci;+ StkId lim = L->top;+ for (ci = L->ci; ci != NULL; ci = ci->previous) {+ lua_assert(ci->top <= L->stack_last);+ if (lim < ci->top) lim = ci->top;+ }+ return cast_int(lim - L->stack) + 1; /* part of stack in use */+}+++void luaD_shrinkstack (lua_State *L) {+ int inuse = stackinuse(L);+ int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;+ if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK;+ if (inuse > LUAI_MAXSTACK || /* handling stack overflow? */+ goodsize >= L->stacksize) /* would grow instead of shrink? */+ condmovestack(L); /* don't change stack (change only for debugging) */+ else+ luaD_reallocstack(L, goodsize); /* shrink it */+}+++void luaD_hook (lua_State *L, int event, int line) {+ lua_Hook hook = L->hook;+ if (hook && L->allowhook) {+ CallInfo *ci = L->ci;+ ptrdiff_t top = savestack(L, L->top);+ ptrdiff_t ci_top = savestack(L, ci->top);+ lua_Debug ar;+ ar.event = event;+ ar.currentline = line;+ ar.i_ci = ci;+ luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */+ ci->top = L->top + LUA_MINSTACK;+ lua_assert(ci->top <= L->stack_last);+ L->allowhook = 0; /* cannot call hooks inside a hook */+ ci->callstatus |= CIST_HOOKED;+ lua_unlock(L);+ (*hook)(L, &ar);+ lua_lock(L);+ lua_assert(!L->allowhook);+ L->allowhook = 1;+ ci->top = restorestack(L, ci_top);+ L->top = restorestack(L, top);+ ci->callstatus &= ~CIST_HOOKED;+ }+}+++static void callhook (lua_State *L, CallInfo *ci) {+ int hook = LUA_HOOKCALL;+ ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */+ if (isLua(ci->previous) &&+ GET_OPCODE(*(ci->previous->u.l.savedpc - 1)) == OP_TAILCALL) {+ ci->callstatus |= CIST_TAIL;+ hook = LUA_HOOKTAILCALL;+ }+ luaD_hook(L, hook, -1);+ ci->u.l.savedpc--; /* correct 'pc' */+}+++static StkId adjust_varargs (lua_State *L, Proto *p, int actual) {+ int i;+ int nfixargs = p->numparams;+ StkId base, fixed;+ lua_assert(actual >= nfixargs);+ /* move fixed parameters to final position */+ luaD_checkstack(L, p->maxstacksize); /* check again for new 'base' */+ fixed = L->top - actual; /* first fixed argument */+ base = L->top; /* final position of first argument */+ for (i=0; i<nfixargs; i++) {+ setobjs2s(L, L->top++, fixed + i);+ setnilvalue(fixed + i);+ }+ return base;+}+++static StkId tryfuncTM (lua_State *L, StkId func) {+ const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL);+ StkId p;+ ptrdiff_t funcr = savestack(L, func);+ if (!ttisfunction(tm))+ luaG_typeerror(L, func, "call");+ /* Open a hole inside the stack at `func' */+ for (p = L->top; p > func; p--) setobjs2s(L, p, p-1);+ incr_top(L);+ func = restorestack(L, funcr); /* previous call may change stack */+ setobj2s(L, func, tm); /* tag method is the new function to be called */+ return func;+}++++#define next_ci(L) (L->ci = (L->ci->next ? L->ci->next : luaE_extendCI(L)))+++/*+** returns true if function has been executed (C function)+*/+int luaD_precall (lua_State *L, StkId func, int nresults) {+ lua_CFunction f;+ CallInfo *ci;+ int n; /* number of arguments (Lua) or returns (C) */+ ptrdiff_t funcr = savestack(L, func);+ switch (ttype(func)) {+ case LUA_TLCF: /* light C function */+ f = fvalue(func);+ goto Cfunc;+ case LUA_TCCL: { /* C closure */+ f = clCvalue(func)->f;+ Cfunc:+ luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */+ ci = next_ci(L); /* now 'enter' new function */+ ci->nresults = nresults;+ ci->func = restorestack(L, funcr);+ ci->top = L->top + LUA_MINSTACK;+ lua_assert(ci->top <= L->stack_last);+ ci->callstatus = 0;+ luaC_checkGC(L); /* stack grow uses memory */+ if (L->hookmask & LUA_MASKCALL)+ luaD_hook(L, LUA_HOOKCALL, -1);+ lua_unlock(L);+ n = (*f)(L); /* do the actual call */+ lua_lock(L);+ api_checknelems(L, n);+ luaD_poscall(L, L->top - n);+ return 1;+ }+ case LUA_TLCL: { /* Lua function: prepare its call */+ StkId base;+ Proto *p = clLvalue(func)->p;+ n = cast_int(L->top - func) - 1; /* number of real arguments */+ luaD_checkstack(L, p->maxstacksize);+ for (; n < p->numparams; n++)+ setnilvalue(L->top++); /* complete missing arguments */+ if (!p->is_vararg) {+ func = restorestack(L, funcr);+ base = func + 1;+ }+ else {+ base = adjust_varargs(L, p, n);+ func = restorestack(L, funcr); /* previous call can change stack */+ }+ ci = next_ci(L); /* now 'enter' new function */+ ci->nresults = nresults;+ ci->func = func;+ ci->u.l.base = base;+ ci->top = base + p->maxstacksize;+ lua_assert(ci->top <= L->stack_last);+ ci->u.l.savedpc = p->code; /* starting point */+ ci->callstatus = CIST_LUA;+ L->top = ci->top;+ luaC_checkGC(L); /* stack grow uses memory */+ if (L->hookmask & LUA_MASKCALL)+ callhook(L, ci);+ return 0;+ }+ default: { /* not a function */+ func = tryfuncTM(L, func); /* retry with 'function' tag method */+ return luaD_precall(L, func, nresults); /* now it must be a function */+ }+ }+}+++int luaD_poscall (lua_State *L, StkId firstResult) {+ StkId res;+ int wanted, i;+ CallInfo *ci = L->ci;+ if (L->hookmask & (LUA_MASKRET | LUA_MASKLINE)) {+ if (L->hookmask & LUA_MASKRET) {+ ptrdiff_t fr = savestack(L, firstResult); /* hook may change stack */+ luaD_hook(L, LUA_HOOKRET, -1);+ firstResult = restorestack(L, fr);+ }+ L->oldpc = ci->previous->u.l.savedpc; /* 'oldpc' for caller function */+ }+ res = ci->func; /* res == final position of 1st result */+ wanted = ci->nresults;+ L->ci = ci = ci->previous; /* back to caller */+ /* move results to correct place */+ for (i = wanted; i != 0 && firstResult < L->top; i--)+ setobjs2s(L, res++, firstResult++);+ while (i-- > 0)+ setnilvalue(res++);+ L->top = res;+ return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */+}+++/*+** Call a function (C or Lua). The function to be called is at *func.+** The arguments are on the stack, right after the function.+** When returns, all the results are on the stack, starting at the original+** function position.+*/+void luaD_call (lua_State *L, StkId func, int nResults, int allowyield) {+ if (++L->nCcalls >= LUAI_MAXCCALLS) {+ if (L->nCcalls == LUAI_MAXCCALLS)+ luaG_runerror(L, "C stack overflow");+ else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3)))+ luaD_throw(L, LUA_ERRERR); /* error while handing stack error */+ }+ if (!allowyield) L->nny++;+ if (!luaD_precall(L, func, nResults)) /* is a Lua function? */+ luaV_execute(L); /* call it */+ if (!allowyield) L->nny--;+ L->nCcalls--;+}+++static void finishCcall (lua_State *L) {+ CallInfo *ci = L->ci;+ int n;+ lua_assert(ci->u.c.k != NULL); /* must have a continuation */+ lua_assert(L->nny == 0);+ if (ci->callstatus & CIST_YPCALL) { /* was inside a pcall? */+ ci->callstatus &= ~CIST_YPCALL; /* finish 'lua_pcall' */+ L->errfunc = ci->u.c.old_errfunc;+ }+ /* finish 'lua_callk'/'lua_pcall' */+ adjustresults(L, ci->nresults);+ /* call continuation function */+ if (!(ci->callstatus & CIST_STAT)) /* no call status? */+ ci->u.c.status = LUA_YIELD; /* 'default' status */+ lua_assert(ci->u.c.status != LUA_OK);+ ci->callstatus = (ci->callstatus & ~(CIST_YPCALL | CIST_STAT)) | CIST_YIELDED;+ lua_unlock(L);+ n = (*ci->u.c.k)(L);+ lua_lock(L);+ api_checknelems(L, n);+ /* finish 'luaD_precall' */+ luaD_poscall(L, L->top - n);+}+++static void unroll (lua_State *L, void *ud) {+ UNUSED(ud);+ for (;;) {+ if (L->ci == &L->base_ci) /* stack is empty? */+ return; /* coroutine finished normally */+ if (!isLua(L->ci)) /* C function? */+ finishCcall(L);+ else { /* Lua function */+ luaV_finishOp(L); /* finish interrupted instruction */+ luaV_execute(L); /* execute down to higher C 'boundary' */+ }+ }+}+++/*+** check whether thread has a suspended protected call+*/+static CallInfo *findpcall (lua_State *L) {+ CallInfo *ci;+ for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */+ if (ci->callstatus & CIST_YPCALL)+ return ci;+ }+ return NULL; /* no pending pcall */+}+++static int recover (lua_State *L, int status) {+ StkId oldtop;+ CallInfo *ci = findpcall(L);+ if (ci == NULL) return 0; /* no recovery point */+ /* "finish" luaD_pcall */+ oldtop = restorestack(L, ci->extra);+ luaF_close(L, oldtop);+ seterrorobj(L, status, oldtop);+ L->ci = ci;+ L->allowhook = ci->u.c.old_allowhook;+ L->nny = 0; /* should be zero to be yieldable */+ luaD_shrinkstack(L);+ L->errfunc = ci->u.c.old_errfunc;+ ci->callstatus |= CIST_STAT; /* call has error status */+ ci->u.c.status = status; /* (here it is) */+ return 1; /* continue running the coroutine */+}+++/*+** signal an error in the call to 'resume', not in the execution of the+** coroutine itself. (Such errors should not be handled by any coroutine+** error handler and should not kill the coroutine.)+*/+static l_noret resume_error (lua_State *L, const char *msg, StkId firstArg) {+ L->top = firstArg; /* remove args from the stack */+ setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */+ api_incr_top(L);+ luaD_throw(L, -1); /* jump back to 'lua_resume' */+}+++/*+** do the work for 'lua_resume' in protected mode+*/+static void resume (lua_State *L, void *ud) {+ int nCcalls = L->nCcalls;+ StkId firstArg = cast(StkId, ud);+ CallInfo *ci = L->ci;+ if (nCcalls >= LUAI_MAXCCALLS)+ resume_error(L, "C stack overflow", firstArg);+ if (L->status == LUA_OK) { /* may be starting a coroutine */+ if (ci != &L->base_ci) /* not in base level? */+ resume_error(L, "cannot resume non-suspended coroutine", firstArg);+ /* coroutine is in base level; start running it */+ if (!luaD_precall(L, firstArg - 1, LUA_MULTRET)) /* Lua function? */+ luaV_execute(L); /* call it */+ }+ else if (L->status != LUA_YIELD)+ resume_error(L, "cannot resume dead coroutine", firstArg);+ else { /* resuming from previous yield */+ L->status = LUA_OK;+ ci->func = restorestack(L, ci->extra);+ if (isLua(ci)) /* yielded inside a hook? */+ luaV_execute(L); /* just continue running Lua code */+ else { /* 'common' yield */+ if (ci->u.c.k != NULL) { /* does it have a continuation? */+ int n;+ ci->u.c.status = LUA_YIELD; /* 'default' status */+ ci->callstatus |= CIST_YIELDED;+ lua_unlock(L);+ n = (*ci->u.c.k)(L); /* call continuation */+ lua_lock(L);+ api_checknelems(L, n);+ firstArg = L->top - n; /* yield results come from continuation */+ }+ luaD_poscall(L, firstArg); /* finish 'luaD_precall' */+ }+ unroll(L, NULL);+ }+ lua_assert(nCcalls == L->nCcalls);+}+++LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) {+ int status;+ int oldnny = L->nny; /* save 'nny' */+ lua_lock(L);+ luai_userstateresume(L, nargs);+ L->nCcalls = (from) ? from->nCcalls + 1 : 1;+ L->nny = 0; /* allow yields */+ api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);+ status = luaD_rawrunprotected(L, resume, L->top - nargs);+ if (status == -1) /* error calling 'lua_resume'? */+ status = LUA_ERRRUN;+ else { /* yield or regular error */+ while (status != LUA_OK && status != LUA_YIELD) { /* error? */+ if (recover(L, status)) /* recover point? */+ status = luaD_rawrunprotected(L, unroll, NULL); /* run continuation */+ else { /* unrecoverable error */+ L->status = cast_byte(status); /* mark thread as `dead' */+ seterrorobj(L, status, L->top);+ L->ci->top = L->top;+ break;+ }+ }+ lua_assert(status == L->status);+ }+ L->nny = oldnny; /* restore 'nny' */+ L->nCcalls--;+ lua_assert(L->nCcalls == ((from) ? from->nCcalls : 0));+ lua_unlock(L);+ return status;+}+++LUA_API int lua_yieldk (lua_State *L, int nresults, int ctx, lua_CFunction k) {+ CallInfo *ci = L->ci;+ luai_userstateyield(L, nresults);+ lua_lock(L);+ api_checknelems(L, nresults);+ if (L->nny > 0) {+ if (L != G(L)->mainthread)+ luaG_runerror(L, "attempt to yield across a C-call boundary");+ else+ luaG_runerror(L, "attempt to yield from outside a coroutine");+ }+ L->status = LUA_YIELD;+ ci->extra = savestack(L, ci->func); /* save current 'func' */+ if (isLua(ci)) { /* inside a hook? */+ api_check(L, k == NULL, "hooks cannot continue after yielding");+ }+ else {+ if ((ci->u.c.k = k) != NULL) /* is there a continuation? */+ ci->u.c.ctx = ctx; /* save context */+ ci->func = L->top - nresults - 1; /* protect stack below results */+ luaD_throw(L, LUA_YIELD);+ }+ lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */+ lua_unlock(L);+ return 0; /* return to 'luaD_hook' */+}+++int luaD_pcall (lua_State *L, Pfunc func, void *u,+ ptrdiff_t old_top, ptrdiff_t ef) {+ int status;+ CallInfo *old_ci = L->ci;+ lu_byte old_allowhooks = L->allowhook;+ unsigned short old_nny = L->nny;+ ptrdiff_t old_errfunc = L->errfunc;+ L->errfunc = ef;+ status = luaD_rawrunprotected(L, func, u);+ if (status != LUA_OK) { /* an error occurred? */+ StkId oldtop = restorestack(L, old_top);+ luaF_close(L, oldtop); /* close possible pending closures */+ seterrorobj(L, status, oldtop);+ L->ci = old_ci;+ L->allowhook = old_allowhooks;+ L->nny = old_nny;+ luaD_shrinkstack(L);+ }+ L->errfunc = old_errfunc;+ return status;+}++++/*+** Execute a protected parser.+*/+struct SParser { /* data to `f_parser' */+ ZIO *z;+ Mbuffer buff; /* dynamic structure used by the scanner */+ Dyndata dyd; /* dynamic structures used by the parser */+ const char *mode;+ const char *name;+};+++static void checkmode (lua_State *L, const char *mode, const char *x) {+ if (mode && strchr(mode, x[0]) == NULL) {+ luaO_pushfstring(L,+ "attempt to load a %s chunk (mode is " LUA_QS ")", x, mode);+ luaD_throw(L, LUA_ERRSYNTAX);+ }+}+++static void f_parser (lua_State *L, void *ud) {+ int i;+ Closure *cl;+ struct SParser *p = cast(struct SParser *, ud);+ int c = zgetc(p->z); /* read first character */+ if (c == LUA_SIGNATURE[0]) {+ luaO_pushfstring(L, "attempt to load a binary chunk");+ luaD_throw(L, LUA_ERRSYNTAX);+ }+ else {+ checkmode(L, p->mode, "text");+ cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);+ }+ lua_assert(cl->l.nupvalues == cl->l.p->sizeupvalues);+ for (i = 0; i < cl->l.nupvalues; i++) { /* initialize upvalues */+ UpVal *up = luaF_newupval(L);+ cl->l.upvals[i] = up;+ luaC_objbarrier(L, cl, up);+ }+}+++int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,+ const char *mode) {+ struct SParser p;+ int status;+ L->nny++; /* cannot yield during parsing */+ p.z = z; p.name = name; p.mode = mode;+ p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;+ p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;+ p.dyd.label.arr = NULL; p.dyd.label.size = 0;+ luaZ_initbuffer(L, &p.buff);+ status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);+ luaZ_freebuffer(L, &p.buff);+ luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);+ luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);+ luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);+ L->nny--;+ return status;+}++diff --git a/games/numpico/src/femto8/lua/ldo.h b/games/numpico/src/femto8/lua/ldo.hnew file mode 100644index 00000000..27b837d9--- /dev/null+++ b/games/numpico/src/femto8/lua/ldo.h@@ -0,0 +1,46 @@+/*+** $Id: ldo.h,v 2.20 2011/11/29 15:55:08 roberto Exp $+** Stack and Call structure of Lua+** See Copyright Notice in lua.h+*/++#ifndef ldo_h+#define ldo_h+++#include "lobject.h"+#include "lstate.h"+#include "lzio.h"+++#define luaD_checkstack(L,n) if (L->stack_last - L->top <= (n)) \+ luaD_growstack(L, n); else condmovestack(L);+++#define incr_top(L) {L->top++; luaD_checkstack(L,0);}++#define savestack(L,p) ((char *)(p) - (char *)L->stack)+#define restorestack(L,n) ((TValue *)((char *)L->stack + (n)))+++/* type of protected functions, to be ran by `runprotected' */+typedef void (*Pfunc) (lua_State *L, void *ud);++LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,+ const char *mode);+LUAI_FUNC void luaD_hook (lua_State *L, int event, int line);+LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults);+LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults,+ int allowyield);+LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u,+ ptrdiff_t oldtop, ptrdiff_t ef);+LUAI_FUNC int luaD_poscall (lua_State *L, StkId firstResult);+LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize);+LUAI_FUNC void luaD_growstack (lua_State *L, int n);+LUAI_FUNC void luaD_shrinkstack (lua_State *L);++LUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode);+LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud);++#endif+diff --git a/games/numpico/src/femto8/lua/lfunc.c b/games/numpico/src/femto8/lua/lfunc.cnew file mode 100644index 00000000..c2128405--- /dev/null+++ b/games/numpico/src/femto8/lua/lfunc.c@@ -0,0 +1,161 @@+/*+** $Id: lfunc.c,v 2.30 2012/10/03 12:36:46 roberto Exp $+** Auxiliary functions to manipulate prototypes and closures+** See Copyright Notice in lua.h+*/+++#include <stddef.h>++#define lfunc_c+#define LUA_CORE++#include "lua.h"++#include "lfunc.h"+#include "lgc.h"+#include "lmem.h"+#include "lobject.h"+#include "lstate.h"++++Closure *luaF_newCclosure (lua_State *L, int n) {+ Closure *c = &luaC_newobj(L, LUA_TCCL, sizeCclosure(n), NULL, 0)->cl;+ c->c.nupvalues = cast_byte(n);+ return c;+}+++Closure *luaF_newLclosure (lua_State *L, int n) {+ Closure *c = &luaC_newobj(L, LUA_TLCL, sizeLclosure(n), NULL, 0)->cl;+ c->l.p = NULL;+ c->l.nupvalues = cast_byte(n);+ while (n--) c->l.upvals[n] = NULL;+ return c;+}+++UpVal *luaF_newupval (lua_State *L) {+ UpVal *uv = &luaC_newobj(L, LUA_TUPVAL, sizeof(UpVal), NULL, 0)->uv;+ uv->v = &uv->u.value;+ setnilvalue(uv->v);+ return uv;+}+++UpVal *luaF_findupval (lua_State *L, StkId level) {+ global_State *g = G(L);+ GCObject **pp = &L->openupval;+ UpVal *p;+ UpVal *uv;+ while (*pp != NULL && (p = gco2uv(*pp))->v >= level) {+ GCObject *o = obj2gco(p);+ lua_assert(p->v != &p->u.value);+ lua_assert(!isold(o) || isold(obj2gco(L)));+ if (p->v == level) { /* found a corresponding upvalue? */+ if (isdead(g, o)) /* is it dead? */+ changewhite(o); /* resurrect it */+ return p;+ }+ pp = &p->next;+ }+ /* not found: create a new one */+ uv = &luaC_newobj(L, LUA_TUPVAL, sizeof(UpVal), pp, 0)->uv;+ uv->v = level; /* current value lives in the stack */+ uv->u.l.prev = &g->uvhead; /* double link it in `uvhead' list */+ uv->u.l.next = g->uvhead.u.l.next;+ uv->u.l.next->u.l.prev = uv;+ g->uvhead.u.l.next = uv;+ lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);+ return uv;+}+++static void unlinkupval (UpVal *uv) {+ lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);+ uv->u.l.next->u.l.prev = uv->u.l.prev; /* remove from `uvhead' list */+ uv->u.l.prev->u.l.next = uv->u.l.next;+}+++void luaF_freeupval (lua_State *L, UpVal *uv) {+ if (uv->v != &uv->u.value) /* is it open? */+ unlinkupval(uv); /* remove from open list */+ luaM_free(L, uv); /* free upvalue */+}+++void luaF_close (lua_State *L, StkId level) {+ UpVal *uv;+ global_State *g = G(L);+ while (L->openupval != NULL && (uv = gco2uv(L->openupval))->v >= level) {+ GCObject *o = obj2gco(uv);+ lua_assert(!isblack(o) && uv->v != &uv->u.value);+ L->openupval = uv->next; /* remove from `open' list */+ if (isdead(g, o))+ luaF_freeupval(L, uv); /* free upvalue */+ else {+ unlinkupval(uv); /* remove upvalue from 'uvhead' list */+ setobj(L, &uv->u.value, uv->v); /* move value to upvalue slot */+ uv->v = &uv->u.value; /* now current value lives here */+ gch(o)->next = g->allgc; /* link upvalue into 'allgc' list */+ g->allgc = o;+ luaC_checkupvalcolor(g, uv);+ }+ }+}+++Proto *luaF_newproto (lua_State *L) {+ Proto *f = &luaC_newobj(L, LUA_TPROTO, sizeof(Proto), NULL, 0)->p;+ f->k = NULL;+ f->sizek = 0;+ f->p = NULL;+ f->sizep = 0;+ f->code = NULL;+ f->cache = NULL;+ f->sizecode = 0;+ f->lineinfo = NULL;+ f->sizelineinfo = 0;+ f->upvalues = NULL;+ f->sizeupvalues = 0;+ f->numparams = 0;+ f->is_vararg = 0;+ f->maxstacksize = 0;+ f->locvars = NULL;+ f->sizelocvars = 0;+ f->linedefined = 0;+ f->lastlinedefined = 0;+ f->source = NULL;+ return f;+}+++void luaF_freeproto (lua_State *L, Proto *f) {+ luaM_freearray(L, f->code, f->sizecode);+ luaM_freearray(L, f->p, f->sizep);+ luaM_freearray(L, f->k, f->sizek);+ luaM_freearray(L, f->lineinfo, f->sizelineinfo);+ luaM_freearray(L, f->locvars, f->sizelocvars);+ luaM_freearray(L, f->upvalues, f->sizeupvalues);+ luaM_free(L, f);+}+++/*+** Look for n-th local variable at line `line' in function `func'.+** Returns NULL if not found.+*/+const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {+ int i;+ for (i = 0; i<f->sizelocvars && f->locvars[i].startpc <= pc; i++) {+ if (pc < f->locvars[i].endpc) { /* is variable active? */+ local_number--;+ if (local_number == 0)+ return getstr(f->locvars[i].varname);+ }+ }+ return NULL; /* not found */+}+diff --git a/games/numpico/src/femto8/lua/lfunc.h b/games/numpico/src/femto8/lua/lfunc.hnew file mode 100644index 00000000..e236a717--- /dev/null+++ b/games/numpico/src/femto8/lua/lfunc.h@@ -0,0 +1,33 @@+/*+** $Id: lfunc.h,v 2.8 2012/05/08 13:53:33 roberto Exp $+** Auxiliary functions to manipulate prototypes and closures+** See Copyright Notice in lua.h+*/++#ifndef lfunc_h+#define lfunc_h+++#include "lobject.h"+++#define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \+ cast(int, sizeof(TValue)*((n)-1)))++#define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \+ cast(int, sizeof(TValue *)*((n)-1)))+++LUAI_FUNC Proto *luaF_newproto (lua_State *L);+LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems);+LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems);+LUAI_FUNC UpVal *luaF_newupval (lua_State *L);+LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);+LUAI_FUNC void luaF_close (lua_State *L, StkId level);+LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);+LUAI_FUNC void luaF_freeupval (lua_State *L, UpVal *uv);+LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,+ int pc);+++#endifdiff --git a/games/numpico/src/femto8/lua/lgc.c b/games/numpico/src/femto8/lua/lgc.cnew file mode 100644index 00000000..9e77f9b3--- /dev/null+++ b/games/numpico/src/femto8/lua/lgc.c@@ -0,0 +1,1220 @@+/*+** $Id: lgc.c,v 2.140.1.2 2013/04/26 18:22:05 roberto Exp roberto $+** Garbage Collector+** See Copyright Notice in lua.h+*/++#include <string.h>++#define lgc_c+#define LUA_CORE++#include "lua.h"++#include "ldebug.h"+#include "ldo.h"+#include "lfunc.h"+#include "lgc.h"+#include "lmem.h"+#include "lobject.h"+#include "lstate.h"+#include "lstring.h"+#include "ltable.h"+#include "ltm.h"++++/*+** cost of sweeping one element (the size of a small object divided+** by some adjust for the sweep speed)+*/+#define GCSWEEPCOST ((sizeof(TString) + 4) / 4)++/* maximum number of elements to sweep in each single step */+#define GCSWEEPMAX (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4))++/* maximum number of finalizers to call in each GC step */+#define GCFINALIZENUM 4+++/*+** macro to adjust 'stepmul': 'stepmul' is actually used like+** 'stepmul / STEPMULADJ' (value chosen by tests)+*/+#define STEPMULADJ 200+++/*+** macro to adjust 'pause': 'pause' is actually used like+** 'pause / PAUSEADJ' (value chosen by tests)+*/+#define PAUSEADJ 100+++/*+** 'makewhite' erases all color bits plus the old bit and then+** sets only the current white bit+*/+#define maskcolors (~(bit2mask(BLACKBIT, OLDBIT) | WHITEBITS))+#define makewhite(g,x) \+ (gch(x)->marked = cast_byte((gch(x)->marked & maskcolors) | luaC_white(g)))++#define white2gray(x) resetbits(gch(x)->marked, WHITEBITS)+#define black2gray(x) resetbit(gch(x)->marked, BLACKBIT)+++#define isfinalized(x) testbit(gch(x)->marked, FINALIZEDBIT)++#define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))+++#define checkconsistency(obj) \+ lua_longassert(!iscollectable(obj) || righttt(obj))+++#define markvalue(g,o) { checkconsistency(o); \+ if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }++#define markobject(g,t) { if ((t) && iswhite(obj2gco(t))) \+ reallymarkobject(g, obj2gco(t)); }++static void reallymarkobject (global_State *g, GCObject *o);+++/*+** {======================================================+** Generic functions+** =======================================================+*/+++/*+** one after last element in a hash array+*/+#define gnodelast(h) gnode(h, cast(size_t, sizenode(h)))+++/*+** link table 'h' into list pointed by 'p'+*/+#define linktable(h,p) ((h)->gclist = *(p), *(p) = obj2gco(h))+++/*+** if key is not marked, mark its entry as dead (therefore removing it+** from the table)+*/+static void removeentry (Node *n) {+ lua_assert(ttisnil(gval(n)));+ if (valiswhite(gkey(n)))+ setdeadvalue(gkey(n)); /* unused and unmarked key; remove it */+}+++/*+** tells whether a key or value can be cleared from a weak+** table. Non-collectable objects are never removed from weak+** tables. Strings behave as `values', so are never removed too. for+** other objects: if really collected, cannot keep them; for objects+** being finalized, keep them in keys, but not in values+*/+static int iscleared (global_State *g, const TValue *o) {+ if (!iscollectable(o)) return 0;+ else if (ttisstring(o)) {+ markobject(g, rawtsvalue(o)); /* strings are `values', so are never weak */+ return 0;+ }+ else return iswhite(gcvalue(o));+}+++/*+** barrier that moves collector forward, that is, mark the white object+** being pointed by a black object.+*/+void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {+ global_State *g = G(L);+ lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));+ lua_assert(g->gcstate != GCSpause);+ lua_assert(gch(o)->tt != LUA_TTABLE);+ if (keepinvariantout(g)) /* must keep invariant? */+ reallymarkobject(g, v); /* restore invariant */+ else { /* sweep phase */+ lua_assert(issweepphase(g));+ makewhite(g, o); /* mark main obj. as white to avoid other barriers */+ }+}+++/*+** barrier that moves collector backward, that is, mark the black object+** pointing to a white object as gray again. (Current implementation+** only works for tables; access to 'gclist' is not uniform across+** different types.)+*/+void luaC_barrierback_ (lua_State *L, GCObject *o) {+ global_State *g = G(L);+ lua_assert(isblack(o) && !isdead(g, o) && gch(o)->tt == LUA_TTABLE);+ black2gray(o); /* make object gray (again) */+ gco2t(o)->gclist = g->grayagain;+ g->grayagain = o;+}+++/*+** barrier for prototypes. When creating first closure (cache is+** NULL), use a forward barrier; this may be the only closure of the+** prototype (if it is a "regular" function, with a single instance)+** and the prototype may be big, so it is better to avoid traversing+** it again. Otherwise, use a backward barrier, to avoid marking all+** possible instances.+*/+LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c) {+ global_State *g = G(L);+ lua_assert(isblack(obj2gco(p)));+ if (p->cache == NULL) { /* first time? */+ luaC_objbarrier(L, p, c);+ }+ else { /* use a backward barrier */+ black2gray(obj2gco(p)); /* make prototype gray (again) */+ p->gclist = g->grayagain;+ g->grayagain = obj2gco(p);+ }+}+++/*+** check color (and invariants) for an upvalue that was closed,+** i.e., moved into the 'allgc' list+*/+void luaC_checkupvalcolor (global_State *g, UpVal *uv) {+ GCObject *o = obj2gco(uv);+ lua_assert(!isblack(o)); /* open upvalues are never black */+ if (isgray(o)) {+ if (keepinvariant(g)) {+ resetoldbit(o); /* see MOVE OLD rule */+ gray2black(o); /* it is being visited now */+ markvalue(g, uv->v);+ }+ else {+ lua_assert(issweepphase(g));+ makewhite(g, o);+ }+ }+}+++/*+** create a new collectable object (with given type and size) and link+** it to '*list'. 'offset' tells how many bytes to allocate before the+** object itself (used only by states).+*/+GCObject *luaC_newobj (lua_State *L, int tt, size_t sz, GCObject **list,+ int offset) {+ global_State *g = G(L);+ char *raw = cast(char *, luaM_newobject(L, novariant(tt), sz));+ GCObject *o = obj2gco(raw + offset);+ if (list == NULL)+ list = &g->allgc; /* standard list for collectable objects */+ gch(o)->marked = luaC_white(g);+ gch(o)->tt = tt;+ gch(o)->next = *list;+ *list = o;+ return o;+}++/* }====================================================== */++++/*+** {======================================================+** Mark functions+** =======================================================+*/+++/*+** mark an object. Userdata, strings, and closed upvalues are visited+** and turned black here. Other objects are marked gray and added+** to appropriate list to be visited (and turned black) later. (Open+** upvalues are already linked in 'headuv' list.)+*/+static void reallymarkobject (global_State *g, GCObject *o) {+ lu_mem size;+ white2gray(o);+ switch (gch(o)->tt) {+ case LUA_TSHRSTR:+ case LUA_TLNGSTR: {+ size = sizestring(gco2ts(o));+ break; /* nothing else to mark; make it black */+ }+ case LUA_TUSERDATA: {+ Table *mt = gco2u(o)->metatable;+ markobject(g, mt);+ markobject(g, gco2u(o)->env);+ size = sizeudata(gco2u(o));+ break;+ }+ case LUA_TUPVAL: {+ UpVal *uv = gco2uv(o);+ markvalue(g, uv->v);+ if (uv->v != &uv->u.value) /* open? */+ return; /* open upvalues remain gray */+ size = sizeof(UpVal);+ break;+ }+ case LUA_TLCL: {+ gco2lcl(o)->gclist = g->gray;+ g->gray = o;+ return;+ }+ case LUA_TCCL: {+ gco2ccl(o)->gclist = g->gray;+ g->gray = o;+ return;+ }+ case LUA_TTABLE: {+ linktable(gco2t(o), &g->gray);+ return;+ }+ case LUA_TTHREAD: {+ gco2th(o)->gclist = g->gray;+ g->gray = o;+ return;+ }+ case LUA_TPROTO: {+ gco2p(o)->gclist = g->gray;+ g->gray = o;+ return;+ }+ default: lua_assert(0); return;+ }+ gray2black(o);+ g->GCmemtrav += size;+}+++/*+** mark metamethods for basic types+*/+static void markmt (global_State *g) {+ int i;+ for (i=0; i < LUA_NUMTAGS; i++)+ markobject(g, g->mt[i]);+}+++/*+** mark all objects in list of being-finalized+*/+static void markbeingfnz (global_State *g) {+ GCObject *o;+ for (o = g->tobefnz; o != NULL; o = gch(o)->next) {+ makewhite(g, o);+ reallymarkobject(g, o);+ }+}+++/*+** mark all values stored in marked open upvalues. (See comment in+** 'lstate.h'.)+*/+static void remarkupvals (global_State *g) {+ UpVal *uv;+ for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) {+ if (isgray(obj2gco(uv)))+ markvalue(g, uv->v);+ }+}+++/*+** mark root set and reset all gray lists, to start a new+** incremental (or full) collection+*/+static void restartcollection (global_State *g) {+ g->gray = g->grayagain = NULL;+ g->weak = g->allweak = g->ephemeron = NULL;+ markobject(g, g->mainthread);+ markvalue(g, &g->l_registry);+ markmt(g);+ markbeingfnz(g); /* mark any finalizing object left from previous cycle */+}++/* }====================================================== */+++/*+** {======================================================+** Traverse functions+** =======================================================+*/++static void traverseweakvalue (global_State *g, Table *h) {+ Node *n, *limit = gnodelast(h);+ /* if there is array part, assume it may have white values (do not+ traverse it just to check) */+ int hasclears = (h->sizearray > 0);+ for (n = gnode(h, 0); n < limit; n++) {+ checkdeadkey(n);+ if (ttisnil(gval(n))) /* entry is empty? */+ removeentry(n); /* remove it */+ else {+ lua_assert(!ttisnil(gkey(n)));+ markvalue(g, gkey(n)); /* mark key */+ if (!hasclears && iscleared(g, gval(n))) /* is there a white value? */+ hasclears = 1; /* table will have to be cleared */+ }+ }+ if (hasclears)+ linktable(h, &g->weak); /* has to be cleared later */+ else /* no white values */+ linktable(h, &g->grayagain); /* no need to clean */+}+++static int traverseephemeron (global_State *g, Table *h) {+ int marked = 0; /* true if an object is marked in this traversal */+ int hasclears = 0; /* true if table has white keys */+ int prop = 0; /* true if table has entry "white-key -> white-value" */+ Node *n, *limit = gnodelast(h);+ int i;+ /* traverse array part (numeric keys are 'strong') */+ for (i = 0; i < h->sizearray; i++) {+ if (valiswhite(&h->array[i])) {+ marked = 1;+ reallymarkobject(g, gcvalue(&h->array[i]));+ }+ }+ /* traverse hash part */+ for (n = gnode(h, 0); n < limit; n++) {+ checkdeadkey(n);+ if (ttisnil(gval(n))) /* entry is empty? */+ removeentry(n); /* remove it */+ else if (iscleared(g, gkey(n))) { /* key is not marked (yet)? */+ hasclears = 1; /* table must be cleared */+ if (valiswhite(gval(n))) /* value not marked yet? */+ prop = 1; /* must propagate again */+ }+ else if (valiswhite(gval(n))) { /* value not marked yet? */+ marked = 1;+ reallymarkobject(g, gcvalue(gval(n))); /* mark it now */+ }+ }+ if (g->gcstate != GCSatomic || prop)+ linktable(h, &g->ephemeron); /* have to propagate again */+ else if (hasclears) /* does table have white keys? */+ linktable(h, &g->allweak); /* may have to clean white keys */+ else /* no white keys */+ linktable(h, &g->grayagain); /* no need to clean */+ return marked;+}+++static void traversestrongtable (global_State *g, Table *h) {+ Node *n, *limit = gnodelast(h);+ int i;+ for (i = 0; i < h->sizearray; i++) /* traverse array part */+ markvalue(g, &h->array[i]);+ for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */+ checkdeadkey(n);+ if (ttisnil(gval(n))) /* entry is empty? */+ removeentry(n); /* remove it */+ else {+ lua_assert(!ttisnil(gkey(n)));+ markvalue(g, gkey(n)); /* mark key */+ markvalue(g, gval(n)); /* mark value */+ }+ }+}+++static lu_mem traversetable (global_State *g, Table *h) {+ const char *weakkey, *weakvalue;+ const TValue *mode = gfasttm(g, h->metatable, TM_MODE);+ markobject(g, h->metatable);+ if (mode && ttisstring(mode) && /* is there a weak mode? */+ ((weakkey = strchr(svalue(mode), 'k')),+ (weakvalue = strchr(svalue(mode), 'v')),+ (weakkey || weakvalue))) { /* is really weak? */+ black2gray(obj2gco(h)); /* keep table gray */+ if (!weakkey) /* strong keys? */+ traverseweakvalue(g, h);+ else if (!weakvalue) /* strong values? */+ traverseephemeron(g, h);+ else /* all weak */+ linktable(h, &g->allweak); /* nothing to traverse now */+ }+ else /* not weak */+ traversestrongtable(g, h);+ return sizeof(Table) + sizeof(TValue) * h->sizearray ++ sizeof(Node) * cast(size_t, sizenode(h));+}+++static int traverseproto (global_State *g, Proto *f) {+ int i;+ if (f->cache && iswhite(obj2gco(f->cache)))+ f->cache = NULL; /* allow cache to be collected */+ markobject(g, f->source);+ for (i = 0; i < f->sizek; i++) /* mark literals */+ markvalue(g, &f->k[i]);+ for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */+ markobject(g, f->upvalues[i].name);+ for (i = 0; i < f->sizep; i++) /* mark nested protos */+ markobject(g, f->p[i]);+ for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */+ markobject(g, f->locvars[i].varname);+ return sizeof(Proto) + sizeof(Instruction) * f->sizecode ++ sizeof(Proto *) * f->sizep ++ sizeof(TValue) * f->sizek ++ sizeof(int) * f->sizelineinfo ++ sizeof(LocVar) * f->sizelocvars ++ sizeof(Upvaldesc) * f->sizeupvalues;+}+++static lu_mem traverseCclosure (global_State *g, CClosure *cl) {+ int i;+ for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */+ markvalue(g, &cl->upvalue[i]);+ return sizeCclosure(cl->nupvalues);+}++static lu_mem traverseLclosure (global_State *g, LClosure *cl) {+ int i;+ markobject(g, cl->p); /* mark its prototype */+ for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */+ markobject(g, cl->upvals[i]);+ return sizeLclosure(cl->nupvalues);+}+++static lu_mem traversestack (global_State *g, lua_State *th) {+ int n = 0;+ StkId o = th->stack;+ if (o == NULL)+ return 1; /* stack not completely built yet */+ for (; o < th->top; o++) /* mark live elements in the stack */+ markvalue(g, o);+ if (g->gcstate == GCSatomic) { /* final traversal? */+ StkId lim = th->stack + th->stacksize; /* real end of stack */+ for (; o < lim; o++) /* clear not-marked stack slice */+ setnilvalue(o);+ }+ else { /* count call infos to compute size */+ CallInfo *ci;+ for (ci = &th->base_ci; ci != th->ci; ci = ci->next)+ n++;+ }+ return sizeof(lua_State) + sizeof(TValue) * th->stacksize ++ sizeof(CallInfo) * n;+}+++/*+** traverse one gray object, turning it to black (except for threads,+** which are always gray).+*/+static void propagatemark (global_State *g) {+ lu_mem size;+ GCObject *o = g->gray;+ lua_assert(isgray(o));+ gray2black(o);+ switch (gch(o)->tt) {+ case LUA_TTABLE: {+ Table *h = gco2t(o);+ g->gray = h->gclist; /* remove from 'gray' list */+ size = traversetable(g, h);+ break;+ }+ case LUA_TLCL: {+ LClosure *cl = gco2lcl(o);+ g->gray = cl->gclist; /* remove from 'gray' list */+ size = traverseLclosure(g, cl);+ break;+ }+ case LUA_TCCL: {+ CClosure *cl = gco2ccl(o);+ g->gray = cl->gclist; /* remove from 'gray' list */+ size = traverseCclosure(g, cl);+ break;+ }+ case LUA_TTHREAD: {+ lua_State *th = gco2th(o);+ g->gray = th->gclist; /* remove from 'gray' list */+ th->gclist = g->grayagain;+ g->grayagain = o; /* insert into 'grayagain' list */+ black2gray(o);+ size = traversestack(g, th);+ break;+ }+ case LUA_TPROTO: {+ Proto *p = gco2p(o);+ g->gray = p->gclist; /* remove from 'gray' list */+ size = traverseproto(g, p);+ break;+ }+ default: lua_assert(0); return;+ }+ g->GCmemtrav += size;+}+++static void propagateall (global_State *g) {+ while (g->gray) propagatemark(g);+}+++static void propagatelist (global_State *g, GCObject *l) {+ lua_assert(g->gray == NULL); /* no grays left */+ g->gray = l;+ propagateall(g); /* traverse all elements from 'l' */+}++/*+** retraverse all gray lists. Because tables may be reinserted in other+** lists when traversed, traverse the original lists to avoid traversing+** twice the same table (which is not wrong, but inefficient)+*/+static void retraversegrays (global_State *g) {+ GCObject *weak = g->weak; /* save original lists */+ GCObject *grayagain = g->grayagain;+ GCObject *ephemeron = g->ephemeron;+ g->weak = g->grayagain = g->ephemeron = NULL;+ propagateall(g); /* traverse main gray list */+ propagatelist(g, grayagain);+ propagatelist(g, weak);+ propagatelist(g, ephemeron);+}+++static void convergeephemerons (global_State *g) {+ int changed;+ do {+ GCObject *w;+ GCObject *next = g->ephemeron; /* get ephemeron list */+ g->ephemeron = NULL; /* tables will return to this list when traversed */+ changed = 0;+ while ((w = next) != NULL) {+ next = gco2t(w)->gclist;+ if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */+ propagateall(g); /* propagate changes */+ changed = 1; /* will have to revisit all ephemeron tables */+ }+ }+ } while (changed);+}++/* }====================================================== */+++/*+** {======================================================+** Sweep Functions+** =======================================================+*/+++/*+** clear entries with unmarked keys from all weaktables in list 'l' up+** to element 'f'+*/+static void clearkeys (global_State *g, GCObject *l, GCObject *f) {+ for (; l != f; l = gco2t(l)->gclist) {+ Table *h = gco2t(l);+ Node *n, *limit = gnodelast(h);+ for (n = gnode(h, 0); n < limit; n++) {+ if (!ttisnil(gval(n)) && (iscleared(g, gkey(n)))) {+ setnilvalue(gval(n)); /* remove value ... */+ removeentry(n); /* and remove entry from table */+ }+ }+ }+}+++/*+** clear entries with unmarked values from all weaktables in list 'l' up+** to element 'f'+*/+static void clearvalues (global_State *g, GCObject *l, GCObject *f) {+ for (; l != f; l = gco2t(l)->gclist) {+ Table *h = gco2t(l);+ Node *n, *limit = gnodelast(h);+ int i;+ for (i = 0; i < h->sizearray; i++) {+ TValue *o = &h->array[i];+ if (iscleared(g, o)) /* value was collected? */+ setnilvalue(o); /* remove value */+ }+ for (n = gnode(h, 0); n < limit; n++) {+ if (!ttisnil(gval(n)) && iscleared(g, gval(n))) {+ setnilvalue(gval(n)); /* remove value ... */+ removeentry(n); /* and remove entry from table */+ }+ }+ }+}+++static void freeobj (lua_State *L, GCObject *o) {+ switch (gch(o)->tt) {+ case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;+ case LUA_TLCL: {+ luaM_freemem(L, o, sizeLclosure(gco2lcl(o)->nupvalues));+ break;+ }+ case LUA_TCCL: {+ luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));+ break;+ }+ case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break;+ case LUA_TTABLE: luaH_free(L, gco2t(o)); break;+ case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;+ case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;+ case LUA_TSHRSTR:+ G(L)->strt.nuse--;+ /* go through */+ case LUA_TLNGSTR: {+ luaM_freemem(L, o, sizestring(gco2ts(o)));+ break;+ }+ default: lua_assert(0);+ }+}+++#define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM)+static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);+++/*+** sweep the (open) upvalues of a thread and resize its stack and+** list of call-info structures.+*/+static void sweepthread (lua_State *L, lua_State *L1) {+ if (L1->stack == NULL) return; /* stack not completely built yet */+ sweepwholelist(L, &L1->openupval); /* sweep open upvalues */+ luaE_freeCI(L1); /* free extra CallInfo slots */+ /* should not change the stack during an emergency gc cycle */+ if (G(L)->gckind != KGC_EMERGENCY)+ luaD_shrinkstack(L1);+}+++/*+** sweep at most 'count' elements from a list of GCObjects erasing dead+** objects, where a dead (not alive) object is one marked with the "old"+** (non current) white and not fixed.+** In non-generational mode, change all non-dead objects back to white,+** preparing for next collection cycle.+** In generational mode, keep black objects black, and also mark them as+** old; stop when hitting an old object, as all objects after that+** one will be old too.+** When object is a thread, sweep its list of open upvalues too.+*/+static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {+ global_State *g = G(L);+ int ow = otherwhite(g);+ int toclear, toset; /* bits to clear and to set in all live objects */+ int tostop; /* stop sweep when this is true */+ if (isgenerational(g)) { /* generational mode? */+ toclear = ~0; /* clear nothing */+ toset = bitmask(OLDBIT); /* set the old bit of all surviving objects */+ tostop = bitmask(OLDBIT); /* do not sweep old generation */+ }+ else { /* normal mode */+ toclear = maskcolors; /* clear all color bits + old bit */+ toset = luaC_white(g); /* make object white */+ tostop = 0; /* do not stop */+ }+ while (*p != NULL && count-- > 0) {+ GCObject *curr = *p;+ int marked = gch(curr)->marked;+ if (isdeadm(ow, marked)) { /* is 'curr' dead? */+ *p = gch(curr)->next; /* remove 'curr' from list */+ freeobj(L, curr); /* erase 'curr' */+ }+ else {+ if (testbits(marked, tostop))+ return NULL; /* stop sweeping this list */+ if (gch(curr)->tt == LUA_TTHREAD)+ sweepthread(L, gco2th(curr)); /* sweep thread's upvalues */+ /* update marks */+ gch(curr)->marked = cast_byte((marked & toclear) | toset);+ p = &gch(curr)->next; /* go to next element */+ }+ }+ return (*p == NULL) ? NULL : p;+}+++/*+** sweep a list until a live object (or end of list)+*/+static GCObject **sweeptolive (lua_State *L, GCObject **p, int *n) {+ GCObject ** old = p;+ int i = 0;+ do {+ i++;+ p = sweeplist(L, p, 1);+ } while (p == old);+ if (n) *n += i;+ return p;+}++/* }====================================================== */+++/*+** {======================================================+** Finalization+** =======================================================+*/++static void checkSizes (lua_State *L) {+ global_State *g = G(L);+ if (g->gckind != KGC_EMERGENCY) { /* do not change sizes in emergency */+ int hs = g->strt.size / 2; /* half the size of the string table */+ if (g->strt.nuse < cast(lu_int32, hs)) /* using less than that half? */+ luaS_resize(L, hs); /* halve its size */+ luaZ_freebuffer(L, &g->buff); /* free concatenation buffer */+ }+}+++static GCObject *udata2finalize (global_State *g) {+ GCObject *o = g->tobefnz; /* get first element */+ lua_assert(isfinalized(o));+ g->tobefnz = gch(o)->next; /* remove it from 'tobefnz' list */+ gch(o)->next = g->allgc; /* return it to 'allgc' list */+ g->allgc = o;+ resetbit(gch(o)->marked, SEPARATED); /* mark that it is not in 'tobefnz' */+ lua_assert(!isold(o)); /* see MOVE OLD rule */+ if (!keepinvariantout(g)) /* not keeping invariant? */+ makewhite(g, o); /* "sweep" object */+ return o;+}+++static void dothecall (lua_State *L, void *ud) {+ UNUSED(ud);+ luaD_call(L, L->top - 2, 0, 0);+}+++static void GCTM (lua_State *L, int propagateerrors) {+ global_State *g = G(L);+ const TValue *tm;+ TValue v;+ setgcovalue(L, &v, udata2finalize(g));+ tm = luaT_gettmbyobj(L, &v, TM_GC);+ if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */+ int status;+ lu_byte oldah = L->allowhook;+ int running = g->gcrunning;+ L->allowhook = 0; /* stop debug hooks during GC metamethod */+ g->gcrunning = 0; /* avoid GC steps */+ setobj2s(L, L->top, tm); /* push finalizer... */+ setobj2s(L, L->top + 1, &v); /* ... and its argument */+ L->top += 2; /* and (next line) call the finalizer */+ status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);+ L->allowhook = oldah; /* restore hooks */+ g->gcrunning = running; /* restore state */+ if (status != LUA_OK && propagateerrors) { /* error while running __gc? */+ if (status == LUA_ERRRUN) { /* is there an error object? */+ const char *msg = (ttisstring(L->top - 1))+ ? svalue(L->top - 1)+ : "no message";+ luaO_pushfstring(L, "error in __gc metamethod (%s)", msg);+ status = LUA_ERRGCMM; /* error in __gc metamethod */+ }+ luaD_throw(L, status); /* re-throw error */+ }+ }+}+++/*+** move all unreachable objects (or 'all' objects) that need+** finalization from list 'finobj' to list 'tobefnz' (to be finalized)+*/+static void separatetobefnz (lua_State *L, int all) {+ global_State *g = G(L);+ GCObject **p = &g->finobj;+ GCObject *curr;+ GCObject **lastnext = &g->tobefnz;+ /* find last 'next' field in 'tobefnz' list (to add elements in its end) */+ while (*lastnext != NULL)+ lastnext = &gch(*lastnext)->next;+ while ((curr = *p) != NULL) { /* traverse all finalizable objects */+ lua_assert(!isfinalized(curr));+ lua_assert(testbit(gch(curr)->marked, SEPARATED));+ if (!(iswhite(curr) || all)) /* not being collected? */+ p = &gch(curr)->next; /* don't bother with it */+ else {+ l_setbit(gch(curr)->marked, FINALIZEDBIT); /* won't be finalized again */+ *p = gch(curr)->next; /* remove 'curr' from 'finobj' list */+ gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */+ *lastnext = curr;+ lastnext = &gch(curr)->next;+ }+ }+}+++/*+** if object 'o' has a finalizer, remove it from 'allgc' list (must+** search the list to find it) and link it in 'finobj' list.+*/+void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {+ global_State *g = G(L);+ if (testbit(gch(o)->marked, SEPARATED) || /* obj. is already separated... */+ isfinalized(o) || /* ... or is finalized... */+ gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */+ return; /* nothing to be done */+ else { /* move 'o' to 'finobj' list */+ GCObject **p;+ GCheader *ho = gch(o);+ if (g->sweepgc == &ho->next) { /* avoid removing current sweep object */+ lua_assert(issweepphase(g));+ g->sweepgc = sweeptolive(L, g->sweepgc, NULL);+ }+ /* search for pointer pointing to 'o' */+ for (p = &g->allgc; *p != o; p = &gch(*p)->next) { /* empty */ }+ *p = ho->next; /* remove 'o' from root list */+ ho->next = g->finobj; /* link it in list 'finobj' */+ g->finobj = o;+ l_setbit(ho->marked, SEPARATED); /* mark it as such */+ if (!keepinvariantout(g)) /* not keeping invariant? */+ makewhite(g, o); /* "sweep" object */+ else+ resetoldbit(o); /* see MOVE OLD rule */+ }+}++/* }====================================================== */+++/*+** {======================================================+** GC control+** =======================================================+*/+++/*+** set a reasonable "time" to wait before starting a new GC cycle;+** cycle will start when memory use hits threshold+*/+static void setpause (global_State *g, l_mem estimate) {+ l_mem debt, threshold;+ estimate = estimate / PAUSEADJ; /* adjust 'estimate' */+ threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */+ ? estimate * g->gcpause /* no overflow */+ : MAX_LMEM; /* overflow; truncate to maximum */+ debt = -cast(l_mem, threshold - gettotalbytes(g));+ luaE_setdebt(g, debt);+}+++#define sweepphases \+ (bitmask(GCSsweepstring) | bitmask(GCSsweepudata) | bitmask(GCSsweep))+++/*+** enter first sweep phase (strings) and prepare pointers for other+** sweep phases. The calls to 'sweeptolive' make pointers point to an+** object inside the list (instead of to the header), so that the real+** sweep do not need to skip objects created between "now" and the start+** of the real sweep.+** Returns how many objects it swept.+*/+static int entersweep (lua_State *L) {+ global_State *g = G(L);+ int n = 0;+ g->gcstate = GCSsweepstring;+ lua_assert(g->sweepgc == NULL && g->sweepfin == NULL);+ /* prepare to sweep strings, finalizable objects, and regular objects */+ g->sweepstrgc = 0;+ g->sweepfin = sweeptolive(L, &g->finobj, &n);+ g->sweepgc = sweeptolive(L, &g->allgc, &n);+ return n;+}+++/*+** change GC mode+*/+void luaC_changemode (lua_State *L, int mode) {+ global_State *g = G(L);+ if (mode == g->gckind) return; /* nothing to change */+ if (mode == KGC_GEN) { /* change to generational mode */+ /* make sure gray lists are consistent */+ luaC_runtilstate(L, bitmask(GCSpropagate));+ g->GCestimate = gettotalbytes(g);+ g->gckind = KGC_GEN;+ }+ else { /* change to incremental mode */+ /* sweep all objects to turn them back to white+ (as white has not changed, nothing extra will be collected) */+ g->gckind = KGC_NORMAL;+ entersweep(L);+ luaC_runtilstate(L, ~sweepphases);+ }+}+++/*+** call all pending finalizers+*/+static void callallpendingfinalizers (lua_State *L, int propagateerrors) {+ global_State *g = G(L);+ while (g->tobefnz) {+ resetoldbit(g->tobefnz);+ GCTM(L, propagateerrors);+ }+}+++void luaC_freeallobjects (lua_State *L) {+ global_State *g = G(L);+ int i;+ separatetobefnz(L, 1); /* separate all objects with finalizers */+ lua_assert(g->finobj == NULL);+ callallpendingfinalizers(L, 0);+ g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */+ g->gckind = KGC_NORMAL;+ sweepwholelist(L, &g->finobj); /* finalizers can create objs. in 'finobj' */+ sweepwholelist(L, &g->allgc);+ for (i = 0; i < g->strt.size; i++) /* free all string lists */+ sweepwholelist(L, &g->strt.hash[i]);+ lua_assert(g->strt.nuse == 0);+}+++static l_mem atomic (lua_State *L) {+ global_State *g = G(L);+ l_mem work = -cast(l_mem, g->GCmemtrav); /* start counting work */+ GCObject *origweak, *origall;+ lua_assert(!iswhite(obj2gco(g->mainthread)));+ markobject(g, L); /* mark running thread */+ /* registry and global metatables may be changed by API */+ markvalue(g, &g->l_registry);+ markmt(g); /* mark basic metatables */+ /* remark occasional upvalues of (maybe) dead threads */+ remarkupvals(g);+ propagateall(g); /* propagate changes */+ work += g->GCmemtrav; /* stop counting (do not (re)count grays) */+ /* traverse objects caught by write barrier and by 'remarkupvals' */+ retraversegrays(g);+ work -= g->GCmemtrav; /* restart counting */+ convergeephemerons(g);+ /* at this point, all strongly accessible objects are marked. */+ /* clear values from weak tables, before checking finalizers */+ clearvalues(g, g->weak, NULL);+ clearvalues(g, g->allweak, NULL);+ origweak = g->weak; origall = g->allweak;+ work += g->GCmemtrav; /* stop counting (objects being finalized) */+ separatetobefnz(L, 0); /* separate objects to be finalized */+ markbeingfnz(g); /* mark objects that will be finalized */+ propagateall(g); /* remark, to propagate `preserveness' */+ work -= g->GCmemtrav; /* restart counting */+ convergeephemerons(g);+ /* at this point, all resurrected objects are marked. */+ /* remove dead objects from weak tables */+ clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */+ clearkeys(g, g->allweak, NULL); /* clear keys from all allweak tables */+ /* clear values from resurrected weak tables */+ clearvalues(g, g->weak, origweak);+ clearvalues(g, g->allweak, origall);+ g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */+ work += g->GCmemtrav; /* complete counting */+ return work; /* estimate of memory marked by 'atomic' */+}+++static lu_mem singlestep (lua_State *L) {+ global_State *g = G(L);+ switch (g->gcstate) {+ case GCSpause: {+ /* start to count memory traversed */+ g->GCmemtrav = g->strt.size * sizeof(GCObject*);+ lua_assert(!isgenerational(g));+ restartcollection(g);+ g->gcstate = GCSpropagate;+ return g->GCmemtrav;+ }+ case GCSpropagate: {+ if (g->gray) {+ lu_mem oldtrav = g->GCmemtrav;+ propagatemark(g);+ return g->GCmemtrav - oldtrav; /* memory traversed in this step */+ }+ else { /* no more `gray' objects */+ lu_mem work;+ int sw;+ g->gcstate = GCSatomic; /* finish mark phase */+ g->GCestimate = g->GCmemtrav; /* save what was counted */;+ work = atomic(L); /* add what was traversed by 'atomic' */+ g->GCestimate += work; /* estimate of total memory traversed */+ sw = entersweep(L);+ return work + sw * GCSWEEPCOST;+ }+ }+ case GCSsweepstring: {+ int i;+ for (i = 0; i < GCSWEEPMAX && g->sweepstrgc + i < g->strt.size; i++)+ sweepwholelist(L, &g->strt.hash[g->sweepstrgc + i]);+ g->sweepstrgc += i;+ if (g->sweepstrgc >= g->strt.size) /* no more strings to sweep? */+ g->gcstate = GCSsweepudata;+ return i * GCSWEEPCOST;+ }+ case GCSsweepudata: {+ if (g->sweepfin) {+ g->sweepfin = sweeplist(L, g->sweepfin, GCSWEEPMAX);+ return GCSWEEPMAX*GCSWEEPCOST;+ }+ else {+ g->gcstate = GCSsweep;+ return 0;+ }+ }+ case GCSsweep: {+ if (g->sweepgc) {+ g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);+ return GCSWEEPMAX*GCSWEEPCOST;+ }+ else {+ /* sweep main thread */+ GCObject *mt = obj2gco(g->mainthread);+ sweeplist(L, &mt, 1);+ checkSizes(L);+ g->gcstate = GCSpause; /* finish collection */+ return GCSWEEPCOST;+ }+ }+ default: lua_assert(0); return 0;+ }+}+++/*+** advances the garbage collector until it reaches a state allowed+** by 'statemask'+*/+void luaC_runtilstate (lua_State *L, int statesmask) {+ global_State *g = G(L);+ while (!testbit(statesmask, g->gcstate))+ singlestep(L);+}+++static void generationalcollection (lua_State *L) {+ global_State *g = G(L);+ lua_assert(g->gcstate == GCSpropagate);+ if (g->GCestimate == 0) { /* signal for another major collection? */+ luaC_fullgc(L, 0); /* perform a full regular collection */+ g->GCestimate = gettotalbytes(g); /* update control */+ }+ else {+ lu_mem estimate = g->GCestimate;+ luaC_runtilstate(L, bitmask(GCSpause)); /* run complete (minor) cycle */+ g->gcstate = GCSpropagate; /* skip restart */+ if (gettotalbytes(g) > (estimate / 100) * g->gcmajorinc)+ g->GCestimate = 0; /* signal for a major collection */+ else+ g->GCestimate = estimate; /* keep estimate from last major coll. */++ }+ setpause(g, gettotalbytes(g));+ lua_assert(g->gcstate == GCSpropagate);+}+++static void incstep (lua_State *L) {+ global_State *g = G(L);+ l_mem debt = g->GCdebt;+ int stepmul = g->gcstepmul;+ if (stepmul < 40) stepmul = 40; /* avoid ridiculous low values (and 0) */+ /* convert debt from Kb to 'work units' (avoid zero debt and overflows) */+ debt = (debt / STEPMULADJ) + 1;+ debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM;+ do { /* always perform at least one single step */+ lu_mem work = singlestep(L); /* do some work */+ debt -= work;+ } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);+ if (g->gcstate == GCSpause)+ setpause(g, g->GCestimate); /* pause until next cycle */+ else {+ debt = (debt / stepmul) * STEPMULADJ; /* convert 'work units' to Kb */+ luaE_setdebt(g, debt);+ }+}+++/*+** performs a basic GC step+*/+void luaC_forcestep (lua_State *L) {+ global_State *g = G(L);+ int i;+ if (isgenerational(g)) generationalcollection(L);+ else incstep(L);+ /* run a few finalizers (or all of them at the end of a collect cycle) */+ for (i = 0; g->tobefnz && (i < GCFINALIZENUM || g->gcstate == GCSpause); i++)+ GCTM(L, 1); /* call one finalizer */+}+++/*+** performs a basic GC step only if collector is running+*/+void luaC_step (lua_State *L) {+ global_State *g = G(L);+ if (g->gcrunning) luaC_forcestep(L);+ else luaE_setdebt(g, -GCSTEPSIZE); /* avoid being called too often */+}++++/*+** performs a full GC cycle; if "isemergency", does not call+** finalizers (which could change stack positions)+*/+void luaC_fullgc (lua_State *L, int isemergency) {+ global_State *g = G(L);+ int origkind = g->gckind;+ lua_assert(origkind != KGC_EMERGENCY);+ if (isemergency) /* do not run finalizers during emergency GC */+ g->gckind = KGC_EMERGENCY;+ else {+ g->gckind = KGC_NORMAL;+ callallpendingfinalizers(L, 1);+ }+ if (keepinvariant(g)) { /* may there be some black objects? */+ /* must sweep all objects to turn them back to white+ (as white has not changed, nothing will be collected) */+ entersweep(L);+ }+ /* finish any pending sweep phase to start a new cycle */+ luaC_runtilstate(L, bitmask(GCSpause));+ luaC_runtilstate(L, ~bitmask(GCSpause)); /* start new collection */+ luaC_runtilstate(L, bitmask(GCSpause)); /* run entire collection */+ if (origkind == KGC_GEN) { /* generational mode? */+ /* generational mode must be kept in propagate phase */+ luaC_runtilstate(L, bitmask(GCSpropagate));+ }+ g->gckind = origkind;+ setpause(g, gettotalbytes(g));+ if (!isemergency) /* do not run finalizers during emergency GC */+ callallpendingfinalizers(L, 1);+}++/* }====================================================== */++diff --git a/games/numpico/src/femto8/lua/lgc.h b/games/numpico/src/femto8/lua/lgc.hnew file mode 100644index 00000000..dee270b4--- /dev/null+++ b/games/numpico/src/femto8/lua/lgc.h@@ -0,0 +1,157 @@+/*+** $Id: lgc.h,v 2.58 2012/09/11 12:53:08 roberto Exp $+** Garbage Collector+** See Copyright Notice in lua.h+*/++#ifndef lgc_h+#define lgc_h+++#include "lobject.h"+#include "lstate.h"++/*+** Collectable objects may have one of three colors: white, which+** means the object is not marked; gray, which means the+** object is marked, but its references may be not marked; and+** black, which means that the object and all its references are marked.+** The main invariant of the garbage collector, while marking objects,+** is that a black object can never point to a white one. Moreover,+** any gray object must be in a "gray list" (gray, grayagain, weak,+** allweak, ephemeron) so that it can be visited again before finishing+** the collection cycle. These lists have no meaning when the invariant+** is not being enforced (e.g., sweep phase).+*/++++/* how much to allocate before next GC step */+#if !defined(GCSTEPSIZE)+/* ~100 small strings */+#define GCSTEPSIZE (cast_int(100 * sizeof(TString)))+#endif+++/*+** Possible states of the Garbage Collector+*/+#define GCSpropagate 0+#define GCSatomic 1+#define GCSsweepstring 2+#define GCSsweepudata 3+#define GCSsweep 4+#define GCSpause 5+++#define issweepphase(g) \+ (GCSsweepstring <= (g)->gcstate && (g)->gcstate <= GCSsweep)++#define isgenerational(g) ((g)->gckind == KGC_GEN)++/*+** macros to tell when main invariant (white objects cannot point to black+** ones) must be kept. During a non-generational collection, the sweep+** phase may break the invariant, as objects turned white may point to+** still-black objects. The invariant is restored when sweep ends and+** all objects are white again. During a generational collection, the+** invariant must be kept all times.+*/++#define keepinvariant(g) (isgenerational(g) || g->gcstate <= GCSatomic)+++/*+** Outside the collector, the state in generational mode is kept in+** 'propagate', so 'keepinvariant' is always true.+*/+#define keepinvariantout(g) \+ check_exp(g->gcstate == GCSpropagate || !isgenerational(g), \+ g->gcstate <= GCSatomic)+++/*+** some useful bit tricks+*/+#define resetbits(x,m) ((x) &= cast(lu_byte, ~(m)))+#define setbits(x,m) ((x) |= (m))+#define testbits(x,m) ((x) & (m))+#define bitmask(b) (1<<(b))+#define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2))+#define l_setbit(x,b) setbits(x, bitmask(b))+#define resetbit(x,b) resetbits(x, bitmask(b))+#define testbit(x,b) testbits(x, bitmask(b))+++/* Layout for bit use in `marked' field: */+#define WHITE0BIT 0 /* object is white (type 0) */+#define WHITE1BIT 1 /* object is white (type 1) */+#define BLACKBIT 2 /* object is black */+#define FINALIZEDBIT 3 /* object has been separated for finalization */+#define SEPARATED 4 /* object is in 'finobj' list or in 'tobefnz' */+#define FIXEDBIT 5 /* object is fixed (should not be collected) */+#define OLDBIT 6 /* object is old (only in generational mode) */+/* bit 7 is currently used by tests (luaL_checkmemory) */++#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT)+++#define iswhite(x) testbits((x)->gch.marked, WHITEBITS)+#define isblack(x) testbit((x)->gch.marked, BLACKBIT)+#define isgray(x) /* neither white nor black */ \+ (!testbits((x)->gch.marked, WHITEBITS | bitmask(BLACKBIT)))++#define isold(x) testbit((x)->gch.marked, OLDBIT)++/* MOVE OLD rule: whenever an object is moved to the beginning of+ a GC list, its old bit must be cleared */+#define resetoldbit(o) resetbit((o)->gch.marked, OLDBIT)++#define otherwhite(g) (g->currentwhite ^ WHITEBITS)+#define isdeadm(ow,m) (!(((m) ^ WHITEBITS) & (ow)))+#define isdead(g,v) isdeadm(otherwhite(g), (v)->gch.marked)++#define changewhite(x) ((x)->gch.marked ^= WHITEBITS)+#define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT)++#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))++#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS)+++#define luaC_condGC(L,c) \+ {if (G(L)->GCdebt > 0) {c;}; condchangemem(L);}+#define luaC_checkGC(L) luaC_condGC(L, luaC_step(L);)+++#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \+ luaC_barrier_(L,obj2gco(p),gcvalue(v)); }++#define luaC_barrierback(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \+ luaC_barrierback_(L,p); }++#define luaC_objbarrier(L,p,o) \+ { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \+ luaC_barrier_(L,obj2gco(p),obj2gco(o)); }++#define luaC_objbarrierback(L,p,o) \+ { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) luaC_barrierback_(L,p); }++#define luaC_barrierproto(L,p,c) \+ { if (isblack(obj2gco(p))) luaC_barrierproto_(L,p,c); }++LUAI_FUNC void luaC_freeallobjects (lua_State *L);+LUAI_FUNC void luaC_step (lua_State *L);+LUAI_FUNC void luaC_forcestep (lua_State *L);+LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask);+LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);+LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz,+ GCObject **list, int offset);+LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v);+LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o);+LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c);+LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt);+LUAI_FUNC void luaC_checkupvalcolor (global_State *g, UpVal *uv);+LUAI_FUNC void luaC_changemode (lua_State *L, int mode);++#endifdiff --git a/games/numpico/src/femto8/lua/linit.c b/games/numpico/src/femto8/lua/linit.cnew file mode 100644index 00000000..3c953947--- /dev/null+++ b/games/numpico/src/femto8/lua/linit.c@@ -0,0 +1,67 @@+/*+** $Id: linit.c,v 1.32 2011/04/08 19:17:36 roberto Exp $+** Initialization of libraries for lua.c and other clients+** See Copyright Notice in lua.h+*/+++/*+** If you embed Lua in your program and need to open the standard+** libraries, call luaL_openlibs in your program. If you need a+** different set of libraries, copy this file to your project and edit+** it to suit your needs.+*/+++#define linit_c+#define LUA_LIB++#include "lua.h"++#include "lualib.h"+#include "lauxlib.h"+++/*+** these libs are loaded by lua.c and are readily available to any Lua+** program+*/+static const luaL_Reg loadedlibs[] = {+ {"_G", luaopen_base},+ {"_G", luaopen_pico8},+ {LUA_COLIBNAME, luaopen_coroutine},+ {LUA_STRLIBNAME, luaopen_string},+ {NULL, NULL}+};+++/*+** these libs are preloaded and must be required before used+*/+static const luaL_Reg preloadedlibs[] = {+ {NULL, NULL}+};+++LUALIB_API void luaL_openlibs (lua_State *L) {+ const luaL_Reg *lib;+ /* call open functions from 'loadedlibs' and set results to global table */+ for (lib = loadedlibs; lib->func; lib++) {+ luaL_requiref(L, lib->name, lib->func, 1);+ lua_pop(L, 1); /* remove lib */+ }+ luaL_requiref(L, LUA_TABLIBNAME, luaopen_table, 0);+ lua_getfield(L, -1, "unpack");+ lua_setglobal(L, "unpack");+ lua_pop(L, 1); /* remove table lib */+ lua_pushnil(L);+ lua_setglobal(L, "_G");+ /* add open functions from 'preloadedlibs' into 'package.preload' table */+ luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");+ for (lib = preloadedlibs; lib->func; lib++) {+ lua_pushcfunction(L, lib->func);+ lua_setfield(L, -2, lib->name);+ }+ lua_pop(L, 1); /* remove _PRELOAD table */+}+diff --git a/games/numpico/src/femto8/lua/llex.c b/games/numpico/src/femto8/lua/llex.cnew file mode 100644index 00000000..ee91ad21--- /dev/null+++ b/games/numpico/src/femto8/lua/llex.c@@ -0,0 +1,609 @@+/*+** $Id: llex.c,v 2.63.1.2 2013/08/30 15:49:41 roberto Exp roberto $+** Lexical Analyzer+** See Copyright Notice in lua.h+*/+++#include <locale.h>+#include <string.h>++#define llex_c+#define LUA_CORE++#include "lua.h"++#include "lctype.h"+#include "ldo.h"+#include "llex.h"+#include "lobject.h"+#include "lparser.h"+#include "lstate.h"+#include "lstring.h"+#include "ltable.h"+#include "lzio.h"++++#define next(ls) (ls->current = zgetc(ls->z))++++#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r')+++/* ORDER RESERVED */+static const char *const luaX_tokens [] = {+ "and", "break", "do", "else", "elseif",+ "end", "false", "for", "function", "goto", "if",+ "in", "local", "nil", "not", "or", "repeat",+ "return", "then", "true", "until", "while",+ "..", "...", "==", ">=", "<=", "~=", "!=", "::",+ "<eof>", "<number>", "<name>", "<string>", "?",+ "<eol>", "^^", "<<", ">>", ">>>", "<<>", ">><",+ "+=", "-=", "*=", "/=", "%=", "^=", "\\=", "&=", "|=",+ "^^=", "<<=", ">>=", ">>>=", "<<>=", ">><=", "..=",+};+++#define save_and_next(ls) (save(ls, ls->current), next(ls))+++static l_noret lexerror (LexState *ls, const char *msg, int token);+++static void save (LexState *ls, int c) {+ Mbuffer *b = ls->buff;+ if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) {+ size_t newsize;+ if (luaZ_sizebuffer(b) >= MAX_SIZET/2)+ lexerror(ls, "lexical element too long", 0);+ newsize = luaZ_sizebuffer(b) * 2;+ luaZ_resizebuffer(ls->L, b, newsize);+ }+ b->buffer[luaZ_bufflen(b)++] = cast(char, c);+}+++void luaX_init (lua_State *L) {+ int i;+ for (i=0; i<NUM_RESERVED; i++) {+ TString *ts = luaS_new(L, luaX_tokens[i]);+ luaS_fix(ts); /* reserved words are never collected */+ ts->tsv.extra = cast_byte(i+1); /* reserved word */+ }+}+++const char *luaX_token2str (LexState *ls, int token) {+ if (token < FIRST_RESERVED) { /* single-byte symbols? */+ lua_assert(token == cast(unsigned char, token));+ return (lisprint(token)) ? luaO_pushfstring(ls->L, LUA_QL("%c"), token) :+ luaO_pushfstring(ls->L, "char(%d)", token);+ }+ else {+ const char *s = luaX_tokens[token - FIRST_RESERVED];+ if (token < TK_EOS) /* fixed format (symbols and reserved words)? */+ return luaO_pushfstring(ls->L, LUA_QS, s);+ else /* names, strings, and numerals */+ return s;+ }+}+++void luaX_trackbraces (LexState *ls) {+ ls->braces = ls->t.token == '(' ? 1 : -1;+}+++static const char *txtToken (LexState *ls, int token) {+ switch (token) {+ case TK_NAME:+ case TK_STRING:+ case TK_NUMBER:+ save(ls, '\0');+ return luaO_pushfstring(ls->L, LUA_QS, luaZ_buffer(ls->buff));+ default:+ return luaX_token2str(ls, token);+ }+}+++static l_noret lexerror (LexState *ls, const char *msg, int token) {+ char buff[LUA_IDSIZE];+ luaO_chunkid(buff, getstr(ls->source), LUA_IDSIZE);+ msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg);+ if (token)+ luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token));+ luaD_throw(ls->L, LUA_ERRSYNTAX);+}+++l_noret luaX_syntaxerror (LexState *ls, const char *msg) {+ lexerror(ls, msg, ls->t.token);+}+++/*+** creates a new string and anchors it in function's table so that+** it will not be collected until the end of the function's compilation+** (by that time it should be anchored in function's prototype)+*/+TString *luaX_newstring (LexState *ls, const char *str, size_t l) {+ lua_State *L = ls->L;+ TValue *o; /* entry for `str' */+ TString *ts = luaS_newlstr(L, str, l); /* create new string */+ setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */+ o = luaH_set(L, ls->fs->h, L->top - 1);+ if (ttisnil(o)) { /* not in use yet? (see 'addK') */+ /* boolean value does not need GC barrier;+ table has no metatable, so it does not need to invalidate cache */+ setbvalue(o, 1); /* t[string] = true */+ luaC_checkGC(L);+ }+ else { /* string already present */+ ts = rawtsvalue(keyfromval(o)); /* re-use value previously stored */+ }+ L->top--; /* remove string from stack */+ return ts;+}+++/*+** increment line number and skips newline sequence (any of+** \n, \r, \n\r, or \r\n)+*/+static void inclinenumber (LexState *ls) {+ int old = ls->current;+ lua_assert(currIsNewline(ls));+ next(ls); /* skip `\n' or `\r' */+ if (currIsNewline(ls) && ls->current != old)+ next(ls); /* skip `\n\r' or `\r\n' */+ if (++ls->linenumber >= MAX_INT)+ lexerror(ls, "chunk has too many lines", 0);+}+++void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,+ int firstchar) {+ ls->decpoint = '.';+ ls->L = L;+ ls->current = firstchar;+ ls->lookahead.token = TK_EOS; /* no look-ahead token */+ ls->z = z;+ ls->fs = NULL;+ ls->linenumber = 1;+ ls->emiteol = 0;+ ls->lastline = 1;+ ls->braces = -1;+ ls->source = source;+ ls->envn = luaS_new(L, LUA_ENV); /* create env name */+ ls->short_nest = 0;+ luaS_fix(ls->envn); /* never collect this name */+ luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */+}++++/*+** =======================================================+** LEXICAL ANALYZER+** =======================================================+*/++++static int check_next (LexState *ls, const char *set) {+ if (ls->current == '\0' || !strchr(set, ls->current))+ return 0;+ save_and_next(ls);+ return 1;+}+++/*+** change all characters 'from' in buffer to 'to'+*/+static void buffreplace (LexState *ls, char from, char to) {+ size_t n = luaZ_bufflen(ls->buff);+ char *p = luaZ_buffer(ls->buff);+ while (n--)+ if (p[n] == from) p[n] = to;+}+++#if !defined(getlocaledecpoint)+#define getlocaledecpoint() (localeconv()->decimal_point[0])+#endif+++#define buff2d(b,e) luaO_str2d(luaZ_buffer(b), luaZ_bufflen(b) - 1, e)++/*+** in case of format error, try to change decimal point separator to+** the one defined in the current locale and check again+*/+static void trydecpoint (LexState *ls, SemInfo *seminfo) {+ char old = ls->decpoint;+ ls->decpoint = getlocaledecpoint();+ buffreplace(ls, old, ls->decpoint); /* try new decimal separator */+ if (!buff2d(ls->buff, &seminfo->r)) {+ /* format error with correct decimal point: no more options */+ buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */+ lexerror(ls, "malformed number", TK_NUMBER);+ }+}+++/* LUA_NUMBER */+/*+** this function is quite liberal in what it accepts, as 'luaO_str2d'+** will reject ill-formed numerals.+*/+static void read_numeral (LexState *ls, SemInfo *seminfo) {+ int first = ls->current;+ lua_assert(lisdigit(ls->current));+ save_and_next(ls);+ int hexa = 0;+ if (first == '0') {+ if (check_next(ls, "Xx")) { /* hexadecimal? */+ hexa = 1;+ } else check_next(ls, "Bb"); /* binary? */+ }+ for (;;) {+ if ((hexa ? lisxdigit(ls->current) : lisdigit(ls->current)) || ls->current == '.')+ save_and_next(ls);+ else break;+ }+ save(ls, '\0');+ buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */+ if (!buff2d(ls->buff, &seminfo->r)) /* format error? */+ trydecpoint(ls, seminfo); /* try to update decimal point separator */+}+++/*+** skip a sequence '[=*[' or ']=*]' and return its number of '='s or+** -1 if sequence is malformed+*/+static int skip_sep (LexState *ls) {+ int count = 0;+ int s = ls->current;+ lua_assert(s == '[' || s == ']');+ save_and_next(ls);+ while (ls->current == '=') {+ save_and_next(ls);+ count++;+ }+ return (ls->current == s) ? count : (-count) - 1;+}+++static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) {+ save_and_next(ls); /* skip 2nd `[' */+ if (currIsNewline(ls)) /* string starts with a newline? */+ inclinenumber(ls); /* skip it */+ for (;;) {+ switch (ls->current) {+ case EOZ:+ lexerror(ls, (seminfo) ? "unfinished long string" :+ "unfinished long comment", TK_EOS);+ break; /* to avoid warnings */+ case ']': {+ if (skip_sep(ls) == sep) {+ save_and_next(ls); /* skip 2nd `]' */+ goto endloop;+ }+ break;+ }+ case '\n': case '\r': {+ save(ls, '\n');+ inclinenumber(ls);+ if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */+ break;+ }+ default: {+ if (seminfo) save_and_next(ls);+ else next(ls);+ }+ }+ } endloop:+ if (seminfo)+ seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep),+ luaZ_bufflen(ls->buff) - 2*(2 + sep));+}+++static void escerror (LexState *ls, int *c, int n, const char *msg) {+ int i;+ luaZ_resetbuffer(ls->buff); /* prepare error message */+ save(ls, '\\');+ for (i = 0; i < n && c[i] != EOZ; i++)+ save(ls, c[i]);+ lexerror(ls, msg, TK_STRING);+}+++static int readhexaesc (LexState *ls) {+ int c[3], i; /* keep input for error message */+ int r = 0; /* result accumulator */+ c[0] = 'x'; /* for error message */+ for (i = 1; i < 3; i++) { /* read two hexadecimal digits */+ c[i] = next(ls);+ if (!lisxdigit(c[i]))+ escerror(ls, c, i + 1, "hexadecimal digit expected");+ r = (r << 4) + luaO_hexavalue(c[i]);+ }+ return r;+}+++static int readdecesc (LexState *ls) {+ int c[3], i;+ int r = 0; /* result accumulator */+ for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */+ c[i] = ls->current;+ r = 10*r + c[i] - '0';+ next(ls);+ }+ if (r > UCHAR_MAX)+ escerror(ls, c, i, "decimal escape too large");+ return r;+}+++static void read_string (LexState *ls, int del, SemInfo *seminfo) {+ save_and_next(ls); /* keep delimiter (for error messages) */+ while (ls->current != del) {+ switch (ls->current) {+ case EOZ:+ lexerror(ls, "unfinished string", TK_EOS);+ break; /* to avoid warnings */+ case '\n':+ case '\r':+ lexerror(ls, "unfinished string", TK_STRING);+ break; /* to avoid warnings */+ case '\\': { /* escape sequences */+ int c; /* final character to be saved */+ next(ls); /* do not save the `\' */+ switch (ls->current) {+ case '*': c = '\1'; goto read_save;+ case '#': c = '\2'; goto read_save;+ case '-': c = '\3'; goto read_save;+ case '|': c = '\4'; goto read_save;+ case '+': c = '\5'; goto read_save;+ case '^': c = '\6'; goto read_save;+ case 'a': c = '\a'; goto read_save;+ case 'b': c = '\b'; goto read_save;+ case 'f': c = '\f'; goto read_save;+ case 'n': c = '\n'; goto read_save;+ case 'r': c = '\r'; goto read_save;+ case 't': c = '\t'; goto read_save;+ case 'v': c = '\v'; goto read_save;+ case 'x': c = readhexaesc(ls); goto read_save;+ case '\n': case '\r':+ inclinenumber(ls); c = '\n'; goto only_save;+ case '\\': case '\"': case '\'':+ c = ls->current; goto read_save;+ case EOZ: goto no_save; /* will raise an error next loop */+ case 'z': { /* zap following span of spaces */+ next(ls); /* skip the 'z' */+ while (lisspace(ls->current)) {+ if (currIsNewline(ls)) inclinenumber(ls);+ else next(ls);+ }+ goto no_save;+ }+ default: {+ if (!lisdigit(ls->current))+ escerror(ls, &ls->current, 1, "invalid escape sequence");+ /* digital escape \ddd */+ c = readdecesc(ls);+ goto only_save;+ }+ }+ read_save: next(ls); /* read next character */+ only_save: save(ls, c); /* save 'c' */+ no_save: break;+ }+ default:+ save_and_next(ls);+ }+ }+ save_and_next(ls); /* skip delimiter */+ seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1,+ luaZ_bufflen(ls->buff) - 2);+}+++static int llex (LexState *ls, SemInfo *seminfo) {+ luaZ_resetbuffer(ls->buff);+ for (;;) {+ switch (ls->current) {+ case '\n': case '\r': { /* line breaks */+ inclinenumber(ls);+ if (ls->emiteol) { ls->emiteol = 0; return TK_EOL; }+ break;+ }+ case ' ': case '\f': case '\t': case '\v': { /* spaces */+ next(ls);+ break;+ }+ case '?': { /* '?' (shorthand print) */+ next(ls);+ ls->emiteol = 1;+ return TK_PRINT;+ }+ case '-': { /* '-' or '-=' or '--' (comment) */+ next(ls);+ if (ls->current == '=') { next(ls); return TK_SUBE; }+ else if (ls->current != '-') return '-';+ /* else is a comment */+ next(ls);+ if (ls->current == '[') { /* long comment? */+ int sep = skip_sep(ls);+ luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */+ if (sep >= 0) {+ read_long_string(ls, NULL, sep); /* skip long comment */+ luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */+ break;+ }+ }+ /* else short comment */+ while (!currIsNewline(ls) && ls->current != EOZ)+ next(ls); /* skip until end of line (or end of file) */+ break;+ }+ case '/': { /* '/' or '/=' or '//' (short comment) */+ next(ls);+ if (ls->current == '=') { next(ls); return TK_DIVE; }+ else if (ls->current != '/') return '/';+ next(ls);+ while (!currIsNewline(ls) && ls->current != EOZ)+ next(ls); /* skip until end of line (or end of file) */+ break;+ }+ case '+': case '*': case '%': case '&':+ case '|': case '~': case '!': case '\\': {+ /* '+', '*', '%', '\', '&', '|', '!', '~', and+ the '+=' etc. counterparts */+ int c = ls->current;+ next(ls);+ if (ls->current != '=') return c;+ else {+ next(ls);+ switch (c) {+ case '+': return TK_ADDE;+ case '*': return TK_MULE;+ case '%': return TK_MODE;+ case '&': return TK_BANDE;+ case '|': return TK_BORE;+ case '~': return TK_NE;+ case '!': return TK_NE2;+ case '\\': default: return TK_IDIVE;+ }+ }+ }+ case '[': { /* long string or simply '[' */+ int sep = skip_sep(ls);+ if (sep >= 0) {+ read_long_string(ls, seminfo, sep);+ return TK_STRING;+ }+ else if (sep == -1) return '[';+ else lexerror(ls, "invalid long string delimiter", TK_STRING);+ }+ case '=': {+ next(ls);+ if (ls->current != '=') return '=';+ else { next(ls); return TK_EQ; }+ }+ case '<': { /* '<=' or '<' or '<<=' or '<<' or '<<>=' or '<<>' */+ next(ls);+ if (ls->current == '=') { next(ls); return TK_LE; }+ else if (ls->current != '<') return '<';+ next(ls);+ if (ls->current == '=') { next(ls); return TK_SHLE; }+ else if (ls->current != '>') return TK_SHL;+ next(ls);+ if (ls->current == '=') { next(ls); return TK_ROTLE; }+ else return TK_ROTL;+ }+ case '^': { /* '^=' or '^' or '^^' or '^^=' */+ next(ls);+ if (ls->current == '=') { next(ls); return TK_POWE; }+ else if (ls->current != '^') return '^';+ next(ls);+ if (ls->current == '=') { next(ls); return TK_BXORE; }+ else return TK_BXOR;+ }+ case '>': { /* '>=', '>', '>>=', '>><=', >><', '>>', '>>>=', or '>>>' */+ next(ls);+ if (ls->current == '=') { next(ls); return TK_GE; }+ else if (ls->current != '>') return '>';+ next(ls);+ if (ls->current == '=') { next(ls); return TK_SHRE; }+ else if (ls->current == '<') {+ next(ls);+ if (ls->current == '=') { next(ls); return TK_ROTRE; }+ else return TK_ROTR;+ }+ else if (ls->current != '>') return TK_SHR;+ next(ls);+ if (ls->current == '=') { next(ls); return TK_LSHRE; }+ else return TK_LSHR;+ }+ case ':': {+ next(ls);+ if (ls->current != ':') return ':';+ else { next(ls); return TK_DBCOLON; }+ }+ case '"': case '\'': { /* short literal strings */+ read_string(ls, ls->current, seminfo);+ return TK_STRING;+ }+ case '.': { /* '.', '..', '..=', '...', or number */+ save_and_next(ls);+ if (check_next(ls, ".")) {+ if (check_next(ls, "."))+ return TK_DOTS; /* '...' */+ else if (check_next(ls, "="))+ return TK_CONCATE; /* '..=' */+ else return TK_CONCAT; /* '..' */+ }+ else if (!lisdigit(ls->current)) return '.';+ /* else go through */+ }+ case '0': case '1': case '2': case '3': case '4':+ case '5': case '6': case '7': case '8': case '9': {+ read_numeral(ls, seminfo);+ return TK_NUMBER;+ }+ case EOZ: {+ return TK_EOS;+ }+ default: {+ if (lislalpha(ls->current)) { /* identifier or reserved word? */+ TString *ts;+ do {+ save_and_next(ls);+ } while (lislalnum(ls->current));+ ts = luaX_newstring(ls, luaZ_buffer(ls->buff),+ luaZ_bufflen(ls->buff));+ seminfo->ts = ts;+ if (isreserved(ts)) /* reserved word? */+ return ts->tsv.extra - 1 + FIRST_RESERVED;+ else {+ return TK_NAME;+ }+ }+ else { /* single-char tokens (+ - / ...) */+ int c = ls->current;+ ls->braces += c == ')' ? -1 : /* handle brace count for short if */+ c == '(' ? ls->braces > 0 ? 1 : -1 : 0;+ next(ls);+ return c;+ }+ }+ }+ }+}+++void luaX_next (LexState *ls) {+ ls->lastline = ls->linenumber;+ if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */+ ls->t = ls->lookahead; /* use this one */+ ls->lookahead.token = TK_EOS; /* and discharge it */+ }+ else+ ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */+}+++int luaX_lookahead (LexState *ls) {+ lua_assert(ls->lookahead.token == TK_EOS);+ ls->lookahead.token = llex(ls, &ls->lookahead.seminfo);+ return ls->lookahead.token;+}+diff --git a/games/numpico/src/femto8/lua/llex.h b/games/numpico/src/femto8/lua/llex.hnew file mode 100644index 00000000..510baac5--- /dev/null+++ b/games/numpico/src/femto8/lua/llex.h@@ -0,0 +1,88 @@+/*+** $Id: llex.h,v 1.72 2011/11/30 12:43:51 roberto Exp $+** Lexical Analyzer+** See Copyright Notice in lua.h+*/++#ifndef llex_h+#define llex_h++#include "lobject.h"+#include "lzio.h"+++#define FIRST_RESERVED 257++++/*+* WARNING: if you change the order of this enumeration,+* grep "ORDER RESERVED"+*/+enum RESERVED {+ /* terminal symbols denoted by reserved words */+ TK_AND = FIRST_RESERVED, TK_BREAK,+ TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION,+ TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,+ TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,+ /* other terminal symbols */+ TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_NE2, TK_DBCOLON,+ TK_EOS, TK_NUMBER, TK_NAME, TK_STRING, TK_PRINT, TK_EOL,+ TK_BXOR, TK_SHL, TK_SHR, TK_LSHR, TK_ROTL, TK_ROTR,+ /* these must be last and match "ORDER OPR" */+ TK_ADDE, TK_SUBE, TK_MULE, TK_DIVE, TK_MODE, TK_POWE, TK_IDIVE,+ TK_BANDE, TK_BORE, TK_BXORE, TK_SHLE, TK_SHRE, TK_LSHRE, TK_ROTLE,+ TK_ROTRE, TK_CONCATE,+};++/* number of reserved words */+#define NUM_RESERVED (cast(int, TK_WHILE-FIRST_RESERVED+1))+++typedef union {+ lua_Number r;+ TString *ts;+} SemInfo; /* semantics information */+++typedef struct Token {+ int token;+ SemInfo seminfo;+} Token;+++/* state of the lexer plus state of the parser when shared by all+ functions */+typedef struct LexState {+ int current; /* current character (charint) */+ int linenumber; /* input line counter */+ int atsol; /* are we at start of line? */+ int emiteol; /* should EOL be emitted? */+ int lastline; /* line of last token `consumed' */+ int braces; /* braces context */+ int short_nest; /* nesting depth of active short-if/while blocks */+ Token t; /* current token */+ Token lookahead; /* look ahead token */+ struct FuncState *fs; /* current function (parser) */+ struct lua_State *L;+ ZIO *z; /* input stream */+ Mbuffer *buff; /* buffer for tokens */+ struct Dyndata *dyd; /* dynamic structures used by the parser */+ TString *source; /* current source name */+ TString *envn; /* environment variable name */+ char decpoint; /* locale decimal point */+} LexState;+++LUAI_FUNC void luaX_init (lua_State *L);+LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z,+ TString *source, int firstchar);+LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l);+LUAI_FUNC void luaX_next (LexState *ls);+LUAI_FUNC int luaX_lookahead (LexState *ls);+LUAI_FUNC l_noret luaX_syntaxerror (LexState *ls, const char *s);+LUAI_FUNC const char *luaX_token2str (LexState *ls, int token);+LUAI_FUNC void luaX_trackbraces (LexState *ls);+++#endifdiff --git a/games/numpico/src/femto8/lua/llimits.h b/games/numpico/src/femto8/lua/llimits.hnew file mode 100644index 00000000..927ad490--- /dev/null+++ b/games/numpico/src/femto8/lua/llimits.h@@ -0,0 +1,228 @@+/*+** $Id: llimits.h,v 1.103 2013/02/20 14:08:56 roberto Exp $+** Limits, basic types, and some other `installation-dependent' definitions+** See Copyright Notice in lua.h+*/++#ifndef llimits_h+#define llimits_h+++#include <limits.h>+#include <stddef.h>+++#include "lua.h"+++typedef unsigned LUA_INT32 lu_int32;++typedef LUAI_UMEM lu_mem;++typedef LUAI_MEM l_mem;++++/* chars used as small naturals (so that `char' is reserved for characters) */+typedef unsigned char lu_byte;+++#define MAX_SIZET ((size_t)(~(size_t)0)-2)++#define MAX_LUMEM ((lu_mem)(~(lu_mem)0)-2)++#define MAX_LMEM ((l_mem) ((MAX_LUMEM >> 1) - 2))+++#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */++/*+** conversion of pointer to integer+** this is for hashing only; there is no problem if the integer+** cannot hold the whole pointer value+*/+#define IntPoint(p) ((unsigned int)(lu_mem)(p))++++/* type to ensure maximum alignment */+#if !defined(LUAI_USER_ALIGNMENT_T)+#define LUAI_USER_ALIGNMENT_T union { double u; void *s; long l; }+#endif++typedef LUAI_USER_ALIGNMENT_T L_Umaxalign;+++/* result of a `usual argument conversion' over lua_Number */+typedef LUAI_UACNUMBER l_uacNumber;+++/* internal assertions for in-house debugging */+#if defined(lua_assert)+#define check_exp(c,e) (lua_assert(c), (e))+/* to avoid problems with conditions too long */+#define lua_longassert(c) { if (!(c)) lua_assert(0); }+#else+#define lua_assert(c) ((void)0)+#define check_exp(c,e) (e)+#define lua_longassert(c) ((void)0)+#endif++/*+** assertion for checking API calls+*/+#if !defined(luai_apicheck)++#if defined(LUA_USE_APICHECK)+#include <assert.h>+#define luai_apicheck(L,e) assert(e)+#else+#define luai_apicheck(L,e) lua_assert(e)+#endif++#endif++#define api_check(l,e,msg) luai_apicheck(l,(e) && msg)+++#if !defined(UNUSED)+#define UNUSED(x) ((void)(x)) /* to avoid warnings */+#endif+++#define cast(t, exp) ((t)(exp))++#define cast_byte(i) cast(lu_byte, (i))+#define cast_num(i) fix32_from_int(i)+#define cast_int(i) cast(int, (i))+#define cast_uchar(i) cast(unsigned char, (i))+++/*+** non-return type+*/+#if defined(__GNUC__)+#define l_noret void __attribute__((noreturn))+#elif defined(_MSC_VER)+#define l_noret void __declspec(noreturn)+#else+#define l_noret void+#endif++++/*+** maximum depth for nested C calls and syntactical nested non-terminals+** in a program. (Value must fit in an unsigned short int.)+*/+#if !defined(LUAI_MAXCCALLS)+#define LUAI_MAXCCALLS 200+#endif++/*+** maximum number of upvalues in a closure (both C and Lua). (Value+** must fit in an unsigned char.)+*/+#define MAXUPVAL UCHAR_MAX+++/*+** type for virtual-machine instructions+** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)+*/+typedef lu_int32 Instruction;++++/* maximum stack for a Lua function */+#define MAXSTACK 250++++/* minimum size for the string table (must be power of 2) */+#if !defined(MINSTRTABSIZE)+#define MINSTRTABSIZE 32+#endif+++/* minimum size for string buffer */+#if !defined(LUA_MINBUFFER)+#define LUA_MINBUFFER 32+#endif+++#if !defined(lua_lock)+#define lua_lock(L) ((void) 0)+#define lua_unlock(L) ((void) 0)+#endif++#if !defined(luai_threadyield)+#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);}+#endif+++/*+** these macros allow user-specific actions on threads when you defined+** LUAI_EXTRASPACE and need to do something extra when a thread is+** created/deleted/resumed/yielded.+*/+#if !defined(luai_userstateopen)+#define luai_userstateopen(L) ((void)L)+#endif++#if !defined(luai_userstateclose)+#define luai_userstateclose(L) ((void)L)+#endif++#if !defined(luai_userstatethread)+#define luai_userstatethread(L,L1) ((void)L)+#endif++#if !defined(luai_userstatefree)+#define luai_userstatefree(L,L1) ((void)L)+#endif++#if !defined(luai_userstateresume)+#define luai_userstateresume(L,n) ((void)L)+#endif++#if !defined(luai_userstateyield)+#define luai_userstateyield(L,n) ((void)L)+#endif++/*+** lua_number2int is a macro to convert lua_Number (fix32_t) to int.+** lua_number2integer is a macro to convert lua_Number to lua_Integer.+** lua_number2unsigned is a macro to convert a lua_Number to a lua_Unsigned.+** lua_unsigned2number is a macro to convert a lua_Unsigned to a lua_Number.+** luai_hashnum is defined in luaconf.h for fix32.+**+** For fix32_t, these all use fix32_to_int which does >> 16.+*/++#define lua_number2int(i,n) ((i) = fix32_to_int(n))+#define lua_number2integer(i,n) ((i) = (lua_Integer)fix32_to_int(n))+#define lua_number2unsigned(i,n) ((i) = (lua_Unsigned)(uint16_t)fix32_to_int(n))++#define lua_unsigned2number(u) fix32_from_int((int)(u))++++/*+** macro to control inclusion of some hard tests on stack reallocation+*/+#if !defined(HARDSTACKTESTS)+#define condmovestack(L) ((void)0)+#else+/* realloc stack keeping its size */+#define condmovestack(L) luaD_reallocstack((L), (L)->stacksize)+#endif++#if !defined(HARDMEMTESTS)+#define condchangemem(L) condmovestack(L)+#else+#define condchangemem(L) \+ ((void)(!(G(L)->gcrunning) || (luaC_fullgc(L, 0), 1)))+#endif++#endifdiff --git a/games/numpico/src/femto8/lua/lmem.c b/games/numpico/src/femto8/lua/lmem.cnew file mode 100644index 00000000..3f88496e--- /dev/null+++ b/games/numpico/src/femto8/lua/lmem.c@@ -0,0 +1,99 @@+/*+** $Id: lmem.c,v 1.84 2012/05/23 15:41:53 roberto Exp $+** Interface to Memory Manager+** See Copyright Notice in lua.h+*/+++#include <stddef.h>++#define lmem_c+#define LUA_CORE++#include "lua.h"++#include "ldebug.h"+#include "ldo.h"+#include "lgc.h"+#include "lmem.h"+#include "lobject.h"+#include "lstate.h"++++/*+** About the realloc function:+** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize);+** (`osize' is the old size, `nsize' is the new size)+**+** * frealloc(ud, NULL, x, s) creates a new block of size `s' (no+** matter 'x').+**+** * frealloc(ud, p, x, 0) frees the block `p'+** (in this specific case, frealloc must return NULL);+** particularly, frealloc(ud, NULL, 0, 0) does nothing+** (which is equivalent to free(NULL) in ANSI C)+**+** frealloc returns NULL if it cannot create or reallocate the area+** (any reallocation to an equal or smaller size cannot fail!)+*/++++#define MINSIZEARRAY 4+++void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems,+ int limit, const char *what) {+ void *newblock;+ int newsize;+ if (*size >= limit/2) { /* cannot double it? */+ if (*size >= limit) /* cannot grow even a little? */+ luaG_runerror(L, "too many %s (limit is %d)", what, limit);+ newsize = limit; /* still have at least one free place */+ }+ else {+ newsize = (*size)*2;+ if (newsize < MINSIZEARRAY)+ newsize = MINSIZEARRAY; /* minimum size */+ }+ newblock = luaM_reallocv(L, block, *size, newsize, size_elems);+ *size = newsize; /* update only when everything else is OK */+ return newblock;+}+++l_noret luaM_toobig (lua_State *L) {+ luaG_runerror(L, "memory allocation error: block too big");+}++++/*+** generic allocation routine.+*/+void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {+ void *newblock;+ global_State *g = G(L);+ size_t realosize = (block) ? osize : 0;+ lua_assert((realosize == 0) == (block == NULL));+#if defined(HARDMEMTESTS)+ if (nsize > realosize && g->gcrunning)+ luaC_fullgc(L, 1); /* force a GC whenever possible */+#endif+ newblock = (*g->frealloc)(g->ud, block, osize, nsize);+ if (newblock == NULL && nsize > 0) {+ api_check(L, nsize > realosize,+ "realloc cannot fail when shrinking a block");+ if (g->gcrunning) {+ luaC_fullgc(L, 1); /* try to free some memory... */+ newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */+ }+ if (newblock == NULL)+ luaD_throw(L, LUA_ERRMEM);+ }+ lua_assert((nsize == 0) == (newblock == NULL));+ g->GCdebt = (g->GCdebt + nsize) - realosize;+ return newblock;+}+diff --git a/games/numpico/src/femto8/lua/lmem.h b/games/numpico/src/femto8/lua/lmem.hnew file mode 100644index 00000000..5f850999--- /dev/null+++ b/games/numpico/src/femto8/lua/lmem.h@@ -0,0 +1,57 @@+/*+** $Id: lmem.h,v 1.40 2013/02/20 14:08:21 roberto Exp $+** Interface to Memory Manager+** See Copyright Notice in lua.h+*/++#ifndef lmem_h+#define lmem_h+++#include <stddef.h>++#include "llimits.h"+#include "lua.h"+++/*+** This macro avoids the runtime division MAX_SIZET/(e), as 'e' is+** always constant.+** The macro is somewhat complex to avoid warnings:+** +1 avoids warnings of "comparison has constant result";+** cast to 'void' avoids warnings of "value unused".+*/+#define luaM_reallocv(L,b,on,n,e) \+ (cast(void, \+ (cast(size_t, (n)+1) > MAX_SIZET/(e)) ? (luaM_toobig(L), 0) : 0), \+ luaM_realloc_(L, (b), (on)*(e), (n)*(e)))++#define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0)+#define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0)+#define luaM_freearray(L, b, n) luaM_reallocv(L, (b), n, 0, sizeof((b)[0]))++#define luaM_malloc(L,s) luaM_realloc_(L, NULL, 0, (s))+#define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t)))+#define luaM_newvector(L,n,t) \+ cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t)))++#define luaM_newobject(L,tag,s) luaM_realloc_(L, NULL, tag, (s))++#define luaM_growvector(L,v,nelems,size,t,limit,e) \+ if ((nelems)+1 > (size)) \+ ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e)))++#define luaM_reallocvector(L, v,oldn,n,t) \+ ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t))))++LUAI_FUNC l_noret luaM_toobig (lua_State *L);++/* not to be called directly */+LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize,+ size_t size);+LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int *size,+ size_t size_elem, int limit,+ const char *what);++#endif+diff --git a/games/numpico/src/femto8/lua/lobject.c b/games/numpico/src/femto8/lua/lobject.cnew file mode 100644index 00000000..eae16684--- /dev/null+++ b/games/numpico/src/femto8/lua/lobject.c@@ -0,0 +1,342 @@+/*+** $Id: lobject.c,v 2.58 2013/02/20 14:08:56 roberto Exp $+** Some generic functions over Lua objects+** See Copyright Notice in lua.h+*/++#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#define lobject_c+#define LUA_CORE++#include "lua.h"++#include "lctype.h"+#include "ldebug.h"+#include "ldo.h"+#include "lmem.h"+#include "lobject.h"+#include "lstate.h"+#include "lstring.h"+#include "lvm.h"++++LUAI_DDEF const TValue luaO_nilobject_ = {NILCONSTANT};+++/*+** converts an integer to a "floating point byte", represented as+** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if+** eeeee != 0 and (xxx) otherwise.+*/+int luaO_int2fb (unsigned int x) {+ int e = 0; /* exponent */+ if (x < 8) return x;+ while (x >= 0x10) {+ x = (x+1) >> 1;+ e++;+ }+ return ((e+1) << 3) | (cast_int(x) - 8);+}+++/* converts back */+int luaO_fb2int (int x) {+ int e = (x >> 3) & 0x1f;+ if (e == 0) return x;+ else return ((x & 7) + 8) << (e - 1);+}+++int luaO_ceillog2 (unsigned int x) {+ static const lu_byte log_2[256] = {+ 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8+ };+ int l = 0;+ x--;+ while (x >= 256) { l += 8; x >>= 8; }+ return l + log_2[x];+}+++lua_Number luaO_arith (lua_State *L, int op, lua_Number v1, lua_Number v2) {+ switch (op) {+ case LUA_OPADD: return luai_numadd(NULL, v1, v2);+ case LUA_OPSUB: return luai_numsub(NULL, v1, v2);+ case LUA_OPMUL: return luai_nummul(NULL, v1, v2);+ case LUA_OPDIV: return luai_numdiv(NULL, v1, v2);+ case LUA_OPMOD: return luai_nummod(NULL, v1, v2);+ case LUA_OPPOW: return luai_numpow(NULL, v1, v2);+ case LUA_OPIDIV: return luai_numidiv(NULL, v1, v2);+ case LUA_OPBAND: return luai_numband(NULL, v1, v2);+ case LUA_OPBOR: return luai_numbor(NULL, v1, v2);+ case LUA_OPBXOR: return luai_numbxor(NULL, v1, v2);+ case LUA_OPSHL: return luai_numshl(NULL, v1, v2);+ case LUA_OPSHR: return luai_numshr(NULL, v1, v2);+ case LUA_OPLSHR: return luai_numlshr(NULL, v1, v2);+ case LUA_OPROTL: return luai_numrotl(NULL, v1, v2);+ case LUA_OPROTR: return luai_numrotr(NULL, v1, v2);+ case LUA_OPUNM: return luai_numunm(NULL, v1);+ case LUA_OPBNOT: return luai_numbnot(NULL, v1);+ case LUA_OPPEEK: return luai_numpeek(L, v1);+ case LUA_OPPEEK2: return luai_numpeek2(L, v1);+ case LUA_OPPEEK4: return luai_numpeek4(L, v1);+ default: lua_assert(0); return 0;+ }+}+++int luaO_hexavalue (int c) {+ if (lisdigit(c)) return c - '0';+ else return ltolower(c) - 'a' + 10;+}+++static int isneg (const char **s) {+ if (**s == '-') { (*s)++; return 1; }+ else if (**s == '+') (*s)++;+ return 0;+}+++#if false && !defined(lua_strx2number)++#include <math.h>+++static lua_Number readhexa (const char **s, lua_Number r, int *count) {+ for (; lisxdigit(cast_uchar(**s)); (*s)++) { /* read integer part */+ r = (r * cast_num(16.0)) + cast_num(luaO_hexavalue(cast_uchar(**s)));+ (*count)++;+ }+ return r;+}+++/*+** convert an hexadecimal numeric string to a number, following+** C99 specification for 'strtod'+*/+static lua_Number lua_strx2number (const char *s, char **endptr) {+ lua_Number r = 0.0;+ int e = 0, i = 0;+ int neg = 0; /* 1 if number is negative */+ *endptr = cast(char *, s); /* nothing is valid yet */+ while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */+ neg = isneg(&s); /* check signal */+ if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */+ return 0.0; /* invalid format (no '0x') */+ s += 2; /* skip '0x' */+ r = readhexa(&s, r, &i); /* read integer part */+ if (*s == '.') {+ s++; /* skip dot */+ r = readhexa(&s, r, &e); /* read fractional part */+ }+ if (i == 0 && e == 0)+ return 0.0; /* invalid format (no digit) */+ e *= -4; /* each fractional digit divides value by 2^-4 */+ *endptr = cast(char *, s); /* valid up to here */+ if (*s == 'p' || *s == 'P') { /* exponent part? */+ int exp1 = 0;+ int neg1;+ s++; /* skip 'p' */+ neg1 = isneg(&s); /* signal */+ if (!lisdigit(cast_uchar(*s)))+ goto ret; /* must have at least one digit */+ while (lisdigit(cast_uchar(*s))) /* read exponent */+ exp1 = exp1 * 10 + *(s++) - '0';+ if (neg1) exp1 = -exp1;+ e += exp1;+ }+ *endptr = cast(char *, s); /* valid up to here */+ ret:+ if (neg) r = -r;+ return l_mathop(ldexp)(r, e);+}++#endif+++static lua_Number readany (const char **s, lua_Number r, int *count, int base, int max) {+ for (; lisxdigit(cast_uchar(**s)); (*s)++, max--) {+ if (max > 0) {+ int d = luaO_hexavalue(cast_uchar(**s));+ if (d >= base) break;+ r = fix32_add(fix32_mul(r, cast_num(base)), cast_num(d));+ (*count)++;+ }+ }+ return r;+}+++/*+** convert an hexadecimal or binary numeric string to a number+*/+static lua_Number lua_strany2number (const char *s, char **endptr, int base) {+ lua_Number r = FIX32_ZERO, f = FIX32_ZERO;+ int e = 0, i = 0;+ int neg = 0; /* 1 if number is negative */+ *endptr = cast(char *, s); /* nothing is valid yet */+ while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */+ neg = isneg(&s); /* check sign */+ if (*s != '0' || (base == 2 && *(s + 1) != 'b' && *(s + 1) != 'B')+ || (base == 16 && *(s + 1) != 'x' && *(s + 1) != 'X'))+ return FIX32_ZERO; /* invalid format (no '0b' or '0x') */+ s += 2; /* skip '0x' or '0b' */+ r = readany(&s, r, &i, base, INT_MAX); /* read integer part */+ if (*s == '.') {+ s++; /* skip dot */+ f = readany(&s, f, &e, base, base == 2 ? 16 : 4); /* read fractional part */+ }+ if (i == 0 && e == 0)+ return FIX32_ZERO; /* invalid format (no digit) */+ *endptr = cast(char *, s); /* valid up to here */+ r = fix32_from_bits(fix32_bits(r) | (uint32_t)fix32_bits(f) >> (base == 2 ? e : e * 4));+ return neg ? fix32_neg(r) : r;+}+++int luaO_str2d (const char *s, size_t len, lua_Number *result) {+ char *endptr;+ if (strpbrk(s, "nN")) /* reject 'inf' and 'nan' */+ return 0;+ else if (strpbrk(s, "xX")) /* hexa? */+ *result = lua_strany2number(s, &endptr, 16);+ else if (strpbrk(s, "bB")) /* binary? */+ *result = lua_strany2number(s, &endptr, 2);+ else+ *result = lua_str2number(s, &endptr);+ if (endptr == s) return 0; /* nothing recognized */+ while (lisspace(cast_uchar(*endptr))) endptr++;+ return (endptr == s + len); /* OK if no trailing characters */+}++++static void pushstr (lua_State *L, const char *str, size_t l) {+ setsvalue2s(L, L->top++, luaS_newlstr(L, str, l));+}+++/* this function handles only `%d', `%c', %f, %p, and `%s' formats */+const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {+ int n = 0;+ for (;;) {+ const char *e = strchr(fmt, '%');+ if (e == NULL) break;+ luaD_checkstack(L, 2); /* fmt + item */+ pushstr(L, fmt, e - fmt);+ switch (*(e+1)) {+ case 's': {+ const char *s = va_arg(argp, char *);+ if (s == NULL) s = "(null)";+ pushstr(L, s, strlen(s));+ break;+ }+ case 'c': {+ char buff;+ buff = cast(char, va_arg(argp, int));+ pushstr(L, &buff, 1);+ break;+ }+ case 'd': {+ setnvalue(L->top++, cast_num(va_arg(argp, int)));+ break;+ }+ case 'f': {+ setnvalue(L->top++, (lua_Number)va_arg(argp, l_uacNumber));+ break;+ }+ case 'p': {+ char buff[4*sizeof(void *) + 8]; /* should be enough space for a `0x%llx' */+ int l = sprintf(buff, "0x%llx", (long long int)(intptr_t)va_arg(argp, void *));+ pushstr(L, buff, l);+ break;+ }+ case '%': {+ pushstr(L, "%", 1);+ break;+ }+ default: {+ luaG_runerror(L,+ "invalid option " LUA_QL("%%%c") " to " LUA_QL("lua_pushfstring"),+ *(e + 1));+ }+ }+ n += 2;+ fmt = e+2;+ }+ luaD_checkstack(L, 1);+ pushstr(L, fmt, strlen(fmt));+ if (n > 0) luaV_concat(L, n + 1);+ return svalue(L->top - 1);+}+++const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {+ const char *msg;+ va_list argp;+ va_start(argp, fmt);+ msg = luaO_pushvfstring(L, fmt, argp);+ va_end(argp);+ return msg;+}+++/* number of chars of a literal string without the ending \0 */+#define LL(x) (sizeof(x)/sizeof(char) - 1)++#define RETS "..."+#define PRE "[string \""+#define POS "\"]"++#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )++void luaO_chunkid (char *out, const char *source, size_t bufflen) {+ size_t l = strlen(source);+ if (*source == '=') { /* 'literal' source */+ if (l <= bufflen) /* small enough? */+ memcpy(out, source + 1, l * sizeof(char));+ else { /* truncate it */+ addstr(out, source + 1, bufflen - 1);+ *out = '\0';+ }+ }+ else if (*source == '@') { /* file name */+ if (l <= bufflen) /* small enough? */+ memcpy(out, source + 1, l * sizeof(char));+ else { /* add '...' before rest of name */+ addstr(out, RETS, LL(RETS));+ bufflen -= LL(RETS);+ memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char));+ }+ }+ else { /* string; format as [string "source"] */+ const char *nl = strchr(source, '\n'); /* find first new line (if any) */+ addstr(out, PRE, LL(PRE)); /* add prefix */+ bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */+ if (l < bufflen && nl == NULL) { /* small one-line source? */+ addstr(out, source, l); /* keep it */+ }+ else {+ if (nl != NULL) l = nl - source; /* stop at first newline */+ if (l > bufflen) l = bufflen;+ addstr(out, source, l);+ addstr(out, RETS, LL(RETS));+ }+ memcpy(out, POS, (LL(POS) + 1) * sizeof(char));+ }+}+diff --git a/games/numpico/src/femto8/lua/lobject.h b/games/numpico/src/femto8/lua/lobject.hnew file mode 100644index 00000000..411dbd85--- /dev/null+++ b/games/numpico/src/femto8/lua/lobject.h@@ -0,0 +1,607 @@+/*+** $Id: lobject.h,v 2.71.1.1 2013/04/12 18:48:47 roberto Exp roberto $+** Type definitions for Lua objects+** See Copyright Notice in lua.h+*/+++#ifndef lobject_h+#define lobject_h+++#include <stdarg.h>+++#include "llimits.h"+#include "lua.h"+++/*+** Extra tags for non-values+*/+#define LUA_TPROTO LUA_NUMTAGS+#define LUA_TUPVAL (LUA_NUMTAGS+1)+#define LUA_TDEADKEY (LUA_NUMTAGS+2)++/*+** number of all possible tags (including LUA_TNONE but excluding DEADKEY)+*/+#define LUA_TOTALTAGS (LUA_TUPVAL+2)+++/*+** tags for Tagged Values have the following use of bits:+** bits 0-3: actual tag (a LUA_T* value)+** bits 4-5: variant bits+** bit 6: whether value is collectable+*/++#define VARBITS (3 << 4)+++/*+** LUA_TFUNCTION variants:+** 0 - Lua function+** 1 - light C function+** 2 - regular C function (closure)+*/++/* Variant tags for functions */+#define LUA_TLCL (LUA_TFUNCTION | (0 << 4)) /* Lua closure */+#define LUA_TLCF (LUA_TFUNCTION | (1 << 4)) /* light C function */+#define LUA_TCCL (LUA_TFUNCTION | (2 << 4)) /* C closure */+++/* Variant tags for strings */+#define LUA_TSHRSTR (LUA_TSTRING | (0 << 4)) /* short strings */+#define LUA_TLNGSTR (LUA_TSTRING | (1 << 4)) /* long strings */+++/* Bit mark for collectable types */+#define BIT_ISCOLLECTABLE (1 << 6)++/* mark a tag as collectable */+#define ctb(t) ((t) | BIT_ISCOLLECTABLE)+++/*+** Union of all collectable objects+*/+typedef union GCObject GCObject;+++/*+** Common Header for all collectable objects (in macro form, to be+** included in other objects)+*/+#define CommonHeader GCObject *next; lu_byte tt; lu_byte marked+++/*+** Common header in struct form+*/+typedef struct GCheader {+ CommonHeader;+} GCheader;++++/*+** Union of all Lua values+*/+typedef union Value Value;+++#define numfield lua_Number n; /* numbers */++++/*+** Tagged Values. This is the basic representation of values in Lua,+** an actual value plus a tag with its type.+*/++#define TValuefields Value value_; int tt_++typedef struct lua_TValue TValue;+++/* macro defining a nil value */+#define NILCONSTANT {NULL}, LUA_TNIL+++#define val_(o) ((o)->value_)+#define num_(o) (val_(o).n)+++/* raw type tag of a TValue */+#define rttype(o) ((o)->tt_)++/* tag with no variants (bits 0-3) */+#define novariant(x) ((x) & 0x0F)++/* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */+#define ttype(o) (rttype(o) & 0x3F)++/* type tag of a TValue with no variants (bits 0-3) */+#define ttypenv(o) (novariant(rttype(o)))+++/* Macros to test type */+#define checktag(o,t) (rttype(o) == (t))+#define checktype(o,t) (ttypenv(o) == (t))+#define ttisnumber(o) checktag((o), LUA_TNUMBER)+#define ttisnil(o) checktag((o), LUA_TNIL)+#define ttisboolean(o) checktag((o), LUA_TBOOLEAN)+#define ttislightuserdata(o) checktag((o), LUA_TLIGHTUSERDATA)+#define ttisstring(o) checktype((o), LUA_TSTRING)+#define ttisshrstring(o) checktag((o), ctb(LUA_TSHRSTR))+#define ttislngstring(o) checktag((o), ctb(LUA_TLNGSTR))+#define ttistable(o) checktag((o), ctb(LUA_TTABLE))+#define ttisfunction(o) checktype(o, LUA_TFUNCTION)+#define ttisclosure(o) ((rttype(o) & 0x1F) == LUA_TFUNCTION)+#define ttisCclosure(o) checktag((o), ctb(LUA_TCCL))+#define ttisLclosure(o) checktag((o), ctb(LUA_TLCL))+#define ttislcf(o) checktag((o), LUA_TLCF)+#define ttisuserdata(o) checktag((o), ctb(LUA_TUSERDATA))+#define ttisthread(o) checktag((o), ctb(LUA_TTHREAD))+#define ttisdeadkey(o) checktag((o), LUA_TDEADKEY)++#define ttisequal(o1,o2) (rttype(o1) == rttype(o2))++/* Macros to access values */+#define nvalue(o) check_exp(ttisnumber(o), num_(o))+#define gcvalue(o) check_exp(iscollectable(o), val_(o).gc)+#define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p)+#define rawtsvalue(o) check_exp(ttisstring(o), &val_(o).gc->ts)+#define tsvalue(o) (&rawtsvalue(o)->tsv)+#define rawuvalue(o) check_exp(ttisuserdata(o), &val_(o).gc->u)+#define uvalue(o) (&rawuvalue(o)->uv)+#define clvalue(o) check_exp(ttisclosure(o), &val_(o).gc->cl)+#define clLvalue(o) check_exp(ttisLclosure(o), &val_(o).gc->cl.l)+#define clCvalue(o) check_exp(ttisCclosure(o), &val_(o).gc->cl.c)+#define fvalue(o) check_exp(ttislcf(o), val_(o).f)+#define hvalue(o) check_exp(ttistable(o), &val_(o).gc->h)+#define bvalue(o) check_exp(ttisboolean(o), val_(o).b)+#define thvalue(o) check_exp(ttisthread(o), &val_(o).gc->th)+/* a dead value may get the 'gc' field, but cannot access its contents */+#define deadvalue(o) check_exp(ttisdeadkey(o), cast(void *, val_(o).gc))++#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))+++#define iscollectable(o) (rttype(o) & BIT_ISCOLLECTABLE)+++/* Macros for internal tests */+#define righttt(obj) (ttype(obj) == gcvalue(obj)->gch.tt)++#define checkliveness(g,obj) \+ lua_longassert(!iscollectable(obj) || \+ (righttt(obj) && !isdead(g,gcvalue(obj))))+++/* Macros to set values */+#define settt_(o,t) ((o)->tt_=(t))++#define setnvalue(obj,x) \+ { TValue *io=(obj); num_(io)=(x); settt_(io, LUA_TNUMBER); }++#define setnilvalue(obj) settt_(obj, LUA_TNIL)++#define setfvalue(obj,x) \+ { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_TLCF); }++#define setpvalue(obj,x) \+ { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_TLIGHTUSERDATA); }++#define setbvalue(obj,x) \+ { TValue *io=(obj); val_(io).b=(x); settt_(io, LUA_TBOOLEAN); }++#define setgcovalue(L,obj,x) \+ { TValue *io=(obj); GCObject *i_g=(x); \+ val_(io).gc=i_g; settt_(io, ctb(gch(i_g)->tt)); }++#define setsvalue(L,obj,x) \+ { TValue *io=(obj); \+ TString *x_ = (x); \+ val_(io).gc=cast(GCObject *, x_); settt_(io, ctb(x_->tsv.tt)); \+ checkliveness(G(L),io); }++#define setuvalue(L,obj,x) \+ { TValue *io=(obj); \+ val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TUSERDATA)); \+ checkliveness(G(L),io); }++#define setthvalue(L,obj,x) \+ { TValue *io=(obj); \+ val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTHREAD)); \+ checkliveness(G(L),io); }++#define setclLvalue(L,obj,x) \+ { TValue *io=(obj); \+ val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TLCL)); \+ checkliveness(G(L),io); }++#define setclCvalue(L,obj,x) \+ { TValue *io=(obj); \+ val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TCCL)); \+ checkliveness(G(L),io); }++#define sethvalue(L,obj,x) \+ { TValue *io=(obj); \+ val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTABLE)); \+ checkliveness(G(L),io); }++#define setdeadvalue(obj) settt_(obj, LUA_TDEADKEY)++++#define setobj(L,obj1,obj2) \+ { const TValue *io2=(obj2); TValue *io1=(obj1); \+ io1->value_ = io2->value_; io1->tt_ = io2->tt_; \+ checkliveness(G(L),io1); }+++/*+** different types of assignments, according to destination+*/++/* from stack to (same) stack */+#define setobjs2s setobj+/* to stack (not from same stack) */+#define setobj2s setobj+#define setsvalue2s setsvalue+#define sethvalue2s sethvalue+#define setptvalue2s setptvalue+/* from table to same table */+#define setobjt2t setobj+/* to table */+#define setobj2t setobj+/* to new object */+#define setobj2n setobj+#define setsvalue2n setsvalue+++/* check whether a number is valid (useful only for NaN trick) */+#define luai_checknum(L,o,c) { /* empty */ }+++/*+** {======================================================+** NaN Trick+** =======================================================+*/+#if defined(LUA_NANTRICK)++/*+** numbers are represented in the 'd_' field. All other values have the+** value (NNMARK | tag) in 'tt__'. A number with such pattern would be+** a "signaled NaN", which is never generated by regular operations by+** the CPU (nor by 'strtod')+*/++/* allows for external implementation for part of the trick */+#if !defined(NNMARK) /* { */+++#if !defined(LUA_IEEEENDIAN)+#error option 'LUA_NANTRICK' needs 'LUA_IEEEENDIAN'+#endif+++#define NNMARK 0x7FF7A500+#define NNMASK 0x7FFFFF00++#undef TValuefields+#undef NILCONSTANT++#if (LUA_IEEEENDIAN == 0) /* { */++/* little endian */+#define TValuefields \+ union { struct { Value v__; int tt__; } i; double d__; } u+#define NILCONSTANT {{{NULL}, tag2tt(LUA_TNIL)}}+/* field-access macros */+#define v_(o) ((o)->u.i.v__)+#define d_(o) ((o)->u.d__)+#define tt_(o) ((o)->u.i.tt__)++#else /* }{ */++/* big endian */+#define TValuefields \+ union { struct { int tt__; Value v__; } i; double d__; } u+#define NILCONSTANT {{tag2tt(LUA_TNIL), {NULL}}}+/* field-access macros */+#define v_(o) ((o)->u.i.v__)+#define d_(o) ((o)->u.d__)+#define tt_(o) ((o)->u.i.tt__)++#endif /* } */++#endif /* } */+++/* correspondence with standard representation */+#undef val_+#define val_(o) v_(o)+#undef num_+#define num_(o) d_(o)+++#undef numfield+#define numfield /* no such field; numbers are the entire struct */++/* basic check to distinguish numbers from non-numbers */+#undef ttisnumber+#define ttisnumber(o) ((tt_(o) & NNMASK) != NNMARK)++#define tag2tt(t) (NNMARK | (t))++#undef rttype+#define rttype(o) (ttisnumber(o) ? LUA_TNUMBER : tt_(o) & 0xff)++#undef settt_+#define settt_(o,t) (tt_(o) = tag2tt(t))++#undef setnvalue+#define setnvalue(obj,x) \+ { TValue *io_=(obj); num_(io_)=(x); lua_assert(ttisnumber(io_)); }++#undef setobj+#define setobj(L,obj1,obj2) \+ { const TValue *o2_=(obj2); TValue *o1_=(obj1); \+ o1_->u = o2_->u; \+ checkliveness(G(L),o1_); }+++/*+** these redefinitions are not mandatory, but these forms are more efficient+*/++#undef checktag+#undef checktype+#define checktag(o,t) (tt_(o) == tag2tt(t))+#define checktype(o,t) (ctb(tt_(o) | VARBITS) == ctb(tag2tt(t) | VARBITS))++#undef ttisequal+#define ttisequal(o1,o2) \+ (ttisnumber(o1) ? ttisnumber(o2) : (tt_(o1) == tt_(o2)))+++#undef luai_checknum+#define luai_checknum(L,o,c) { if (!ttisnumber(o)) c; }++#endif+/* }====================================================== */++++/*+** {======================================================+** types and prototypes+** =======================================================+*/+++union Value {+ GCObject *gc; /* collectable objects */+ void *p; /* light userdata */+ int b; /* booleans */+ lua_CFunction f; /* light C functions */+ numfield /* numbers */+};+++struct lua_TValue {+ TValuefields;+};+++typedef TValue *StkId; /* index to stack elements */+++++/*+** Header for string value; string bytes follow the end of this structure+*/+typedef union TString {+ L_Umaxalign dummy; /* ensures maximum alignment for strings */+ struct {+ CommonHeader;+ lu_byte extra; /* reserved words for short strings; "has hash" for longs */+ unsigned int hash;+ size_t len; /* number of characters in string */+ } tsv;+} TString;+++/* get the actual string (array of bytes) from a TString */+#define getstr(ts) cast(const char *, (ts) + 1)++/* get the actual string (array of bytes) from a Lua value */+#define svalue(o) getstr(rawtsvalue(o))+++/*+** Header for userdata; memory area follows the end of this structure+*/+typedef union Udata {+ L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */+ struct {+ CommonHeader;+ struct Table *metatable;+ struct Table *env;+ size_t len; /* number of bytes */+ } uv;+} Udata;++++/*+** Description of an upvalue for function prototypes+*/+typedef struct Upvaldesc {+ TString *name; /* upvalue name (for debug information) */+ lu_byte instack; /* whether it is in stack */+ lu_byte idx; /* index of upvalue (in stack or in outer function's list) */+} Upvaldesc;+++/*+** Description of a local variable for function prototypes+** (used for debug information)+*/+typedef struct LocVar {+ TString *varname;+ int startpc; /* first point where variable is active */+ int endpc; /* first point where variable is dead */+} LocVar;+++/*+** Function Prototypes+*/+typedef struct Proto {+ CommonHeader;+ TValue *k; /* constants used by the function */+ Instruction *code;+ struct Proto **p; /* functions defined inside the function */+ int *lineinfo; /* map from opcodes to source lines (debug information) */+ LocVar *locvars; /* information about local variables (debug information) */+ Upvaldesc *upvalues; /* upvalue information */+ union Closure *cache; /* last created closure with this prototype */+ TString *source; /* used for debug information */+ int sizeupvalues; /* size of 'upvalues' */+ int sizek; /* size of `k' */+ int sizecode;+ int sizelineinfo;+ int sizep; /* size of `p' */+ int sizelocvars;+ int linedefined;+ int lastlinedefined;+ GCObject *gclist;+ lu_byte numparams; /* number of fixed parameters */+ lu_byte is_vararg;+ lu_byte maxstacksize; /* maximum stack used by this function */+} Proto;++++/*+** Lua Upvalues+*/+typedef struct UpVal {+ CommonHeader;+ TValue *v; /* points to stack or to its own value */+ union {+ TValue value; /* the value (when closed) */+ struct { /* double linked list (when open) */+ struct UpVal *prev;+ struct UpVal *next;+ } l;+ } u;+} UpVal;+++/*+** Closures+*/++#define ClosureHeader \+ CommonHeader; lu_byte nupvalues; GCObject *gclist++typedef struct CClosure {+ ClosureHeader;+ lua_CFunction f;+ TValue upvalue[1]; /* list of upvalues */+} CClosure;+++typedef struct LClosure {+ ClosureHeader;+ struct Proto *p;+ UpVal *upvals[1]; /* list of upvalues */+} LClosure;+++typedef union Closure {+ CClosure c;+ LClosure l;+} Closure;+++#define isLfunction(o) ttisLclosure(o)++#define getproto(o) (clLvalue(o)->p)+++/*+** Tables+*/++typedef union TKey {+ struct {+ TValuefields;+ struct Node *next; /* for chaining */+ } nk;+ TValue tvk;+} TKey;+++typedef struct Node {+ TValue i_val;+ TKey i_key;+} Node;+++typedef struct Table {+ CommonHeader;+ lu_byte flags; /* 1<<p means tagmethod(p) is not present */+ lu_byte lsizenode; /* log2 of size of `node' array */+ int sizearray; /* size of `array' array */+ TValue *array; /* array part */+ Node *node;+ Node *lastfree; /* any free position is before this position */+ struct Table *metatable;+ GCObject *gclist;+} Table;++++/*+** `module' operation for hashing (size is always a power of 2)+*/+#define lmod(s,size) \+ (check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1)))))+++#define twoto(x) (1<<(x))+#define sizenode(t) (twoto((t)->lsizenode))+++/*+** (address of) a fixed nil value+*/+#define luaO_nilobject (&luaO_nilobject_)+++LUAI_DDEC const TValue luaO_nilobject_;+++LUAI_FUNC int luaO_int2fb (unsigned int x);+LUAI_FUNC int luaO_fb2int (int x);+LUAI_FUNC int luaO_ceillog2 (unsigned int x);+LUAI_FUNC lua_Number luaO_arith (lua_State *L, int op, lua_Number v1, lua_Number v2);+LUAI_FUNC int luaO_str2d (const char *s, size_t len, lua_Number *result);+LUAI_FUNC int luaO_hexavalue (int c);+LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,+ va_list argp);+LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);+LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len);+++#endif+diff --git a/games/numpico/src/femto8/lua/lopcodes.c b/games/numpico/src/femto8/lua/lopcodes.cnew file mode 100644index 00000000..4422320e--- /dev/null+++ b/games/numpico/src/femto8/lua/lopcodes.c@@ -0,0 +1,137 @@+/*+** $Id: lopcodes.c,v 1.49 2012/05/14 13:34:18 roberto Exp $+** Opcodes for Lua virtual machine+** See Copyright Notice in lua.h+*/+++#define lopcodes_c+#define LUA_CORE+++#include "lopcodes.h"+++/* ORDER OP */++LUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = {+ "MOVE",+ "LOADK",+ "LOADKX",+ "LOADBOOL",+ "LOADNIL",+ "GETUPVAL",+ "GETTABUP",+ "GETTABLE",+ "GETGLOBALTABLE",+ "SETTABUP",+ "SETUPVAL",+ "SETTABLE",+ "SETGLOBALTABLE",+ "NEWTABLE",+ "SELF",+ "ADD",+ "SUB",+ "MUL",+ "DIV",+ "MOD",+ "POW",+ "IDIV",+ "BAND",+ "BOR",+ "BXOR",+ "SHL",+ "SHR",+ "LSHR",+ "ROTL",+ "ROTR",+ "UNM",+ "BNOT",+ "NOT",+ "PEEK",+ "PEEK2",+ "PEEK4",+ "LEN",+ "CONCAT",+ "JMP",+ "EQ",+ "LT",+ "LE",+ "TEST",+ "TESTSET",+ "CALL",+ "TAILCALL",+ "RETURN",+ "FORLOOP",+ "FORPREP",+ "TFORCALL",+ "TFORLOOP",+ "SETLIST",+ "CLOSURE",+ "VARARG",+ "EXTRAARG",+ NULL+};+++#define opmode(t,a,b,c,m) (((t)<<7) | ((a)<<6) | ((b)<<4) | ((c)<<2) | (m))++LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = {+/* T A B C mode opcode */+ opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_MOVE */+ ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_LOADK */+ ,opmode(0, 1, OpArgN, OpArgN, iABx) /* OP_LOADKX */+ ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */+ ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_LOADNIL */+ ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */+ ,opmode(0, 1, OpArgU, OpArgK, iABC) /* OP_GETTABUP */+ ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */+ ,opmode(0, 1, OpArgK, OpArgN, iABC) /* OP_GETGLOBALTABLE */+ ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABUP */+ ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_SETUPVAL */+ ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABLE */+ ,opmode(0, 0, OpArgK, OpArgN, iABC) /* OP_SETGLOBALTABLE */+ ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_NEWTABLE */+ ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_SELF */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ADD */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SUB */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MUL */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_DIV */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MOD */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_POW */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_IDIV */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BAND */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BOR */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BXOR */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SHL */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SHR */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_LSHR */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ROTL */+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ROTR */+ ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_UNM */+ ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_BNOT */+ ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_NOT */+ ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_PEEK */+ ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_PEEK2 */+ ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_PEEK4 */+ ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LEN */+ ,opmode(0, 1, OpArgR, OpArgR, iABC) /* OP_CONCAT */+ ,opmode(0, 0, OpArgR, OpArgN, iAsBx) /* OP_JMP */+ ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */+ ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */+ ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */+ ,opmode(1, 0, OpArgN, OpArgU, iABC) /* OP_TEST */+ ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */+ ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */+ ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */+ ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_RETURN */+ ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORLOOP */+ ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORPREP */+ ,opmode(0, 0, OpArgN, OpArgU, iABC) /* OP_TFORCALL */+ ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_TFORLOOP */+ ,opmode(0, 0, OpArgU, OpArgU, iABC) /* OP_SETLIST */+ ,opmode(0, 1, OpArgU, OpArgN, iABx) /* OP_CLOSURE */+ ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_VARARG */+ ,opmode(0, 0, OpArgU, OpArgU, iAx) /* OP_EXTRAARG */+};+diff --git a/games/numpico/src/femto8/lua/lopcodes.h b/games/numpico/src/femto8/lua/lopcodes.hnew file mode 100644index 00000000..b18edda2--- /dev/null+++ b/games/numpico/src/femto8/lua/lopcodes.h@@ -0,0 +1,306 @@+/*+** $Id: lopcodes.h,v 1.142.1.1 2013/04/12 18:48:47 roberto Exp roberto $+** Opcodes for Lua virtual machine+** See Copyright Notice in lua.h+*/++#ifndef lopcodes_h+#define lopcodes_h++#include "llimits.h"+++/*===========================================================================+ We assume that instructions are unsigned numbers.+ All instructions have an opcode in the first 6 bits.+ Instructions can have the following fields:+ `A' : 8 bits+ `B' : 9 bits+ `C' : 9 bits+ 'Ax' : 26 bits ('A', 'B', and 'C' together)+ `Bx' : 18 bits (`B' and `C' together)+ `sBx' : signed Bx++ A signed argument is represented in excess K; that is, the number+ value is the unsigned value minus K. K is exactly the maximum value+ for that argument (so that -max is represented by 0, and +max is+ represented by 2*max), which is half the maximum for the corresponding+ unsigned argument.+===========================================================================*/+++enum OpMode {iABC, iABx, iAsBx, iAx}; /* basic instruction format */+++/*+** size and position of opcode arguments.+*/+#define SIZE_C 9+#define SIZE_B 9+#define SIZE_Bx (SIZE_C + SIZE_B)+#define SIZE_A 8+#define SIZE_Ax (SIZE_C + SIZE_B + SIZE_A)++#define SIZE_OP 6++#define POS_OP 0+#define POS_A (POS_OP + SIZE_OP)+#define POS_C (POS_A + SIZE_A)+#define POS_B (POS_C + SIZE_C)+#define POS_Bx POS_C+#define POS_Ax POS_A+++/*+** limits for opcode arguments.+** we use (signed) int to manipulate most arguments,+** so they must fit in LUAI_BITSINT-1 bits (-1 for sign)+*/+#if SIZE_Bx < LUAI_BITSINT-1+#define MAXARG_Bx ((1<<SIZE_Bx)-1)+#define MAXARG_sBx (MAXARG_Bx>>1) /* `sBx' is signed */+#else+#define MAXARG_Bx MAX_INT+#define MAXARG_sBx MAX_INT+#endif++#if SIZE_Ax < LUAI_BITSINT-1+#define MAXARG_Ax ((1<<SIZE_Ax)-1)+#else+#define MAXARG_Ax MAX_INT+#endif+++#define MAXARG_A ((1<<SIZE_A)-1)+#define MAXARG_B ((1<<SIZE_B)-1)+#define MAXARG_C ((1<<SIZE_C)-1)+++/* creates a mask with `n' 1 bits at position `p' */+#define MASK1(n,p) ((~((~(Instruction)0)<<(n)))<<(p))++/* creates a mask with `n' 0 bits at position `p' */+#define MASK0(n,p) (~MASK1(n,p))++/*+** the following macros help to manipulate instructions+*/++#define GET_OPCODE(i) (cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0)))+#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \+ ((cast(Instruction, o)<<POS_OP)&MASK1(SIZE_OP,POS_OP))))++#define getarg(i,pos,size) (cast(int, ((i)>>pos) & MASK1(size,0)))+#define setarg(i,v,pos,size) ((i) = (((i)&MASK0(size,pos)) | \+ ((cast(Instruction, v)<<pos)&MASK1(size,pos))))++#define GETARG_A(i) getarg(i, POS_A, SIZE_A)+#define SETARG_A(i,v) setarg(i, v, POS_A, SIZE_A)++#define GETARG_B(i) getarg(i, POS_B, SIZE_B)+#define SETARG_B(i,v) setarg(i, v, POS_B, SIZE_B)++#define GETARG_C(i) getarg(i, POS_C, SIZE_C)+#define SETARG_C(i,v) setarg(i, v, POS_C, SIZE_C)++#define GETARG_Bx(i) getarg(i, POS_Bx, SIZE_Bx)+#define SETARG_Bx(i,v) setarg(i, v, POS_Bx, SIZE_Bx)++#define GETARG_Ax(i) getarg(i, POS_Ax, SIZE_Ax)+#define SETARG_Ax(i,v) setarg(i, v, POS_Ax, SIZE_Ax)++#define GETARG_sBx(i) (GETARG_Bx(i)-MAXARG_sBx)+#define SETARG_sBx(i,b) SETARG_Bx((i),cast(unsigned int, (b)+MAXARG_sBx))+++#define CREATE_ABC(o,a,b,c) ((cast(Instruction, o)<<POS_OP) \+ | (cast(Instruction, a)<<POS_A) \+ | (cast(Instruction, b)<<POS_B) \+ | (cast(Instruction, c)<<POS_C))++#define CREATE_ABx(o,a,bc) ((cast(Instruction, o)<<POS_OP) \+ | (cast(Instruction, a)<<POS_A) \+ | (cast(Instruction, bc)<<POS_Bx))++#define CREATE_Ax(o,a) ((cast(Instruction, o)<<POS_OP) \+ | (cast(Instruction, a)<<POS_Ax))+++/*+** Macros to operate RK indices+*/++/* this bit 1 means constant (0 means register) */+#define BITRK (1 << (SIZE_B - 1))++/* test whether value is a constant */+#define ISK(x) ((x) & BITRK)++/* gets the index of the constant */+#define INDEXK(r) ((int)(r) & ~BITRK)++#define MAXINDEXRK (BITRK - 1)++/* code a constant index as a RK value */+#define RKASK(x) ((x) | BITRK)+++/*+** invalid register that fits in 8 bits+*/+#define NO_REG MAXARG_A+++/*+** R(x) - register+** Kst(x) - constant (in constant table)+** RK(x) == if ISK(x) then Kst(INDEXK(x)) else R(x)+*/+++/*+** grep "ORDER OP" if you change these enums+*/++typedef enum {+/*----------------------------------------------------------------------+name args description+------------------------------------------------------------------------*/+OP_MOVE,/* A B R(A) := R(B) */+OP_LOADK,/* A Bx R(A) := Kst(Bx) */+OP_LOADKX,/* A R(A) := Kst(extra arg) */+OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */+OP_LOADNIL,/* A B R(A), R(A+1), ..., R(A+B) := nil */+OP_GETUPVAL,/* A B R(A) := UpValue[B] */++OP_GETTABUP,/* A B C R(A) := UpValue[B][RK(C)] */+OP_GETTABLE,/* A B C R(A) := R(B)[RK(C)] */++OP_GETGLOBALTABLE,/* A B R(A) := registry[LUA_RIDX_GLOBALS][RK(B)] */++OP_SETTABUP,/* A B C UpValue[A][RK(B)] := RK(C) */+OP_SETUPVAL,/* A B UpValue[B] := R(A) */+OP_SETTABLE,/* A B C R(A)[RK(B)] := RK(C) */++OP_SETGLOBALTABLE,/* A B registry[LUA_RIDX_GLOBALS][RK(B)] := R(A) */++OP_NEWTABLE,/* A B C R(A) := {} (size = B,C) */++OP_SELF,/* A B C R(A+1) := R(B); R(A) := R(B)[RK(C)] */++OP_ADD,/* A B C R(A) := RK(B) + RK(C) */+OP_SUB,/* A B C R(A) := RK(B) - RK(C) */+OP_MUL,/* A B C R(A) := RK(B) * RK(C) */+OP_DIV,/* A B C R(A) := RK(B) / RK(C) */+OP_MOD,/* A B C R(A) := RK(B) % RK(C) */+OP_POW,/* A B C R(A) := RK(B) ^ RK(C) */+OP_IDIV,/* A B C R(A) := RK(B) \ RK(C) */+OP_BAND,/* A B C R(A) := RK(B) & RK(C) */+OP_BOR,/* A B C R(A) := RK(B) | RK(C) */+OP_BXOR,/* A B C R(A) := RK(B) ^^ RK(C) */+OP_SHL,/* A B C R(A) := RK(B) << RK(C) */+OP_SHR,/* A B C R(A) := RK(B) >> RK(C) */+OP_LSHR,/* A B C R(A) := RK(B) >>> RK(C) */+OP_ROTL,/* A B C R(A) := RK(B) <<> RK(C) */+OP_ROTR,/* A B C R(A) := RK(B) >>< RK(C) */++OP_UNM,/* A B R(A) := -R(B) */+OP_BNOT,/* A B R(A) := ~R(B) */+OP_NOT,/* A B R(A) := not R(B) */+OP_PEEK,/* A B R(A) := @ R(B) */+OP_PEEK2,/* A B R(A) := % R(B) */+OP_PEEK4,/* A B R(A) := $ R(B) */+OP_LEN,/* A B R(A) := length of R(B) */++OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */++OP_JMP,/* A sBx pc+=sBx; if (A) close all upvalues >= R(A - 1) */+OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */+OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */+OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */++OP_TEST,/* A C if not (R(A) <=> C) then pc++ */+OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */++OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */+OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */+OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */++OP_FORLOOP,/* A sBx R(A)+=R(A+2);+ if R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }*/+OP_FORPREP,/* A sBx R(A)-=R(A+2); pc+=sBx */++OP_TFORCALL,/* A C R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2)); */+OP_TFORLOOP,/* A sBx if R(A+1) ~= nil then { R(A)=R(A+1); pc += sBx }*/++OP_SETLIST,/* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */++OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx]) */++OP_VARARG,/* A B R(A), R(A+1), ..., R(A+B-2) = vararg */++OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */+} OpCode;+++#define NUM_OPCODES (cast(int, OP_EXTRAARG) + 1)++++/*===========================================================================+ Notes:+ (*) In OP_CALL, if (B == 0) then B = top. If (C == 0), then `top' is+ set to last_result+1, so next open instruction (OP_CALL, OP_RETURN,+ OP_SETLIST) may use `top'.++ (*) In OP_VARARG, if (B == 0) then use actual number of varargs and+ set top (like in OP_CALL with C == 0).++ (*) In OP_RETURN, if (B == 0) then return up to `top'.++ (*) In OP_SETLIST, if (B == 0) then B = `top'; if (C == 0) then next+ 'instruction' is EXTRAARG(real C).++ (*) In OP_LOADKX, the next 'instruction' is always EXTRAARG.++ (*) For comparisons, A specifies what condition the test should accept+ (true or false).++ (*) All `skips' (pc++) assume that next instruction is a jump.++===========================================================================*/+++/*+** masks for instruction properties. The format is:+** bits 0-1: op mode+** bits 2-3: C arg mode+** bits 4-5: B arg mode+** bit 6: instruction set register A+** bit 7: operator is a test (next instruction must be a jump)+*/++enum OpArgMask {+ OpArgN, /* argument is not used */+ OpArgU, /* argument is used */+ OpArgR, /* argument is a register or a jump offset */+ OpArgK /* argument is a constant or register/constant */+};++LUAI_DDEC const lu_byte luaP_opmodes[NUM_OPCODES];++#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 3))+#define getBMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 4) & 3))+#define getCMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 2) & 3))+#define testAMode(m) (luaP_opmodes[m] & (1 << 6))+#define testTMode(m) (luaP_opmodes[m] & (1 << 7))+++LUAI_DDEC const char *const luaP_opnames[NUM_OPCODES+1]; /* opcode names */+++/* number of list items to accumulate before a SETLIST instruction */+#define LFIELDS_PER_FLUSH 50+++#endifdiff --git a/games/numpico/src/femto8/lua/lparser.c b/games/numpico/src/femto8/lua/lparser.cnew file mode 100644index 00000000..601fbdf5--- /dev/null+++ b/games/numpico/src/femto8/lua/lparser.c@@ -0,0 +1,1856 @@+/*+** $Id: lparser.c,v 2.130 2013/02/06 13:37:39 roberto Exp $+** Lua Parser+** See Copyright Notice in lua.h+*/+++#include <string.h>++#define lparser_c+#define LUA_CORE++#include "lua.h"++#include "lcode.h"+#include "ldebug.h"+#include "ldo.h"+#include "lfunc.h"+#include "llex.h"+#include "lmem.h"+#include "lobject.h"+#include "lopcodes.h"+#include "lparser.h"+#include "lstate.h"+#include "lstring.h"+#include "ltable.h"++++/* maximum number of local variables per function (must be smaller+ than 250, due to the bytecode format) */+#define MAXVARS 200+++#define hasmultret(k) ((k) == VCALL || (k) == VVARARG)++++/*+** nodes for block list (list of active blocks)+*/+typedef struct BlockCnt {+ struct BlockCnt *previous; /* chain */+ short firstlabel; /* index of first label in this block */+ short firstgoto; /* index of first pending goto in this block */+ lu_byte nactvar; /* # active locals outside the block */+ lu_byte upval; /* true if some variable in the block is an upvalue */+ lu_byte isloop; /* true if `block' is a loop */+} BlockCnt;++++/*+** prototypes for recursive non-terminal functions+*/+static void statement (LexState *ls);+static void expr (LexState *ls, expdesc *v);+static void printexpr (LexState *ls, expdesc *v, int line);+++static void anchor_token (LexState *ls) {+ /* last token from outer function must be EOS */+ lua_assert(ls->fs != NULL || ls->t.token == TK_EOS);+ if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {+ TString *ts = ls->t.seminfo.ts;+ luaX_newstring(ls, getstr(ts), ts->tsv.len);+ }+}+++/* semantic error */+static l_noret semerror (LexState *ls, const char *msg) {+ ls->t.token = 0; /* remove 'near to' from final message */+ luaX_syntaxerror(ls, msg);+}+++static l_noret error_expected (LexState *ls, int token) {+ luaX_syntaxerror(ls,+ luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));+}+++static l_noret errorlimit (FuncState *fs, int limit, const char *what) {+ lua_State *L = fs->ls->L;+ const char *msg;+ int line = fs->f->linedefined;+ const char *where = (line == 0)+ ? "main function"+ : luaO_pushfstring(L, "function at line %d", line);+ msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",+ what, limit, where);+ luaX_syntaxerror(fs->ls, msg);+}+++static void checklimit (FuncState *fs, int v, int l, const char *what) {+ if (v > l) errorlimit(fs, l, what);+}+++static int testnext (LexState *ls, int c) {+ if (ls->t.token == c) {+ luaX_next(ls);+ return 1;+ }+ else return 0;+}+++static void check (LexState *ls, int c) {+ if (ls->t.token != c)+ error_expected(ls, c);+}+++static void checknext (LexState *ls, int c) {+ check(ls, c);+ luaX_next(ls);+}+++#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }++++static void check_match (LexState *ls, int what, int who, int where) {+ if (!testnext(ls, what)) {+ if (where == ls->linenumber)+ error_expected(ls, what);+ else {+ luaX_syntaxerror(ls, luaO_pushfstring(ls->L,+ "%s expected (to close %s at line %d)",+ luaX_token2str(ls, what), luaX_token2str(ls, who), where));+ }+ }+}+++static TString *str_checkname (LexState *ls) {+ TString *ts;+ check(ls, TK_NAME);+ ts = ls->t.seminfo.ts;+ luaX_next(ls);+ return ts;+}+++static void init_exp (expdesc *e, expkind k, int i) {+ e->f = e->t = NO_JUMP;+ e->k = k;+ e->u.info = i;+}+++static void codestring (LexState *ls, expdesc *e, TString *s) {+ init_exp(e, VK, luaK_stringK(ls->fs, s));+}+++static void checkname (LexState *ls, expdesc *e) {+ codestring(ls, e, str_checkname(ls));+}+++static int registerlocalvar (LexState *ls, TString *varname) {+ FuncState *fs = ls->fs;+ Proto *f = fs->f;+ int oldsize = f->sizelocvars;+ luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,+ LocVar, SHRT_MAX, "local variables");+ while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;+ f->locvars[fs->nlocvars].varname = varname;+ luaC_objbarrier(ls->L, f, varname);+ return fs->nlocvars++;+}+++static void new_localvar (LexState *ls, TString *name) {+ FuncState *fs = ls->fs;+ Dyndata *dyd = ls->dyd;+ int reg = registerlocalvar(ls, name);+ checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,+ MAXVARS, "local variables");+ luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1,+ dyd->actvar.size, Vardesc, MAX_INT, "local variables");+ dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg);+}+++static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) {+ new_localvar(ls, luaX_newstring(ls, name, sz));+}++#define new_localvarliteral(ls,v) \+ new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1)+++static LocVar *getlocvar (FuncState *fs, int i) {+ int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;+ lua_assert(idx < fs->nlocvars);+ return &fs->f->locvars[idx];+}+++static void adjustlocalvars (LexState *ls, int nvars) {+ FuncState *fs = ls->fs;+ fs->nactvar = cast_byte(fs->nactvar + nvars);+ for (; nvars; nvars--) {+ getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc;+ }+}+++static void removevars (FuncState *fs, int tolevel) {+ fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);+ while (fs->nactvar > tolevel)+ getlocvar(fs, --fs->nactvar)->endpc = fs->pc;+}+++static int searchupvalue (FuncState *fs, TString *name) {+ int i;+ Upvaldesc *up = fs->f->upvalues;+ for (i = 0; i < fs->nups; i++) {+ if (luaS_eqstr(up[i].name, name)) return i;+ }+ return -1; /* not found */+}+++static int newupvalue (FuncState *fs, TString *name, expdesc *v) {+ Proto *f = fs->f;+ int oldsize = f->sizeupvalues;+ checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");+ luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,+ Upvaldesc, MAXUPVAL, "upvalues");+ while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL;+ f->upvalues[fs->nups].instack = (v->k == VLOCAL);+ f->upvalues[fs->nups].idx = cast_byte(v->u.info);+ f->upvalues[fs->nups].name = name;+ luaC_objbarrier(fs->ls->L, f, name);+ return fs->nups++;+}+++static int searchvar (FuncState *fs, TString *n) {+ int i;+ for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {+ if (luaS_eqstr(n, getlocvar(fs, i)->varname))+ return i;+ }+ return -1; /* not found */+}+++/*+ Mark block where variable at given level was defined+ (to emit close instructions later).+*/+static void markupval (FuncState *fs, int level) {+ BlockCnt *bl = fs->bl;+ while (bl->nactvar > level) bl = bl->previous;+ bl->upval = 1;+}+++/*+ Find variable with given name 'n'. If it is an upvalue, add this+ upvalue into all intermediate functions.+*/+static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {+ if (fs == NULL) /* no more levels? */+ return VVOID; /* default is global */+ else {+ int v = searchvar(fs, n); /* look up locals at current level */+ if (v >= 0) { /* found? */+ init_exp(var, VLOCAL, v); /* variable is local */+ if (!base)+ markupval(fs, v); /* local will be used as an upval */+ return VLOCAL;+ }+ else { /* not found as local at current level; try upvalues */+ int idx = searchupvalue(fs, n); /* try existing upvalues */+ if (idx < 0) { /* not found? */+ if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */+ return VVOID; /* not found; is a global */+ /* else was LOCAL or UPVAL */+ idx = newupvalue(fs, n, var); /* will be a new upvalue */+ }+ init_exp(var, VUPVAL, idx);+ return VUPVAL;+ }+ }+}+++/*+** PICO-8 compat: certain math/bitwise/graphics functions bypass _ENV+** entirely. Functions NOT in this list (sqrt, sgn, abs, add, del, all,+** printh, ...) go through _ENV as normal -- carts that use them inside+** _ENV-param functions rely on the passed table having __index set to the+** real global env.+*/+static int is_pico8_builtin (TString *name) {+ static const char * const builtins[] = {+ /* Math functions */+ "flr","ceil","sin","cos","tan","atan","atan2",+ "sqr","sqrt","sgn","abs",+ "max","min","mid",+ /* Bitwise functions */+ "band","bor","bxor","bnot","shl","shr","lshr","rotl","rotr",+ /* String/conversion */+ "tostr","tonum","chr","ord","sub",+ /* Graphics functions */+ "circ","circfill","line","oval","ovalfill",+ "rect","rectfill","rrect","rrectfill",+ "pset","pget","sget","sset","spr","sspr",+ "clip","cls","color","cursor","fillp","pal","palt",+ "map","mget","mset","fget","fset",+ /* Misc PICO-8 specific */+ "rnd","srand","flip","holdframe",+ "tline",+ NULL+ };+ const char *s = getstr(name);+ int i;+ for (i = 0; builtins[i]; i++)+ if (strcmp(s, builtins[i]) == 0) return 1;+ return 0;+}++static void singlevar (LexState *ls, expdesc *var) {+ TString *varname = str_checkname(ls);+ FuncState *fs = ls->fs;+ if (singlevaraux(fs, varname, var, 1) == VVOID) { /* global name? */+ if (is_pico8_builtin(varname)) {+ /* Variable found locally, but it's a PICO-8 builtin so use VGLOBAL+ (this handles the case where _ENV is a local parameter) */+ expdesc key;+ codestring(ls, &key, varname);+ var->k = VGLOBAL;+ var->f = var->t = NO_JUMP;+ var->u.glb.idx = luaK_exp2RK(fs, &key);+ } else {+ expdesc key;+ singlevaraux(fs, ls->envn, var, 1); /* get environment variable */+ lua_assert(var->k == VLOCAL || var->k == VUPVAL);+ codestring(ls, &key, varname); /* key is variable name */+ luaK_indexed(fs, var, &key); /* env[varname] */+ }+ }+}+++static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {+ FuncState *fs = ls->fs;+ int extra = nvars - nexps;+ if (hasmultret(e->k)) {+ extra++; /* includes call itself */+ if (extra < 0) extra = 0;+ luaK_setreturns(fs, e, extra); /* last exp. provides the difference */+ if (extra > 1) luaK_reserveregs(fs, extra-1);+ }+ else {+ if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */+ if (extra > 0) {+ int reg = fs->freereg;+ luaK_reserveregs(fs, extra);+ luaK_nil(fs, reg, extra);+ }+ }+}+++static void enterlevel (LexState *ls) {+ lua_State *L = ls->L;+ ++L->nCcalls;+ checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels");+}+++#define leavelevel(ls) ((ls)->L->nCcalls--)+++static void closegoto (LexState *ls, int g, Labeldesc *label) {+ int i;+ FuncState *fs = ls->fs;+ Labellist *gl = &ls->dyd->gt;+ Labeldesc *gt = &gl->arr[g];+ lua_assert(luaS_eqstr(gt->name, label->name));+ if (gt->nactvar < label->nactvar) {+ TString *vname = getlocvar(fs, gt->nactvar)->varname;+ const char *msg = luaO_pushfstring(ls->L,+ "<goto %s> at line %d jumps into the scope of local " LUA_QS,+ getstr(gt->name), gt->line, getstr(vname));+ semerror(ls, msg);+ }+ luaK_patchlist(fs, gt->pc, label->pc);+ /* remove goto from pending list */+ for (i = g; i < gl->n - 1; i++)+ gl->arr[i] = gl->arr[i + 1];+ gl->n--;+}+++/*+** try to close a goto with existing labels; this solves backward jumps+*/+static int findlabel (LexState *ls, int g) {+ int i;+ BlockCnt *bl = ls->fs->bl;+ Dyndata *dyd = ls->dyd;+ Labeldesc *gt = &dyd->gt.arr[g];+ /* check labels in current block for a match */+ for (i = bl->firstlabel; i < dyd->label.n; i++) {+ Labeldesc *lb = &dyd->label.arr[i];+ if (luaS_eqstr(lb->name, gt->name)) { /* correct label? */+ if (gt->nactvar > lb->nactvar &&+ (bl->upval || dyd->label.n > bl->firstlabel))+ luaK_patchclose(ls->fs, gt->pc, lb->nactvar);+ closegoto(ls, g, lb); /* close it */+ return 1;+ }+ }+ return 0; /* label not found; cannot close goto */+}+++static int newlabelentry (LexState *ls, Labellist *l, TString *name,+ int line, int pc) {+ int n = l->n;+ luaM_growvector(ls->L, l->arr, n, l->size,+ Labeldesc, SHRT_MAX, "labels/gotos");+ l->arr[n].name = name;+ l->arr[n].line = line;+ l->arr[n].nactvar = ls->fs->nactvar;+ l->arr[n].pc = pc;+ l->n++;+ return n;+}+++/*+** check whether new label 'lb' matches any pending gotos in current+** block; solves forward jumps+*/+static void findgotos (LexState *ls, Labeldesc *lb) {+ Labellist *gl = &ls->dyd->gt;+ int i = ls->fs->bl->firstgoto;+ while (i < gl->n) {+ if (luaS_eqstr(gl->arr[i].name, lb->name))+ closegoto(ls, i, lb);+ else+ i++;+ }+}+++/*+** "export" pending gotos to outer level, to check them against+** outer labels; if the block being exited has upvalues, and+** the goto exits the scope of any variable (which can be the+** upvalue), close those variables being exited.+*/+static void movegotosout (FuncState *fs, BlockCnt *bl) {+ int i = bl->firstgoto;+ Labellist *gl = &fs->ls->dyd->gt;+ /* correct pending gotos to current block and try to close it+ with visible labels */+ while (i < gl->n) {+ Labeldesc *gt = &gl->arr[i];+ if (gt->nactvar > bl->nactvar) {+ if (bl->upval)+ luaK_patchclose(fs, gt->pc, bl->nactvar);+ gt->nactvar = bl->nactvar;+ }+ if (!findlabel(fs->ls, i))+ i++; /* move to next one */+ }+}+++static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {+ bl->isloop = isloop;+ bl->nactvar = fs->nactvar;+ bl->firstlabel = fs->ls->dyd->label.n;+ bl->firstgoto = fs->ls->dyd->gt.n;+ bl->upval = 0;+ bl->previous = fs->bl;+ fs->bl = bl;+ lua_assert(fs->freereg == fs->nactvar);+}+++/*+** create a label named "break" to resolve break statements+*/+static void breaklabel (LexState *ls) {+ TString *n = luaS_new(ls->L, "break");+ int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc);+ findgotos(ls, &ls->dyd->label.arr[l]);+}++/*+** generates an error for an undefined 'goto'; choose appropriate+** message when label name is a reserved word (which can only be 'break')+*/+static l_noret undefgoto (LexState *ls, Labeldesc *gt) {+ const char *msg = isreserved(gt->name)+ ? "<%s> at line %d not inside a loop"+ : "no visible label " LUA_QS " for <goto> at line %d";+ msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);+ semerror(ls, msg);+}+++static void leaveblock (FuncState *fs) {+ BlockCnt *bl = fs->bl;+ LexState *ls = fs->ls;+ if (bl->previous && bl->upval) {+ /* create a 'jump to here' to close upvalues */+ int j = luaK_jump(fs);+ luaK_patchclose(fs, j, bl->nactvar);+ luaK_patchtohere(fs, j);+ }+ if (bl->isloop)+ breaklabel(ls); /* close pending breaks */+ fs->bl = bl->previous;+ removevars(fs, bl->nactvar);+ lua_assert(bl->nactvar == fs->nactvar);+ fs->freereg = fs->nactvar; /* free registers */+ ls->dyd->label.n = bl->firstlabel; /* remove local labels */+ if (bl->previous) /* inner block? */+ movegotosout(fs, bl); /* update pending gotos to outer block */+ else if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */+ undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */+}+++/*+** adds a new prototype into list of prototypes+*/+static Proto *addprototype (LexState *ls) {+ Proto *clp;+ lua_State *L = ls->L;+ FuncState *fs = ls->fs;+ Proto *f = fs->f; /* prototype of current function */+ if (fs->np >= f->sizep) {+ int oldsize = f->sizep;+ luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions");+ while (oldsize < f->sizep) f->p[oldsize++] = NULL;+ }+ f->p[fs->np++] = clp = luaF_newproto(L);+ luaC_objbarrier(L, f, clp);+ return clp;+}+++/*+** codes instruction to create new closure in parent function.+** The OP_CLOSURE instruction must use the last available register,+** so that, if it invokes the GC, the GC knows which registers+** are in use at that time.+*/+static void codeclosure (LexState *ls, expdesc *v) {+ FuncState *fs = ls->fs->prev;+ init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));+ luaK_exp2nextreg(fs, v); /* fix it at the last register */+}+++static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {+ lua_State *L = ls->L;+ Proto *f;+ fs->prev = ls->fs; /* linked list of funcstates */+ fs->ls = ls;+ ls->fs = fs;+ fs->pc = 0;+ fs->lasttarget = 0;+ fs->jpc = NO_JUMP;+ fs->freereg = 0;+ fs->nk = 0;+ fs->np = 0;+ fs->nups = 0;+ fs->nlocvars = 0;+ fs->nactvar = 0;+ fs->firstlocal = ls->dyd->actvar.n;+ fs->bl = NULL;+ f = fs->f;+ f->source = ls->source;+ f->maxstacksize = 2; /* registers 0/1 are always valid */+ fs->h = luaH_new(L);+ /* anchor table of constants (to avoid being collected) */+ sethvalue2s(L, L->top, fs->h);+ incr_top(L);+ enterblock(fs, bl, 0);+}+++static void close_func (LexState *ls) {+ lua_State *L = ls->L;+ FuncState *fs = ls->fs;+ Proto *f = fs->f;+ luaK_ret(fs, 0, 0); /* final return */+ leaveblock(fs);+ luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);+ f->sizecode = fs->pc;+ luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);+ f->sizelineinfo = fs->pc;+ luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);+ f->sizek = fs->nk;+ luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);+ f->sizep = fs->np;+ luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);+ f->sizelocvars = fs->nlocvars;+ luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);+ f->sizeupvalues = fs->nups;+ lua_assert(fs->bl == NULL);+ ls->fs = fs->prev;+ /* last token read was anchored in defunct function; must re-anchor it */+ anchor_token(ls);+ L->top--; /* pop table of constants */+ luaC_checkGC(L);+}++++/*============================================================*/+/* GRAMMAR RULES */+/*============================================================*/+++/*+** check whether current token is in the follow set of a block.+** 'until' closes syntactical blocks, but do not close scope,+** so it handled in separate.+*/+static int block_follow (LexState *ls, int withuntil) {+ switch (ls->t.token) {+ case TK_ELSE: case TK_ELSEIF:+ case TK_END: case TK_EOS:+ case TK_EOL: /* EOL indicates end of short IF or WHILE */+ return 1;+ case TK_UNTIL: return withuntil;+ default: return 0;+ }+}+++static void statlist (LexState *ls) {+ /* statlist -> { stat [`;'] } */+ while (!block_follow(ls, 1)) {+ if (ls->t.token == TK_RETURN) {+ statement(ls);+ return; /* 'return' must be last statement */+ }+ statement(ls);+ }+}+++static void fieldsel (LexState *ls, expdesc *v) {+ /* fieldsel -> ['.' | ':'] NAME */+ FuncState *fs = ls->fs;+ expdesc key;+ luaK_exp2anyregup(fs, v);+ luaX_next(ls); /* skip the dot or colon */+ checkname(ls, &key);+ luaK_indexed(fs, v, &key);+}+++static void yindex (LexState *ls, expdesc *v) {+ /* index -> '[' expr ']' */+ luaX_next(ls); /* skip the '[' */+ expr(ls, v);+ luaK_exp2val(ls->fs, v);+ checknext(ls, ']');+}+++/*+** {======================================================================+** Rules for Constructors+** =======================================================================+*/+++struct ConsControl {+ expdesc v; /* last list item read */+ expdesc *t; /* table descriptor */+ int nh; /* total number of `record' elements */+ int na; /* total number of array elements */+ int tostore; /* number of array elements pending to be stored */+};+++static void recfield (LexState *ls, struct ConsControl *cc) {+ /* recfield -> (NAME | `['exp1`]') = exp1 */+ FuncState *fs = ls->fs;+ int reg = ls->fs->freereg;+ expdesc key, val;+ int rkkey;+ if (ls->t.token == TK_NAME) {+ checklimit(fs, cc->nh, MAX_INT, "items in a constructor");+ checkname(ls, &key);+ }+ else /* ls->t.token == '[' */+ yindex(ls, &key);+ cc->nh++;+ checknext(ls, '=');+ rkkey = luaK_exp2RK(fs, &key);+ expr(ls, &val);+ luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val));+ fs->freereg = reg; /* free registers */+}+++static void closelistfield (FuncState *fs, struct ConsControl *cc) {+ if (cc->v.k == VVOID) return; /* there is no list item */+ luaK_exp2nextreg(fs, &cc->v);+ cc->v.k = VVOID;+ if (cc->tostore == LFIELDS_PER_FLUSH) {+ luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */+ cc->tostore = 0; /* no more items pending */+ }+}+++static void lastlistfield (FuncState *fs, struct ConsControl *cc) {+ if (cc->tostore == 0) return;+ if (hasmultret(cc->v.k)) {+ luaK_setmultret(fs, &cc->v);+ luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);+ cc->na--; /* do not count last expression (unknown number of elements) */+ }+ else {+ if (cc->v.k != VVOID)+ luaK_exp2nextreg(fs, &cc->v);+ luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);+ }+}+++static void listfield (LexState *ls, struct ConsControl *cc) {+ /* listfield -> exp */+ expr(ls, &cc->v);+ checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");+ cc->na++;+ cc->tostore++;+}+++static void field (LexState *ls, struct ConsControl *cc) {+ /* field -> listfield | recfield */+ switch(ls->t.token) {+ case TK_NAME: { /* may be 'listfield' or 'recfield' */+ if (luaX_lookahead(ls) != '=') /* expression? */+ listfield(ls, cc);+ else+ recfield(ls, cc);+ break;+ }+ case '[': {+ recfield(ls, cc);+ break;+ }+ default: {+ listfield(ls, cc);+ break;+ }+ }+}+++static void constructor (LexState *ls, expdesc *t) {+ /* constructor -> '{' [ field { sep field } [sep] ] '}'+ sep -> ',' | ';' */+ FuncState *fs = ls->fs;+ int line = ls->linenumber;+ int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);+ struct ConsControl cc;+ cc.na = cc.nh = cc.tostore = 0;+ cc.t = t;+ init_exp(t, VRELOCABLE, pc);+ init_exp(&cc.v, VVOID, 0); /* no value (yet) */+ luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */+ checknext(ls, '{');+ do {+ lua_assert(cc.v.k == VVOID || cc.tostore > 0);+ if (ls->t.token == '}') break;+ closelistfield(fs, &cc);+ field(ls, &cc);+ } while (testnext(ls, ',') || testnext(ls, ';'));+ check_match(ls, '}', '{', line);+ lastlistfield(fs, &cc);+ SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */+ SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */+}++/* }====================================================================== */++++static void parlist (LexState *ls) {+ /* parlist -> [ param { `,' param } ] */+ FuncState *fs = ls->fs;+ Proto *f = fs->f;+ int nparams = 0;+ f->is_vararg = 0;+ if (ls->t.token != ')') { /* is `parlist' not empty? */+ do {+ switch (ls->t.token) {+ case TK_NAME: { /* param -> NAME */+ new_localvar(ls, str_checkname(ls));+ nparams++;+ break;+ }+ case TK_DOTS: { /* param -> `...' */+ luaX_next(ls);+ f->is_vararg = 1;+ break;+ }+ default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");+ }+ } while (!f->is_vararg && testnext(ls, ','));+ }+ adjustlocalvars(ls, nparams);+ f->numparams = cast_byte(fs->nactvar);+ luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */+}+++static void body (LexState *ls, expdesc *e, int ismethod, int line) {+ /* body -> `(' parlist `)' block END */+ FuncState new_fs;+ BlockCnt bl;+ new_fs.f = addprototype(ls);+ new_fs.f->linedefined = line;+ open_func(ls, &new_fs, &bl);+ checknext(ls, '(');+ if (ismethod) {+ new_localvarliteral(ls, "self"); /* create 'self' parameter */+ adjustlocalvars(ls, 1);+ }+ parlist(ls);+ checknext(ls, ')');+ statlist(ls);+ new_fs.f->lastlinedefined = ls->linenumber;+ check_match(ls, TK_END, TK_FUNCTION, line);+ codeclosure(ls, e);+ close_func(ls);+}+++static int explist (LexState *ls, expdesc *v) {+ /* explist -> expr { `,' expr } */+ int n = 1; /* at least one expression */+ expr(ls, v);+ while (testnext(ls, ',')) {+ luaK_exp2nextreg(ls->fs, v);+ expr(ls, v);+ n++;+ }+ return n;+}+++static void funcargs (LexState *ls, expdesc *f, int line) {+ FuncState *fs = ls->fs;+ expdesc args;+ int base, nparams;+ switch (ls->t.token) {+ case '(': { /* funcargs -> `(' [ explist ] `)' */+ luaX_next(ls);+ if (ls->t.token == ')') /* arg list is empty? */+ args.k = VVOID;+ else {+ explist(ls, &args);+ luaK_setmultret(fs, &args);+ }+ check_match(ls, ')', '(', line);+ break;+ }+ case '{': { /* funcargs -> constructor */+ constructor(ls, &args);+ break;+ }+ case TK_STRING: { /* funcargs -> STRING */+ codestring(ls, &args, ls->t.seminfo.ts);+ luaX_next(ls); /* must use `seminfo' before `next' */+ break;+ }+ default: {+ luaX_syntaxerror(ls, "function arguments expected");+ }+ }+ lua_assert(f->k == VNONRELOC);+ base = f->u.info; /* base register for call */+ if (hasmultret(args.k))+ nparams = LUA_MULTRET; /* open call */+ else {+ if (args.k != VVOID)+ luaK_exp2nextreg(fs, &args); /* close last argument */+ nparams = fs->freereg - (base+1);+ }+ init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));+ luaK_fixline(fs, line);+ fs->freereg = base+1; /* call remove function and arguments and leaves+ (unless changed) one result */+}+++++/*+** {======================================================================+** Expression parsing+** =======================================================================+*/+++static void primaryexp (LexState *ls, expdesc *v) {+ /* primaryexp -> NAME | '(' expr ')' */+ switch (ls->t.token) {+ case '(': {+ int line = ls->linenumber;+ luaX_next(ls);+ expr(ls, v);+ check_match(ls, ')', '(', line);+ luaK_dischargevars(ls->fs, v);+ return;+ }+ case TK_NAME: {+ singlevar(ls, v);+ return;+ }+ default: {+ luaX_syntaxerror(ls, "unexpected symbol");+ }+ }+}+++static void suffixedexp (LexState *ls, expdesc *v) {+ /* suffixedexp ->+ primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */+ FuncState *fs = ls->fs;+ int line = ls->linenumber;+ primaryexp(ls, v);+ for (;;) {+ switch (ls->t.token) {+ case '.': { /* fieldsel */+ fieldsel(ls, v);+ break;+ }+ case '[': { /* `[' exp1 `]' */+ expdesc key;+ luaK_exp2anyregup(fs, v);+ yindex(ls, &key);+ luaK_indexed(fs, v, &key);+ break;+ }+ case ':': { /* `:' NAME funcargs */+ expdesc key;+ luaX_next(ls);+ checkname(ls, &key);+ luaK_self(fs, v, &key);+ funcargs(ls, v, line);+ break;+ }+ case '(': case TK_STRING: case '{': { /* funcargs */+ luaK_exp2nextreg(fs, v);+ funcargs(ls, v, line);+ break;+ }+ default: return;+ }+ }+}+++static void simpleexp (LexState *ls, expdesc *v) {+ /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |+ constructor | FUNCTION body | suffixedexp */+ switch (ls->t.token) {+ case TK_NUMBER: {+ init_exp(v, VKNUM, 0);+ v->u.nval = ls->t.seminfo.r;+ break;+ }+ case TK_STRING: {+ codestring(ls, v, ls->t.seminfo.ts);+ break;+ }+ case TK_NIL: {+ init_exp(v, VNIL, 0);+ break;+ }+ case TK_TRUE: {+ init_exp(v, VTRUE, 0);+ break;+ }+ case TK_FALSE: {+ init_exp(v, VFALSE, 0);+ break;+ }+ case TK_DOTS: { /* vararg */+ FuncState *fs = ls->fs;+ check_condition(ls, fs->f->is_vararg,+ "cannot use " LUA_QL("...") " outside a vararg function");+ init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));+ break;+ }+ case '{': { /* constructor */+ constructor(ls, v);+ return;+ }+ case TK_FUNCTION: {+ luaX_next(ls);+ body(ls, v, 0, ls->linenumber);+ return;+ }+ case TK_PRINT: { /* '?' - print as expression, returns right-most x position */+ printexpr(ls, v, ls->linenumber);+ return;+ }+ default: {+ suffixedexp(ls, v);+ return;+ }+ }+ luaX_next(ls);+}+++static UnOpr getunopr (int op) {+ switch (op) {+ case TK_NOT: return OPR_NOT;+ case '-': return OPR_MINUS;+ case '~': return OPR_BNOT;+ case '@': return OPR_PEEK;+ case '%': return OPR_PEEK2;+ case '$': return OPR_PEEK4;+ case '#': return OPR_LEN;+ default: return OPR_NOUNOPR;+ }+}+++static BinOpr getbinopr (int op) {+ switch (op) {+ case '+': return OPR_ADD;+ case '-': return OPR_SUB;+ case '*': return OPR_MUL;+ case '/': return OPR_DIV;+ case '%': return OPR_MOD;+ case '^': return OPR_POW;+ case '\\': return OPR_IDIV;+ case '&': return OPR_BAND;+ case '|': return OPR_BOR;+ case '~': case TK_BXOR: return OPR_BXOR;+ case TK_SHL: return OPR_SHL;+ case TK_SHR: return OPR_SHR;+ case TK_LSHR: return OPR_LSHR;+ case TK_ROTL: return OPR_ROTL;+ case TK_ROTR: return OPR_ROTR;+ case TK_CONCAT: return OPR_CONCAT;+ case TK_NE: case TK_NE2: return OPR_NE;+ case TK_EQ: return OPR_EQ;+ case '<': return OPR_LT;+ case TK_LE: return OPR_LE;+ case '>': return OPR_GT;+ case TK_GE: return OPR_GE;+ case TK_AND: return OPR_AND;+ case TK_OR: return OPR_OR;+ default: return OPR_NOBINOPR;+ }+}+++static const struct {+ lu_byte left; /* left priority for each binary operator */+ lu_byte right; /* right priority */+} priority[] = { /* ORDER OPR */+ {10, 10}, {10, 10}, /* `+' `-' */+ {11, 11}, {11, 11}, {11, 11}, /* `*' `/' `%' */+ {13, 12}, /* ^ (right associative) */+ {11, 11}, /* `\' */+ {6, 6}, {4, 4}, {5, 5}, /* `&' `|' `^^' */+ {7, 7}, {7, 7}, {7, 7}, /* `<<' `>>' `>>>' */+ {7, 7}, {7, 7}, /* `<<>' `>><' */+ {9, 8}, /* .. (right associative) */+ {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */+ {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */+ {2, 2}, {1, 1} /* and, or */+};++#define UNARY_PRIORITY 12 /* priority for unary operators */+++/*+** subexpr -> (simpleexp | unop subexpr) { binop subexpr }+** where `binop' is any binary operator with a priority higher than `limit'+*/+static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {+ BinOpr op;+ UnOpr uop;+ enterlevel(ls);+ uop = getunopr(ls->t.token);+ if (uop != OPR_NOUNOPR) {+ int line = ls->linenumber;+ luaX_next(ls);+ subexpr(ls, v, UNARY_PRIORITY);+ luaK_prefix(ls->fs, uop, v, line);+ }+ else simpleexp(ls, v);+ /* expand while operators have priorities higher than `limit' */+ op = getbinopr(ls->t.token);+ while (op != OPR_NOBINOPR && priority[op].left > limit) {+ expdesc v2;+ BinOpr nextop;+ int line = ls->linenumber;+ luaX_next(ls);+ luaK_infix(ls->fs, op, v);+ /* read sub-expression with higher priority */+ nextop = subexpr(ls, &v2, priority[op].right);+ luaK_posfix(ls->fs, op, v, &v2, line);+ op = nextop;+ }+ leavelevel(ls);+ return op; /* return first untreated operator */+}+++static void expr (LexState *ls, expdesc *v) {+ subexpr(ls, v, 0);+}++/* }==================================================================== */++++/*+** {======================================================================+** Rules for Statements+** =======================================================================+*/+++static void block (LexState *ls) {+ /* block -> statlist */+ FuncState *fs = ls->fs;+ BlockCnt bl;+ enterblock(fs, &bl, 0);+ statlist(ls);+ leaveblock(fs);+}+++/*+** structure to chain all variables in the left-hand side of an+** assignment+*/+struct LHS_assign {+ struct LHS_assign *prev;+ expdesc v; /* variable (global, local, upvalue, or indexed) */+};+++/*+** check whether, in an assignment to an upvalue/local variable, the+** upvalue/local variable is begin used in a previous assignment to a+** table. If so, save original upvalue/local value in a safe place and+** use this safe copy in the previous assignment.+*/+static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {+ FuncState *fs = ls->fs;+ int extra = fs->freereg; /* eventual position to save local variable */+ int conflict = 0;+ for (; lh; lh = lh->prev) { /* check all previous assignments */+ if (lh->v.k == VINDEXED) { /* assigning to a table? */+ /* table is the upvalue/local being assigned now? */+ if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) {+ conflict = 1;+ lh->v.u.ind.vt = VLOCAL;+ lh->v.u.ind.t = extra; /* previous assignment will use safe copy */+ }+ /* index is the local being assigned? (index cannot be upvalue) */+ if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) {+ conflict = 1;+ lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */+ }+ }+ }+ if (conflict) {+ /* copy upvalue/local value to a temporary (in position 'extra') */+ OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;+ luaK_codeABC(fs, op, extra, v->u.info, 0);+ luaK_reserveregs(fs, 1);+ }+}+++static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {+ expdesc e;+ check_condition(ls, vkisvar(lh->v.k), "syntax error");+ if (testnext(ls, ',')) { /* assignment -> ',' suffixedexp assignment */+ struct LHS_assign nv;+ nv.prev = lh;+ suffixedexp(ls, &nv.v);+ if (nv.v.k != VINDEXED)+ check_conflict(ls, lh, &nv.v);+ checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS,+ "C levels");+ assignment(ls, &nv, nvars+1);+ }+ else { /* assignment -> `=' explist */+ int nexps;+ checknext(ls, '=');+ nexps = explist(ls, &e);+ if (nexps != nvars) {+ adjust_assign(ls, nvars, nexps, &e);+ if (nexps > nvars)+ ls->fs->freereg -= nexps - nvars; /* remove extra values */+ }+ else {+ luaK_setoneret(ls->fs, &e); /* close last expression */+ luaK_storevar(ls->fs, &lh->v, &e);+ return; /* avoid default */+ }+ }+ init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */+ luaK_storevar(ls->fs, &lh->v, &e);+}+++static void compound (LexState *ls, expdesc *v) {+ int i, line, extra;+ FuncState *fs = ls->fs;+ expdesc e1 = *v, e2;+ /* compound -> ( `+=' | `-=' | `*=' | `/=' | etc. ) expression */+ BinOpr op = ls->t.token >= TK_ADDE && ls->t.token <= TK_CONCATE ?+ (BinOpr)(ls->t.token - TK_ADDE + OPR_ADD) :+ OPR_NOBINOPR;+ extra = fs->freereg - fs->nactvar;+ for (i = 0; i < extra; ++i)+ new_localvarliteral(ls, "(for compound)");+ adjustlocalvars(ls, extra);++ luaX_next(ls);+ line = ls->linenumber;++ enterlevel(ls);+ luaK_infix(fs, op, &e1);+ expr(ls, &e2);+ luaK_posfix(fs, op, &e1, &e2, line);+ leavelevel(ls);++ luaK_exp2nextreg(fs, &e1);+ luaK_setoneret(ls->fs, &e1);+ luaK_storevar(ls->fs, v, &e1);+}+++static int cond (LexState *ls) {+ /* cond -> exp */+ expdesc v;+ expr(ls, &v); /* read condition */+ if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */+ luaK_goiftrue(ls->fs, &v);+ return v.f;+}+++static void gotostat (LexState *ls, int pc) {+ int line = ls->linenumber;+ TString *label;+ int g;+ if (testnext(ls, TK_GOTO))+ label = str_checkname(ls);+ else {+ luaX_next(ls); /* skip break */+ label = luaS_new(ls->L, "break");+ }+ g = newlabelentry(ls, &ls->dyd->gt, label, line, pc);+ findlabel(ls, g); /* close it if label already defined */+}+++/* check for repeated labels on the same block */+static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {+ int i;+ for (i = fs->bl->firstlabel; i < ll->n; i++) {+ if (luaS_eqstr(label, ll->arr[i].name)) {+ const char *msg = luaO_pushfstring(fs->ls->L,+ "label " LUA_QS " already defined on line %d",+ getstr(label), ll->arr[i].line);+ semerror(fs->ls, msg);+ }+ }+}+++/* skip no-op statements */+static void skipnoopstat (LexState *ls) {+ while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)+ statement(ls);+}+++static void labelstat (LexState *ls, TString *label, int line) {+ /* label -> '::' NAME '::' */+ FuncState *fs = ls->fs;+ Labellist *ll = &ls->dyd->label;+ int l; /* index of new label being created */+ checkrepeated(fs, ll, label); /* check for repeated labels */+ checknext(ls, TK_DBCOLON); /* skip double colon */+ /* create new entry for this label */+ l = newlabelentry(ls, ll, label, line, fs->pc);+ skipnoopstat(ls); /* skip other no-op statements */+ if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */+ /* assume that locals are already out of scope */+ ll->arr[l].nactvar = fs->bl->nactvar;+ }+ findgotos(ls, &ll->arr[l]);+}+++static void whilestat (LexState *ls, int line) {+ /* whilestat -> WHILE cond DO block END */+ FuncState *fs = ls->fs;+ int whileinit;+ int condexit;+ BlockCnt bl;+ luaX_next(ls); /* skip WHILE */+ luaX_trackbraces(ls); /* track braces for short WHILE */+ whileinit = luaK_getlabel(fs);+ condexit = cond(ls);+ enterblock(fs, &bl, 1);+ int short_while = ls->t.token != TK_DO && ls->t.token != TK_EOS+ && ls->braces == 0 && line == ls->linenumber;+ if (short_while) {+ ls->emiteol = 1;+ ls->short_nest++;+ }+ else+ checknext(ls, TK_DO);+ block(ls);+ luaK_jumpto(fs, whileinit);+ if (!short_while)+ check_match(ls, TK_END, TK_WHILE, line);+ else {+ ls->short_nest--;+ if (ls->t.token == TK_EOL || ls->t.token == TK_EOS) {+ if (ls->short_nest == 0) luaX_next(ls); /* eat EOL or EOS */+ } else if (block_follow(ls, 1))+ ls->emiteol = 0; /* close the short WHILE */+ else+ check_match(ls, TK_EOL, TK_WHILE, line); /* we expected EOL */+ }+ leaveblock(fs);+ luaK_patchtohere(fs, condexit); /* false conditions finish the loop */+}+++static void repeatstat (LexState *ls, int line) {+ /* repeatstat -> REPEAT block UNTIL cond */+ int condexit;+ FuncState *fs = ls->fs;+ int repeat_init = luaK_getlabel(fs);+ BlockCnt bl1, bl2;+ enterblock(fs, &bl1, 1); /* loop block */+ enterblock(fs, &bl2, 0); /* scope block */+ luaX_next(ls); /* skip REPEAT */+ statlist(ls);+ check_match(ls, TK_UNTIL, TK_REPEAT, line);+ condexit = cond(ls); /* read condition (inside scope block) */+ if (bl2.upval) /* upvalues? */+ luaK_patchclose(fs, condexit, bl2.nactvar);+ leaveblock(fs); /* finish scope */+ luaK_patchlist(fs, condexit, repeat_init); /* close the loop */+ leaveblock(fs); /* finish loop */+}+++static int exp1 (LexState *ls) {+ expdesc e;+ int reg;+ expr(ls, &e);+ luaK_exp2nextreg(ls->fs, &e);+ lua_assert(e.k == VNONRELOC);+ reg = e.u.info;+ return reg;+}+++static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {+ /* forbody -> DO block */+ BlockCnt bl;+ FuncState *fs = ls->fs;+ int prep, endfor;+ adjustlocalvars(ls, 3); /* control variables */+ checknext(ls, TK_DO);+ prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);+ enterblock(fs, &bl, 0); /* scope for declared variables */+ adjustlocalvars(ls, nvars);+ luaK_reserveregs(fs, nvars);+ block(ls);+ leaveblock(fs); /* end of scope for declared variables */+ luaK_patchtohere(fs, prep);+ if (isnum) /* numeric for? */+ endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP);+ else { /* generic for */+ luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);+ luaK_fixline(fs, line);+ endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP);+ }+ luaK_patchlist(fs, endfor, prep + 1);+ luaK_fixline(fs, line);+}+++static void fornum (LexState *ls, TString *varname, int line) {+ /* fornum -> NAME = exp1,exp1[,exp1] forbody */+ FuncState *fs = ls->fs;+ int base = fs->freereg;+ new_localvarliteral(ls, "(for index)");+ new_localvarliteral(ls, "(for limit)");+ new_localvarliteral(ls, "(for step)");+ new_localvar(ls, varname);+ checknext(ls, '=');+ exp1(ls); /* initial value */+ checknext(ls, ',');+ exp1(ls); /* limit */+ if (testnext(ls, ','))+ exp1(ls); /* optional step */+ else { /* default step = 1 */+ luaK_codek(fs, fs->freereg, luaK_numberK(fs, cast_num(1)));+ luaK_reserveregs(fs, 1);+ }+ forbody(ls, base, line, 1, 1);+}+++static void forlist (LexState *ls, TString *indexname) {+ /* forlist -> NAME {,NAME} IN explist forbody */+ FuncState *fs = ls->fs;+ expdesc e;+ int nvars = 4; /* gen, state, control, plus at least one declared var */+ int line;+ int base = fs->freereg;+ /* create control variables */+ new_localvarliteral(ls, "(for generator)");+ new_localvarliteral(ls, "(for state)");+ new_localvarliteral(ls, "(for control)");+ /* create declared variables */+ new_localvar(ls, indexname);+ while (testnext(ls, ',')) {+ new_localvar(ls, str_checkname(ls));+ nvars++;+ }+ checknext(ls, TK_IN);+ line = ls->linenumber;+ adjust_assign(ls, 3, explist(ls, &e), &e);+ luaK_checkstack(fs, 3); /* extra space to call generator */+ forbody(ls, base, line, nvars - 3, 0);+}+++static void forstat (LexState *ls, int line) {+ /* forstat -> FOR (fornum | forlist) END */+ FuncState *fs = ls->fs;+ TString *varname;+ BlockCnt bl;+ enterblock(fs, &bl, 1); /* scope for loop and control variables */+ luaX_next(ls); /* skip `for' */+ varname = str_checkname(ls); /* first variable name */+ switch (ls->t.token) {+ case '=': fornum(ls, varname, line); break;+ case ',': case TK_IN: forlist(ls, varname); break;+ default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");+ }+ check_match(ls, TK_END, TK_FOR, line);+ leaveblock(fs); /* loop scope (`break' jumps to this point) */+}+++static int test_then_block (LexState *ls, int *escapelist) {+ /* test_then_block -> [IF | ELSEIF] cond THEN block */+ BlockCnt bl;+ FuncState *fs = ls->fs;+ expdesc v;+ int jf; /* instruction to skip 'then' code (if condition is false) */+ int line = ls->linenumber;+ int short_if = (ls->t.token == TK_IF); /* if TK_IF, can be a short IF */+ luaX_next(ls); /* skip IF or ELSEIF */+ luaX_trackbraces(ls); /* track braces for short IF */+ expr(ls, &v); /* read condition */+ short_if &= ls->t.token != TK_THEN && ls->t.token != TK_DO && ls->t.token != TK_EOS+ && ls->braces == 0 && line == ls->linenumber;+ if (short_if) {+ ls->emiteol = 1;+ ls->short_nest++;+ }+ else {+ /* PICO-8 allows 'do' as alternative to 'then' in if statements */+ if (ls->t.token == TK_DO || ls->t.token == TK_THEN)+ luaX_next(ls); /* skip THEN or DO */+ else+ luaX_syntaxerror(ls, "'then' expected");+ }+ if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {+ luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */+ enterblock(fs, &bl, 0); /* must enter block before 'goto' */+ gotostat(ls, v.t); /* handle goto/break */+ skipnoopstat(ls); /* skip other no-op statements */+ if (block_follow(ls, 0)) { /* 'goto' is the entire block? */+ leaveblock(fs);+ return short_if; /* and that is it */+ }+ else /* must skip over 'then' part if condition is false */+ jf = luaK_jump(fs);+ }+ else { /* regular case (not goto/break) */+ luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */+ enterblock(fs, &bl, 0);+ jf = v.f;+ }+ statlist(ls); /* `then' part */+ leaveblock(fs);+ if (ls->t.token == TK_ELSE ||+ ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */+ luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */+ luaK_patchtohere(fs, jf);+ return short_if;+}+++static void ifstat (LexState *ls, int line) {+ /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */+ FuncState *fs = ls->fs;+ int escapelist = NO_JUMP; /* exit list for finished parts */+ int short_if = test_then_block(ls, &escapelist); /* IF cond THEN block */+ while (ls->t.token == TK_ELSEIF)+ test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */+ if (testnext(ls, TK_ELSE))+ block(ls); /* `else' part */+ if (!short_if)+ check_match(ls, TK_END, TK_IF, line);+ else {+ ls->short_nest--;+ if (ls->t.token == TK_EOL || ls->t.token == TK_EOS) {+ if (ls->short_nest == 0) luaX_next(ls); /* eat EOL or EOS */+ } else if (block_follow(ls, 1))+ ls->emiteol = 0; /* close the short IF */+ else+ check_match(ls, TK_EOL, TK_IF, line); /* we expected EOL */+ }+ luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */+}+++static void localfunc (LexState *ls) {+ expdesc b;+ FuncState *fs = ls->fs;+ new_localvar(ls, str_checkname(ls)); /* new local variable */+ adjustlocalvars(ls, 1); /* enter its scope */+ body(ls, &b, 0, ls->linenumber); /* function created in next register */+ /* debug information will only see the variable after this point! */+ getlocvar(fs, b.u.info)->startpc = fs->pc;+}+++static void localstat (LexState *ls) {+ /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */+ int nvars = 0;+ int nexps;+ expdesc e;+ do {+ new_localvar(ls, str_checkname(ls));+ nvars++;+ } while (testnext(ls, ','));+ if (testnext(ls, '='))+ nexps = explist(ls, &e);+ else {+ e.k = VVOID;+ nexps = 0;+ }+ adjust_assign(ls, nvars, nexps, &e);+ adjustlocalvars(ls, nvars);+}+++static int funcname (LexState *ls, expdesc *v) {+ /* funcname -> NAME {fieldsel} [`:' NAME] */+ int ismethod = 0;+ singlevar(ls, v);+ while (ls->t.token == '.')+ fieldsel(ls, v);+ if (ls->t.token == ':') {+ ismethod = 1;+ fieldsel(ls, v);+ }+ return ismethod;+}+++static void funcstat (LexState *ls, int line) {+ /* funcstat -> FUNCTION funcname body */+ int ismethod;+ expdesc v, b;+ luaX_next(ls); /* skip FUNCTION */+ ismethod = funcname(ls, &v);+ body(ls, &b, ismethod, line);+ luaK_storevar(ls->fs, &v, &b);+ luaK_fixline(ls->fs, line); /* definition `happens' in the first line */+}+++static void exprstat (LexState *ls) {+ /* stat -> func | compound | assignment */+ FuncState *fs = ls->fs;+ struct LHS_assign v;+ suffixedexp(ls, &v.v);+ if (ls->t.token >= TK_ADDE && ls->t.token <= TK_CONCATE) {+ v.prev = NULL;+ compound(ls, &v.v);+ }+ else if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */+ v.prev = NULL;+ assignment(ls, &v, 1);+ }+ else { /* stat -> func */+ check_condition(ls, v.v.k == VCALL, "syntax error");+ SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */+ }+}+++static void retstat (LexState *ls) {+ /* stat -> RETURN [explist] [';'] */+ FuncState *fs = ls->fs;+ expdesc e;+ int first, nret; /* registers with returned values */+ if (block_follow(ls, 1) || ls->t.token == ';')+ first = nret = 0; /* return no values */+ else {+ nret = explist(ls, &e); /* optional return values */+ if (hasmultret(e.k)) {+ luaK_setmultret(fs, &e);+ if (e.k == VCALL && nret == 1) { /* tail call? */+ SET_OPCODE(getcode(fs,&e), OP_TAILCALL);+ lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);+ }+ first = fs->nactvar;+ nret = LUA_MULTRET; /* return all values */+ }+ else {+ if (nret == 1) /* only one single value? */+ first = luaK_exp2anyreg(fs, &e);+ else {+ luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */+ first = fs->nactvar; /* return all `active' values */+ lua_assert(nret == fs->freereg - first);+ }+ }+ }+ luaK_ret(fs, first, nret);+ testnext(ls, ';'); /* skip optional semicolon */+}+++/*+** Parse ?args as an expression (returns the right-most x position)+** Works in both expression and statement context.+**+** When used in expression context (from simpleexp), no EOL handling needed.+** When used in statement context (from shortprint), handle EOL based on short_nest.+*/+static void printexpr (LexState *ls, expdesc *v, int line) {+ FuncState *fs = ls->fs;++ /* same as suffixedexp() except we push "print" first */+ expdesc f;+ TString *n = luaS_new(ls->L, "print");+ ls->t.seminfo.ts = n;+ ls->t.token = TK_NAME;+ singlevar(ls, &f);+ luaK_exp2nextreg(fs, &f);++ /* now we do the same as funcargs() */+ expdesc args;+ if (ls->t.token == TK_EOL || ls->t.token == TK_EOS) /* arg list is empty? */+ args.k = VVOID;+ else {+ explist(ls, &args);+ luaK_setmultret(fs, &args);+ }++ if (!testnext(ls, TK_EOS)) /* check that we are at EOL or EOS */+ check_match(ls, TK_EOL, '?', line);++ /* If we're inside a short-if/while, it was relying on TK_EOL to terminate+ itself, but shortprint just consumed that EOL. Re-inject a synthetic+ TK_EOL so the enclosing short block can still see it and terminate. */+ if (ls->short_nest > 0) {+ ls->lookahead = ls->t;+ ls->t.token = TK_EOL;+ }++ int base, nparams;+ lua_assert(f.k == VNONRELOC);+ base = f.u.info; /* base register for call */+ if (hasmultret(args.k))+ nparams = LUA_MULTRET; /* open call */+ else {+ if (args.k != VVOID)+ luaK_exp2nextreg(fs, &args); /* close last argument */+ nparams = fs->freereg - (base+1);+ }++ init_exp(v, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));+ luaK_fixline(fs, line);+ /* Note: the result stays on stack */+}+++static void shortprint (LexState *ls) {+ int line = ls->linenumber;++ /* Parse ?args as expression */+ expdesc v;+ printexpr(ls, &v, line);++ /* Discard the result since this is a statement context */+ luaK_exp2nextreg(ls->fs, &v);+ ls->fs->freereg = ls->fs->nactvar;+}+++static void statement (LexState *ls) {+ int line = ls->linenumber; /* may be needed for error messages */+ enterlevel(ls);+ switch (ls->t.token) {+ case ';': { /* stat -> ';' (empty statement) */+ luaX_next(ls); /* skip ';' */+ break;+ }+ case TK_PRINT: {+ shortprint(ls); /* stat -> shortprint (on a single line) */+ break;+ }+ case TK_IF: { /* stat -> ifstat */+ ifstat(ls, line);+ break;+ }+ case TK_WHILE: { /* stat -> whilestat */+ whilestat(ls, line);+ break;+ }+ case TK_DO: { /* stat -> DO block END */+ luaX_next(ls); /* skip DO */+ block(ls);+ check_match(ls, TK_END, TK_DO, line);+ break;+ }+ case TK_FOR: { /* stat -> forstat */+ forstat(ls, line);+ break;+ }+ case TK_REPEAT: { /* stat -> repeatstat */+ repeatstat(ls, line);+ break;+ }+ case TK_FUNCTION: { /* stat -> funcstat */+ funcstat(ls, line);+ break;+ }+ case TK_LOCAL: { /* stat -> localstat */+ luaX_next(ls); /* skip LOCAL */+ if (testnext(ls, TK_FUNCTION)) /* local function? */+ localfunc(ls);+ else+ localstat(ls);+ break;+ }+ case TK_DBCOLON: { /* stat -> label */+ luaX_next(ls); /* skip double colon */+ labelstat(ls, str_checkname(ls), line);+ break;+ }+ case TK_RETURN: { /* stat -> retstat */+ luaX_next(ls); /* skip RETURN */+ retstat(ls);+ break;+ }+ case TK_BREAK: /* stat -> breakstat */+ case TK_GOTO: { /* stat -> 'goto' NAME */+ gotostat(ls, luaK_jump(ls->fs));+ break;+ }+ default: { /* stat -> func | assignment */+ exprstat(ls);+ break;+ }+ }+ lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&+ ls->fs->freereg >= ls->fs->nactvar);+ ls->fs->freereg = ls->fs->nactvar; /* free registers */+ leavelevel(ls);+}++/* }====================================================================== */+++/*+** compiles the main function, which is a regular vararg function with an+** upvalue named LUA_ENV+*/+static void mainfunc (LexState *ls, FuncState *fs) {+ BlockCnt bl;+ expdesc v;+ open_func(ls, fs, &bl);+ fs->f->is_vararg = 1; /* main function is always vararg */+ init_exp(&v, VLOCAL, 0); /* create and... */+ newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */+ luaX_next(ls); /* read first token */+ statlist(ls); /* parse main body */+ check(ls, TK_EOS);+ close_func(ls);+}+++Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,+ Dyndata *dyd, const char *name, int firstchar) {+ LexState lexstate;+ FuncState funcstate;+ Closure *cl = luaF_newLclosure(L, 1); /* create main closure */+ /* anchor closure (to avoid being collected) */+ setclLvalue(L, L->top, cl);+ incr_top(L);+ funcstate.f = cl->l.p = luaF_newproto(L);+ funcstate.f->source = luaS_new(L, name); /* create and anchor TString */+ lexstate.buff = buff;+ lexstate.dyd = dyd;+ dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;+ luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);+ mainfunc(&lexstate, &funcstate);+ lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);+ /* all scopes should be correctly finished */+ lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);+ return cl; /* it's on the stack too */+}+diff --git a/games/numpico/src/femto8/lua/lparser.h b/games/numpico/src/femto8/lua/lparser.hnew file mode 100644index 00000000..c0136712--- /dev/null+++ b/games/numpico/src/femto8/lua/lparser.h@@ -0,0 +1,123 @@+/*+** $Id: lparser.h,v 1.70 2012/05/08 13:53:33 roberto Exp $+** Lua Parser+** See Copyright Notice in lua.h+*/++#ifndef lparser_h+#define lparser_h++#include "llimits.h"+#include "lobject.h"+#include "lzio.h"+++/*+** Expression descriptor+*/++typedef enum {+ VVOID, /* no value */+ VNIL,+ VTRUE,+ VFALSE,+ VK, /* info = index of constant in `k' */+ VKNUM, /* nval = numerical value */+ VNONRELOC, /* info = result register */+ VLOCAL, /* info = local register */+ VUPVAL, /* info = index of upvalue in 'upvalues' */+ VINDEXED, /* t = table register/upvalue; idx = index R/K */+ VGLOBAL, /* info = global table register */+ VJMP, /* info = instruction pc */+ VRELOCABLE, /* info = instruction pc */+ VCALL, /* info = instruction pc */+ VVARARG /* info = instruction pc */+} expkind;+++#define vkisvar(k) (VLOCAL <= (k) && (k) <= VGLOBAL)+#define vkisinreg(k) ((k) == VNONRELOC || (k) == VLOCAL)++typedef struct expdesc {+ expkind k;+ union {+ struct { /* for indexed variables (VINDEXED) */+ short idx; /* index (R/K) */+ lu_byte t; /* table (register or upvalue) */+ lu_byte vt; /* whether 't' is register (VLOCAL) or upvalue (VUPVAL) */+ } ind;+ struct { /* global*/+ short idx; /* index (R/K) */+ } glb;+ int info; /* for generic use */+ lua_Number nval; /* for VKNUM */+ } u;+ int t; /* patch list of `exit when true' */+ int f; /* patch list of `exit when false' */+} expdesc;+++/* description of active local variable */+typedef struct Vardesc {+ short idx; /* variable index in stack */+} Vardesc;+++/* description of pending goto statements and label statements */+typedef struct Labeldesc {+ TString *name; /* label identifier */+ int pc; /* position in code */+ int line; /* line where it appeared */+ lu_byte nactvar; /* local level where it appears in current block */+} Labeldesc;+++/* list of labels or gotos */+typedef struct Labellist {+ Labeldesc *arr; /* array */+ int n; /* number of entries in use */+ int size; /* array size */+} Labellist;+++/* dynamic structures used by the parser */+typedef struct Dyndata {+ struct { /* list of active local variables */+ Vardesc *arr;+ int n;+ int size;+ } actvar;+ Labellist gt; /* list of pending gotos */+ Labellist label; /* list of active labels */+} Dyndata;+++/* control of blocks */+struct BlockCnt; /* defined in lparser.c */+++/* state needed to generate code for a given function */+typedef struct FuncState {+ Proto *f; /* current function header */+ Table *h; /* table to find (and reuse) elements in `k' */+ struct FuncState *prev; /* enclosing function */+ struct LexState *ls; /* lexical state */+ struct BlockCnt *bl; /* chain of current blocks */+ int pc; /* next position to code (equivalent to `ncode') */+ int lasttarget; /* 'label' of last 'jump label' */+ int jpc; /* list of pending jumps to `pc' */+ int nk; /* number of elements in `k' */+ int np; /* number of elements in `p' */+ int firstlocal; /* index of first local var (in Dyndata array) */+ short nlocvars; /* number of elements in 'f->locvars' */+ lu_byte nactvar; /* number of active local variables */+ lu_byte nups; /* number of upvalues */+ lu_byte freereg; /* first free register */+} FuncState;+++LUAI_FUNC Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,+ Dyndata *dyd, const char *name, int firstchar);+++#endifdiff --git a/games/numpico/src/femto8/lua/lpico8lib.c b/games/numpico/src/femto8/lua/lpico8lib.cnew file mode 100644index 00000000..9db0974b--- /dev/null+++ b/games/numpico/src/femto8/lua/lpico8lib.c@@ -0,0 +1,842 @@+/*+** 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;+}diff --git a/games/numpico/src/femto8/lua/lstate.c b/games/numpico/src/femto8/lua/lstate.cnew file mode 100644index 00000000..4ba4fe6d--- /dev/null+++ b/games/numpico/src/femto8/lua/lstate.c@@ -0,0 +1,324 @@+/*+** $Id: lstate.c,v 2.99.1.1 2013/04/12 18:48:47 roberto Exp roberto $+** Global State+** See Copyright Notice in lua.h+*/+++#include <stddef.h>+#include <string.h>++#define lstate_c+#define LUA_CORE++#include "lua.h"++#include "lapi.h"+#include "ldebug.h"+#include "ldo.h"+#include "lfunc.h"+#include "lgc.h"+#include "llex.h"+#include "lmem.h"+#include "lstate.h"+#include "lstring.h"+#include "ltable.h"+#include "ltm.h"+++#if !defined(LUAI_GCPAUSE)+#define LUAI_GCPAUSE 200 /* 200% */+#endif++#if !defined(LUAI_GCMAJOR)+#define LUAI_GCMAJOR 200 /* 200% */+#endif++#if !defined(LUAI_GCMUL)+#define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */+#endif+++#define MEMERRMSG "not enough memory"+++/*+** a macro to help the creation of a unique random seed when a state is+** created; the seed is used to randomize hashes.+*/+#if !defined(luai_makeseed)+#include <time.h>+#define luai_makeseed() cast(unsigned int, time(NULL))+#endif++++/*+** thread state + extra space+*/+typedef struct LX {+#if defined(LUAI_EXTRASPACE)+ char buff[LUAI_EXTRASPACE];+#endif+ lua_State l;+} LX;+++/*+** Main thread combines a thread state and the global state+*/+typedef struct LG {+ LX l;+ global_State g;+} LG;++++#define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l)))+++/*+** Compute an initial seed as random as possible. In ANSI, rely on+** Address Space Layout Randomization (if present) to increase+** randomness..+*/+#define addbuff(b,p,e) \+ { size_t t = cast(size_t, e); \+ memcpy(buff + p, &t, sizeof(t)); p += sizeof(t); }++static unsigned int makeseed (lua_State *L) {+ char buff[4 * sizeof(size_t)];+ unsigned int h = luai_makeseed();+ int p = 0;+ addbuff(buff, p, L); /* heap variable */+ addbuff(buff, p, &h); /* local variable */+ addbuff(buff, p, luaO_nilobject); /* global variable */+ addbuff(buff, p, &lua_newstate); /* public function */+ lua_assert(p == sizeof(buff));+ return luaS_hash(buff, p, h);+}+++/*+** set GCdebt to a new value keeping the value (totalbytes + GCdebt)+** invariant+*/+void luaE_setdebt (global_State *g, l_mem debt) {+ g->totalbytes -= (debt - g->GCdebt);+ g->GCdebt = debt;+}+++CallInfo *luaE_extendCI (lua_State *L) {+ CallInfo *ci = luaM_new(L, CallInfo);+ lua_assert(L->ci->next == NULL);+ L->ci->next = ci;+ ci->previous = L->ci;+ ci->next = NULL;+ return ci;+}+++void luaE_freeCI (lua_State *L) {+ CallInfo *ci = L->ci;+ CallInfo *next = ci->next;+ ci->next = NULL;+ while ((ci = next) != NULL) {+ next = ci->next;+ luaM_free(L, ci);+ }+}+++static void stack_init (lua_State *L1, lua_State *L) {+ int i; CallInfo *ci;+ /* initialize stack array */+ L1->stack = luaM_newvector(L, BASIC_STACK_SIZE, TValue);+ L1->stacksize = BASIC_STACK_SIZE;+ for (i = 0; i < BASIC_STACK_SIZE; i++)+ setnilvalue(L1->stack + i); /* erase new stack */+ L1->top = L1->stack;+ L1->stack_last = L1->stack + L1->stacksize - EXTRA_STACK;+ /* initialize first ci */+ ci = &L1->base_ci;+ ci->next = ci->previous = NULL;+ ci->callstatus = 0;+ ci->func = L1->top;+ setnilvalue(L1->top++); /* 'function' entry for this 'ci' */+ ci->top = L1->top + LUA_MINSTACK;+ L1->ci = ci;+}+++static void freestack (lua_State *L) {+ if (L->stack == NULL)+ return; /* stack not completely built yet */+ L->ci = &L->base_ci; /* free the entire 'ci' list */+ luaE_freeCI(L);+ luaM_freearray(L, L->stack, L->stacksize); /* free stack array */+}+++/*+** Create registry table and its predefined values+*/+static void init_registry (lua_State *L, global_State *g) {+ TValue mt;+ /* create registry */+ Table *registry = luaH_new(L);+ sethvalue(L, &g->l_registry, registry);+ luaH_resize(L, registry, LUA_RIDX_LAST, 0);+ /* registry[LUA_RIDX_MAINTHREAD] = L */+ setthvalue(L, &mt, L);+ luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &mt);+ /* registry[LUA_RIDX_GLOBALS] = table of globals */+ sethvalue(L, &mt, luaH_new(L));+ luaH_setint(L, registry, LUA_RIDX_GLOBALS, &mt);+}+++/*+** open parts of the state that may cause memory-allocation errors+*/+static void f_luaopen (lua_State *L, void *ud) {+ global_State *g = G(L);+ UNUSED(ud);+ stack_init(L, L); /* init stack */+ init_registry(L, g);+ luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */+ luaT_init(L);+ luaX_init(L);+ /* pre-create memory-error message */+ g->memerrmsg = luaS_newliteral(L, MEMERRMSG);+ luaS_fix(g->memerrmsg); /* it should never be collected */+ g->gcrunning = 1; /* allow gc */+ g->version = lua_version(NULL);+ luai_userstateopen(L);+}+++/*+** preinitialize a state with consistent values without allocating+** any memory (to avoid errors)+*/+static void preinit_state (lua_State *L, global_State *g) {+ G(L) = g;+ L->stack = NULL;+ L->ci = NULL;+ L->stacksize = 0;+ L->errorJmp = NULL;+ L->nCcalls = 0;+ L->hook = NULL;+ L->hookmask = 0;+ L->basehookcount = 0;+ L->allowhook = 1;+ resethookcount(L);+ L->openupval = NULL;+ L->nny = 1;+ L->status = LUA_OK;+ L->errfunc = 0;+}+++static void close_state (lua_State *L) {+ global_State *g = G(L);+ luaF_close(L, L->stack); /* close all upvalues for this thread */+ luaC_freeallobjects(L); /* collect all objects */+ if (g->version) /* closing a fully built state? */+ luai_userstateclose(L);+ luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size);+ luaZ_freebuffer(L, &g->buff);+ freestack(L);+ lua_assert(gettotalbytes(g) == sizeof(LG));+ (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0); /* free main block */+}+++LUA_API lua_State *lua_newthread (lua_State *L) {+ lua_State *L1;+ lua_lock(L);+ luaC_checkGC(L);+ L1 = &luaC_newobj(L, LUA_TTHREAD, sizeof(LX), NULL, offsetof(LX, l))->th;+ setthvalue(L, L->top, L1);+ api_incr_top(L);+ preinit_state(L1, G(L));+ L1->hookmask = L->hookmask;+ L1->basehookcount = L->basehookcount;+ L1->hook = L->hook;+ resethookcount(L1);+ luai_userstatethread(L, L1);+ stack_init(L1, L); /* init stack */+ lua_unlock(L);+ return L1;+}+++void luaE_freethread (lua_State *L, lua_State *L1) {+ LX *l = fromstate(L1);+ luaF_close(L1, L1->stack); /* close all upvalues for this thread */+ lua_assert(L1->openupval == NULL);+ luai_userstatefree(L, L1);+ freestack(L1);+ luaM_free(L, l);+}+++LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {+ int i;+ lua_State *L;+ global_State *g;+ LG *l = cast(LG *, (*f)(ud, NULL, LUA_TTHREAD, sizeof(LG)));+ if (l == NULL) return NULL;+ L = &l->l.l;+ g = &l->g;+ L->next = NULL;+ L->tt = LUA_TTHREAD;+ g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT);+ L->marked = luaC_white(g);+ g->gckind = KGC_NORMAL;+ preinit_state(L, g);+ g->frealloc = f;+ g->ud = ud;+ g->mainthread = L;+ g->seed = makeseed(L);+ g->uvhead.u.l.prev = &g->uvhead;+ g->uvhead.u.l.next = &g->uvhead;+ g->gcrunning = 0; /* no GC while building state */+ g->GCestimate = 0;+ g->strt.size = 0;+ g->strt.nuse = 0;+ g->strt.hash = NULL;+ setnilvalue(&g->l_registry);+ luaZ_initbuffer(L, &g->buff);+ g->panic = NULL;+ g->version = NULL;+ g->gcstate = GCSpause;+ g->allgc = NULL;+ g->finobj = NULL;+ g->tobefnz = NULL;+ g->sweepgc = g->sweepfin = NULL;+ g->gray = g->grayagain = NULL;+ g->weak = g->ephemeron = g->allweak = NULL;+ g->totalbytes = sizeof(LG);+ g->GCdebt = 0;+ g->gcpause = LUAI_GCPAUSE;+ g->gcmajorinc = LUAI_GCMAJOR;+ g->gcstepmul = LUAI_GCMUL;+ for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL;+ g->pico8memory = NULL;+ if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) {+ /* memory allocation error: free partial state */+ close_state(L);+ L = NULL;+ }+ return L;+}+++LUA_API void lua_close (lua_State *L) {+ L = G(L)->mainthread; /* only the main thread can be closed */+ lua_lock(L);+ close_state(L);+}++diff --git a/games/numpico/src/femto8/lua/lstate.h b/games/numpico/src/femto8/lua/lstate.hnew file mode 100644index 00000000..0cd0ec37--- /dev/null+++ b/games/numpico/src/femto8/lua/lstate.h@@ -0,0 +1,229 @@+/*+** $Id: lstate.h,v 2.82 2012/07/02 13:37:04 roberto Exp $+** Global State+** See Copyright Notice in lua.h+*/++#ifndef lstate_h+#define lstate_h++#include "lua.h"++#include "lobject.h"+#include "ltm.h"+#include "lzio.h"+++/*++** Some notes about garbage-collected objects: All objects in Lua must+** be kept somehow accessible until being freed.+**+** Lua keeps most objects linked in list g->allgc. The link uses field+** 'next' of the CommonHeader.+**+** Strings are kept in several lists headed by the array g->strt.hash.+**+** Open upvalues are not subject to independent garbage collection. They+** are collected together with their respective threads. Lua keeps a+** double-linked list with all open upvalues (g->uvhead) so that it can+** mark objects referred by them. (They are always gray, so they must+** be remarked in the atomic step. Usually their contents would be marked+** when traversing the respective threads, but the thread may already be+** dead, while the upvalue is still accessible through closures.)+**+** Objects with finalizers are kept in the list g->finobj.+**+** The list g->tobefnz links all objects being finalized.++*/+++struct lua_longjmp; /* defined in ldo.c */++++/* extra stack space to handle TM calls and some other extras */+#define EXTRA_STACK 5+++#define BASIC_STACK_SIZE (2*LUA_MINSTACK)+++/* kinds of Garbage Collection */+#define KGC_NORMAL 0+#define KGC_EMERGENCY 1 /* gc was forced by an allocation failure */+#define KGC_GEN 2 /* generational collection */+++typedef struct stringtable {+ GCObject **hash;+ lu_int32 nuse; /* number of elements */+ int size;+} stringtable;+++/*+** information about a call+*/+typedef struct CallInfo {+ StkId func; /* function index in the stack */+ StkId top; /* top for this function */+ struct CallInfo *previous, *next; /* dynamic call link */+ short nresults; /* expected number of results from this function */+ lu_byte callstatus;+ ptrdiff_t extra;+ union {+ struct { /* only for Lua functions */+ StkId base; /* base for this function */+ const Instruction *savedpc;+ } l;+ struct { /* only for C functions */+ int ctx; /* context info. in case of yields */+ lua_CFunction k; /* continuation in case of yields */+ ptrdiff_t old_errfunc;+ lu_byte old_allowhook;+ lu_byte status;+ } c;+ } u;+} CallInfo;+++/*+** Bits in CallInfo status+*/+#define CIST_LUA (1<<0) /* call is running a Lua function */+#define CIST_HOOKED (1<<1) /* call is running a debug hook */+#define CIST_REENTRY (1<<2) /* call is running on same invocation of+ luaV_execute of previous call */+#define CIST_YIELDED (1<<3) /* call reentered after suspension */+#define CIST_YPCALL (1<<4) /* call is a yieldable protected call */+#define CIST_STAT (1<<5) /* call has an error status (pcall) */+#define CIST_TAIL (1<<6) /* call was tail called */+#define CIST_HOOKYIELD (1<<7) /* last hook called yielded */+++#define isLua(ci) ((ci)->callstatus & CIST_LUA)+++/*+** `global state', shared by all threads of this state+*/+typedef struct global_State {+ lua_Alloc frealloc; /* function to reallocate memory */+ void *ud; /* auxiliary data to `frealloc' */+ lu_mem totalbytes; /* number of bytes currently allocated - GCdebt */+ l_mem GCdebt; /* bytes allocated not yet compensated by the collector */+ lu_mem GCmemtrav; /* memory traversed by the GC */+ lu_mem GCestimate; /* an estimate of the non-garbage memory in use */+ stringtable strt; /* hash table for strings */+ TValue l_registry;+ unsigned int seed; /* randomized seed for hashes */+ lu_byte currentwhite;+ lu_byte gcstate; /* state of garbage collector */+ lu_byte gckind; /* kind of GC running */+ lu_byte gcrunning; /* true if GC is running */+ int sweepstrgc; /* position of sweep in `strt' */+ GCObject *allgc; /* list of all collectable objects */+ GCObject *finobj; /* list of collectable objects with finalizers */+ GCObject **sweepgc; /* current position of sweep in list 'allgc' */+ GCObject **sweepfin; /* current position of sweep in list 'finobj' */+ GCObject *gray; /* list of gray objects */+ GCObject *grayagain; /* list of objects to be traversed atomically */+ GCObject *weak; /* list of tables with weak values */+ GCObject *ephemeron; /* list of ephemeron tables (weak keys) */+ GCObject *allweak; /* list of all-weak tables */+ GCObject *tobefnz; /* list of userdata to be GC */+ UpVal uvhead; /* head of double-linked list of all open upvalues */+ Mbuffer buff; /* temporary buffer for string concatenation */+ int gcpause; /* size of pause between successive GCs */+ int gcmajorinc; /* pause between major collections (only in gen. mode) */+ int gcstepmul; /* GC `granularity' */+ lua_CFunction panic; /* to be called in unprotected errors */+ lu_byte const *pico8memory; /* pointer to PICO-8 RAM */+ struct lua_State *mainthread;+ const lua_Number *version; /* pointer to version number */+ TString *memerrmsg; /* memory-error message */+ TString *tmname[TM_N]; /* array with tag-method names */+ struct Table *mt[LUA_NUMTAGS]; /* metatables for basic types */+} global_State;+++/*+** `per thread' state+*/+struct lua_State {+ CommonHeader;+ lu_byte status;+ StkId top; /* first free slot in the stack */+ global_State *l_G;+ CallInfo *ci; /* call info for current function */+ const Instruction *oldpc; /* last pc traced */+ StkId stack_last; /* last free slot in the stack */+ StkId stack; /* stack base */+ int stacksize;+ unsigned short nny; /* number of non-yieldable calls in stack */+ unsigned short nCcalls; /* number of nested C calls */+ lu_byte hookmask;+ lu_byte allowhook;+ int basehookcount;+ int hookcount;+ lua_Hook hook;+ GCObject *openupval; /* list of open upvalues in this stack */+ GCObject *gclist;+ struct lua_longjmp *errorJmp; /* current error recover point */+ ptrdiff_t errfunc; /* current error handling function (stack index) */+ CallInfo base_ci; /* CallInfo for first level (C calling Lua) */+};+++#define G(L) (L->l_G)+++/*+** Union of all collectable objects+*/+union GCObject {+ GCheader gch; /* common header */+ union TString ts;+ union Udata u;+ union Closure cl;+ struct Table h;+ struct Proto p;+ struct UpVal uv;+ struct lua_State th; /* thread */+};+++#define gch(o) (&(o)->gch)++/* macros to convert a GCObject into a specific value */+#define rawgco2ts(o) \+ check_exp(novariant((o)->gch.tt) == LUA_TSTRING, &((o)->ts))+#define gco2ts(o) (&rawgco2ts(o)->tsv)+#define rawgco2u(o) check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u))+#define gco2u(o) (&rawgco2u(o)->uv)+#define gco2lcl(o) check_exp((o)->gch.tt == LUA_TLCL, &((o)->cl.l))+#define gco2ccl(o) check_exp((o)->gch.tt == LUA_TCCL, &((o)->cl.c))+#define gco2cl(o) \+ check_exp(novariant((o)->gch.tt) == LUA_TFUNCTION, &((o)->cl))+#define gco2t(o) check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h))+#define gco2p(o) check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p))+#define gco2uv(o) check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv))+#define gco2th(o) check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th))++/* macro to convert any Lua object into a GCObject */+#define obj2gco(v) (cast(GCObject *, (v)))+++/* actual number of total bytes allocated */+#define gettotalbytes(g) ((g)->totalbytes + (g)->GCdebt)++LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);+LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);+LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);+LUAI_FUNC void luaE_freeCI (lua_State *L);+++#endif+diff --git a/games/numpico/src/femto8/lua/lstring.c b/games/numpico/src/femto8/lua/lstring.cnew file mode 100644index 00000000..8b5af0b2--- /dev/null+++ b/games/numpico/src/femto8/lua/lstring.c@@ -0,0 +1,185 @@+/*+** $Id: lstring.c,v 2.26 2013/01/08 13:50:10 roberto Exp $+** String table (keeps all strings handled by Lua)+** See Copyright Notice in lua.h+*/+++#include <string.h>++#define lstring_c+#define LUA_CORE++#include "lua.h"++#include "lmem.h"+#include "lobject.h"+#include "lstate.h"+#include "lstring.h"+++/*+** Lua will use at most ~(2^LUAI_HASHLIMIT) bytes from a string to+** compute its hash+*/+#if !defined(LUAI_HASHLIMIT)+#define LUAI_HASHLIMIT 5+#endif+++/*+** equality for long strings+*/+int luaS_eqlngstr (TString *a, TString *b) {+ size_t len = a->tsv.len;+ lua_assert(a->tsv.tt == LUA_TLNGSTR && b->tsv.tt == LUA_TLNGSTR);+ return (a == b) || /* same instance or... */+ ((len == b->tsv.len) && /* equal length and ... */+ (memcmp(getstr(a), getstr(b), len) == 0)); /* equal contents */+}+++/*+** equality for strings+*/+int luaS_eqstr (TString *a, TString *b) {+ return (a->tsv.tt == b->tsv.tt) &&+ (a->tsv.tt == LUA_TSHRSTR ? eqshrstr(a, b) : luaS_eqlngstr(a, b));+}+++unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) {+ unsigned int h = seed ^ cast(unsigned int, l);+ size_t l1;+ size_t step = (l >> LUAI_HASHLIMIT) + 1;+ for (l1 = l; l1 >= step; l1 -= step)+ h = h ^ ((h<<5) + (h>>2) + cast_byte(str[l1 - 1]));+ return h;+}+++/*+** resizes the string table+*/+void luaS_resize (lua_State *L, int newsize) {+ int i;+ stringtable *tb = &G(L)->strt;+ /* cannot resize while GC is traversing strings */+ luaC_runtilstate(L, ~bitmask(GCSsweepstring));+ if (newsize > tb->size) {+ luaM_reallocvector(L, tb->hash, tb->size, newsize, GCObject *);+ for (i = tb->size; i < newsize; i++) tb->hash[i] = NULL;+ }+ /* rehash */+ for (i=0; i<tb->size; i++) {+ GCObject *p = tb->hash[i];+ tb->hash[i] = NULL;+ while (p) { /* for each node in the list */+ GCObject *next = gch(p)->next; /* save next */+ unsigned int h = lmod(gco2ts(p)->hash, newsize); /* new position */+ gch(p)->next = tb->hash[h]; /* chain it */+ tb->hash[h] = p;+ resetoldbit(p); /* see MOVE OLD rule */+ p = next;+ }+ }+ if (newsize < tb->size) {+ /* shrinking slice must be empty */+ lua_assert(tb->hash[newsize] == NULL && tb->hash[tb->size - 1] == NULL);+ luaM_reallocvector(L, tb->hash, tb->size, newsize, GCObject *);+ }+ tb->size = newsize;+}+++/*+** creates a new string object+*/+static TString *createstrobj (lua_State *L, const char *str, size_t l,+ int tag, unsigned int h, GCObject **list) {+ TString *ts;+ size_t totalsize; /* total size of TString object */+ totalsize = sizeof(TString) + ((l + 1) * sizeof(char));+ ts = &luaC_newobj(L, tag, totalsize, list, 0)->ts;+ ts->tsv.len = l;+ ts->tsv.hash = h;+ ts->tsv.extra = 0;+ memcpy(ts+1, str, l*sizeof(char));+ ((char *)(ts+1))[l] = '\0'; /* ending 0 */+ return ts;+}+++/*+** creates a new short string, inserting it into string table+*/+static TString *newshrstr (lua_State *L, const char *str, size_t l,+ unsigned int h) {+ GCObject **list; /* (pointer to) list where it will be inserted */+ stringtable *tb = &G(L)->strt;+ TString *s;+ if (tb->nuse >= cast(lu_int32, tb->size) && tb->size <= MAX_INT/2)+ luaS_resize(L, tb->size*2); /* too crowded */+ list = &tb->hash[lmod(h, tb->size)];+ s = createstrobj(L, str, l, LUA_TSHRSTR, h, list);+ tb->nuse++;+ return s;+}+++/*+** checks whether short string exists and reuses it or creates a new one+*/+static TString *internshrstr (lua_State *L, const char *str, size_t l) {+ GCObject *o;+ global_State *g = G(L);+ unsigned int h = luaS_hash(str, l, g->seed);+ for (o = g->strt.hash[lmod(h, g->strt.size)];+ o != NULL;+ o = gch(o)->next) {+ TString *ts = rawgco2ts(o);+ if (h == ts->tsv.hash &&+ l == ts->tsv.len &&+ (memcmp(str, getstr(ts), l * sizeof(char)) == 0)) {+ if (isdead(G(L), o)) /* string is dead (but was not collected yet)? */+ changewhite(o); /* resurrect it */+ return ts;+ }+ }+ return newshrstr(L, str, l, h); /* not found; create a new string */+}+++/*+** new string (with explicit length)+*/+TString *luaS_newlstr (lua_State *L, const char *str, size_t l) {+ if (l <= LUAI_MAXSHORTLEN) /* short string? */+ return internshrstr(L, str, l);+ else {+ if (l + 1 > (MAX_SIZET - sizeof(TString))/sizeof(char))+ luaM_toobig(L);+ return createstrobj(L, str, l, LUA_TLNGSTR, G(L)->seed, NULL);+ }+}+++/*+** new zero-terminated string+*/+TString *luaS_new (lua_State *L, const char *str) {+ return luaS_newlstr(L, str, strlen(str));+}+++Udata *luaS_newudata (lua_State *L, size_t s, Table *e) {+ Udata *u;+ if (s > MAX_SIZET - sizeof(Udata))+ luaM_toobig(L);+ u = &luaC_newobj(L, LUA_TUSERDATA, sizeof(Udata) + s, NULL, 0)->u;+ u->uv.len = s;+ u->uv.metatable = NULL;+ u->uv.env = e;+ return u;+}+diff --git a/games/numpico/src/femto8/lua/lstring.h b/games/numpico/src/femto8/lua/lstring.hnew file mode 100644index 00000000..d312ff3d--- /dev/null+++ b/games/numpico/src/femto8/lua/lstring.h@@ -0,0 +1,46 @@+/*+** $Id: lstring.h,v 1.49 2012/02/01 21:57:15 roberto Exp $+** String table (keep all strings handled by Lua)+** See Copyright Notice in lua.h+*/++#ifndef lstring_h+#define lstring_h++#include "lgc.h"+#include "lobject.h"+#include "lstate.h"+++#define sizestring(s) (sizeof(union TString)+((s)->len+1)*sizeof(char))++#define sizeudata(u) (sizeof(union Udata)+(u)->len)++#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \+ (sizeof(s)/sizeof(char))-1))++#define luaS_fix(s) l_setbit((s)->tsv.marked, FIXEDBIT)+++/*+** test whether a string is a reserved word+*/+#define isreserved(s) ((s)->tsv.tt == LUA_TSHRSTR && (s)->tsv.extra > 0)+++/*+** equality for short strings, which are always internalized+*/+#define eqshrstr(a,b) check_exp((a)->tsv.tt == LUA_TSHRSTR, (a) == (b))+++LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed);+LUAI_FUNC int luaS_eqlngstr (TString *a, TString *b);+LUAI_FUNC int luaS_eqstr (TString *a, TString *b);+LUAI_FUNC void luaS_resize (lua_State *L, int newsize);+LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e);+LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l);+LUAI_FUNC TString *luaS_new (lua_State *L, const char *str);+++#endifdiff --git a/games/numpico/src/femto8/lua/lstrlib.c b/games/numpico/src/femto8/lua/lstrlib.cnew file mode 100644index 00000000..90b3585a--- /dev/null+++ b/games/numpico/src/femto8/lua/lstrlib.c@@ -0,0 +1,1041 @@+/*+** $Id: lstrlib.c,v 1.178 2012/08/14 18:12:34 roberto Exp $+** Standard library for string operations and pattern-matching+** See Copyright Notice in lua.h+** Changed for NumPico: no string.dump (no luaU_dump).+*/+++#include <ctype.h>+#include <stddef.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#define lstrlib_c+#define LUA_LIB++#include "lua.h"++#include "lauxlib.h"+#include "lualib.h"+#include "fix32.h"+++/*+** maximum number of captures that a pattern can do during+** pattern-matching. This limit is arbitrary.+*/+#if !defined(LUA_MAXCAPTURES)+#define LUA_MAXCAPTURES 32+#endif+++/* macro to `unsign' a character */+#define uchar(c) ((unsigned char)(c))++++static int str_len (lua_State *L) {+ size_t l;+ luaL_checklstring(L, 1, &l);+ lua_pushinteger(L, (lua_Integer)l);+ return 1;+}+++/* translate a relative string position: negative means back from end */+static size_t posrelat (ptrdiff_t pos, size_t len) {+ if (pos >= 0) return (size_t)pos;+ else if (0u - (size_t)pos > len) return 0;+ else return len - ((size_t)-pos) + 1;+}+++static int str_sub (lua_State *L) {+ size_t l;+ const char *s = luaL_checklstring(L, 1, &l);+ size_t start = posrelat(luaL_checkinteger(L, 2), l);+ size_t end = posrelat(luaL_optinteger(L, 3, -1), l);+ if (start < 1) start = 1;+ if (end > l) end = l;+ if (start <= end)+ lua_pushlstring(L, s + start - 1, end - start + 1);+ else lua_pushliteral(L, "");+ return 1;+}+++static int str_index (lua_State *L) {+ size_t l;+ const char *s = luaL_checklstring(L, 1, &l);+ if (lua_type(L, 2) == LUA_TNUMBER) {+ int k = fix32_to_int(lua_tonumber(L, 2));+ size_t idx = k > 0 ? k - 1 : l + k;+ if (idx >= l)+ lua_pushnil(L);+ else+ lua_pushlstring(L, s + idx, 1);+ return 1;+ }+ lua_pushvalue(L, lua_upvalueindex(1));+ lua_pushvalue(L, 2);+ lua_gettable(L, -2);+ lua_remove(L, -2);+ return 1;+}+++static int str_reverse (lua_State *L) {+ size_t l, i;+ luaL_Buffer b;+ const char *s = luaL_checklstring(L, 1, &l);+ char *p = luaL_buffinitsize(L, &b, l);+ for (i = 0; i < l; i++)+ p[i] = s[l - i - 1];+ luaL_pushresultsize(&b, l);+ return 1;+}+++static int str_lower (lua_State *L) {+ size_t l;+ size_t i;+ luaL_Buffer b;+ const char *s = luaL_checklstring(L, 1, &l);+ char *p = luaL_buffinitsize(L, &b, l);+ for (i=0; i<l; i++)+ p[i] = tolower(uchar(s[i]));+ luaL_pushresultsize(&b, l);+ return 1;+}+++static int str_upper (lua_State *L) {+ size_t l;+ size_t i;+ luaL_Buffer b;+ const char *s = luaL_checklstring(L, 1, &l);+ char *p = luaL_buffinitsize(L, &b, l);+ for (i=0; i<l; i++)+ p[i] = toupper(uchar(s[i]));+ luaL_pushresultsize(&b, l);+ return 1;+}+++/* reasonable limit to avoid arithmetic overflow */+#define MAXSIZE ((~(size_t)0) >> 1)++static int str_rep (lua_State *L) {+ size_t l, lsep;+ const char *s = luaL_checklstring(L, 1, &l);+ int n = luaL_checkint(L, 2);+ const char *sep = luaL_optlstring(L, 3, "", &lsep);+ if (n <= 0) lua_pushliteral(L, "");+ else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */+ return luaL_error(L, "resulting string too large");+ else {+ size_t totallen = n * l + (n - 1) * lsep;+ luaL_Buffer b;+ char *p = luaL_buffinitsize(L, &b, totallen);+ while (n-- > 1) { /* first n-1 copies (followed by separator) */+ memcpy(p, s, l * sizeof(char)); p += l;+ if (lsep > 0) { /* avoid empty 'memcpy' (may be expensive) */+ memcpy(p, sep, lsep * sizeof(char)); p += lsep;+ }+ }+ memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */+ luaL_pushresultsize(&b, totallen);+ }+ return 1;+}+++static int str_byte (lua_State *L) {+ size_t l;+ const char *s = luaL_checklstring(L, 1, &l);+ size_t posi = posrelat(luaL_optinteger(L, 2, 1), l);+ size_t pose = posrelat(luaL_optinteger(L, 3, posi), l);+ int n, i;+ if (posi < 1) posi = 1;+ if (pose > l) pose = l;+ if (posi > pose) return 0; /* empty interval; return no values */+ n = (int)(pose - posi + 1);+ if (posi + n <= pose) /* (size_t -> int) overflow? */+ return luaL_error(L, "string slice too long");+ luaL_checkstack(L, n, "string slice too long");+ for (i=0; i<n; i++)+ lua_pushinteger(L, uchar(s[posi+i-1]));+ return n;+}+++static int str_char (lua_State *L) {+ int n = lua_gettop(L); /* number of arguments */+ int i;+ luaL_Buffer b;+ char *p = luaL_buffinitsize(L, &b, n);+ for (i=1; i<=n; i++) {+ int c = luaL_checkint(L, i);+ luaL_argcheck(L, uchar(c) == c, i, "value out of range");+ p[i - 1] = uchar(c);+ }+ luaL_pushresultsize(&b, n);+ return 1;+}+++static int writer (lua_State *L, const void* b, size_t size, void* B) {+ (void)L;+ luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);+ return 0;+}+++static int str_dump (lua_State *L) {+ luaL_Buffer b;+ luaL_checktype(L, 1, LUA_TFUNCTION);+ lua_settop(L, 1);+ luaL_buffinit(L,&b);+ if (lua_dump(L, writer, &b) != 0)+ return luaL_error(L, "unable to dump given function");+ luaL_pushresult(&b);+ return 1;+}++++/*+** {======================================================+** PATTERN MATCHING+** =======================================================+*/+++#define CAP_UNFINISHED (-1)+#define CAP_POSITION (-2)+++typedef struct MatchState {+ int matchdepth; /* control for recursive depth (to avoid C stack overflow) */+ const char *src_init; /* init of source string */+ const char *src_end; /* end ('\0') of source string */+ const char *p_end; /* end ('\0') of pattern */+ lua_State *L;+ int level; /* total number of captures (finished or unfinished) */+ struct {+ const char *init;+ ptrdiff_t len;+ } capture[LUA_MAXCAPTURES];+} MatchState;+++/* recursive function */+static const char *match (MatchState *ms, const char *s, const char *p);+++/* maximum recursion depth for 'match' */+#if !defined(MAXCCALLS)+#define MAXCCALLS 200+#endif+++#define L_ESC '%'+#define SPECIALS "^$*+?.([%-"+++static int check_capture (MatchState *ms, int l) {+ l -= '1';+ if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)+ return luaL_error(ms->L, "invalid capture index %%%d", l + 1);+ return l;+}+++static int capture_to_close (MatchState *ms) {+ int level = ms->level;+ for (level--; level>=0; level--)+ if (ms->capture[level].len == CAP_UNFINISHED) return level;+ return luaL_error(ms->L, "invalid pattern capture");+}+++static const char *classend (MatchState *ms, const char *p) {+ switch (*p++) {+ case L_ESC: {+ if (p == ms->p_end)+ luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");+ return p+1;+ }+ case '[': {+ if (*p == '^') p++;+ do { /* look for a `]' */+ if (p == ms->p_end)+ luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");+ if (*(p++) == L_ESC && p < ms->p_end)+ p++; /* skip escapes (e.g. `%]') */+ } while (*p != ']');+ return p+1;+ }+ default: {+ return p;+ }+ }+}+++static int match_class (int c, int cl) {+ int res;+ switch (tolower(cl)) {+ case 'a' : res = isalpha(c); break;+ case 'c' : res = iscntrl(c); break;+ case 'd' : res = isdigit(c); break;+ case 'g' : res = isgraph(c); break;+ case 'l' : res = islower(c); break;+ case 'p' : res = ispunct(c); break;+ case 's' : res = isspace(c); break;+ case 'u' : res = isupper(c); break;+ case 'w' : res = isalnum(c); break;+ case 'x' : res = isxdigit(c); break;+ case 'z' : res = (c == 0); break; /* deprecated option */+ default: return (cl == c);+ }+ return (islower(cl) ? res : !res);+}+++static int matchbracketclass (int c, const char *p, const char *ec) {+ int sig = 1;+ if (*(p+1) == '^') {+ sig = 0;+ p++; /* skip the `^' */+ }+ while (++p < ec) {+ if (*p == L_ESC) {+ p++;+ if (match_class(c, uchar(*p)))+ return sig;+ }+ else if ((*(p+1) == '-') && (p+2 < ec)) {+ p+=2;+ if (uchar(*(p-2)) <= c && c <= uchar(*p))+ return sig;+ }+ else if (uchar(*p) == c) return sig;+ }+ return !sig;+}+++static int singlematch (MatchState *ms, const char *s, const char *p,+ const char *ep) {+ if (s >= ms->src_end)+ return 0;+ else {+ int c = uchar(*s);+ switch (*p) {+ case '.': return 1; /* matches any char */+ case L_ESC: return match_class(c, uchar(*(p+1)));+ case '[': return matchbracketclass(c, p, ep-1);+ default: return (uchar(*p) == c);+ }+ }+}+++static const char *matchbalance (MatchState *ms, const char *s,+ const char *p) {+ if (p >= ms->p_end - 1)+ luaL_error(ms->L, "malformed pattern "+ "(missing arguments to " LUA_QL("%%b") ")");+ if (*s != *p) return NULL;+ else {+ int b = *p;+ int e = *(p+1);+ int cont = 1;+ while (++s < ms->src_end) {+ if (*s == e) {+ if (--cont == 0) return s+1;+ }+ else if (*s == b) cont++;+ }+ }+ return NULL; /* string ends out of balance */+}+++static const char *max_expand (MatchState *ms, const char *s,+ const char *p, const char *ep) {+ ptrdiff_t i = 0; /* counts maximum expand for item */+ while (singlematch(ms, s + i, p, ep))+ i++;+ /* keeps trying to match with the maximum repetitions */+ while (i>=0) {+ const char *res = match(ms, (s+i), ep+1);+ if (res) return res;+ i--; /* else didn't match; reduce 1 repetition to try again */+ }+ return NULL;+}+++static const char *min_expand (MatchState *ms, const char *s,+ const char *p, const char *ep) {+ for (;;) {+ const char *res = match(ms, s, ep+1);+ if (res != NULL)+ return res;+ else if (singlematch(ms, s, p, ep))+ s++; /* try with one more repetition */+ else return NULL;+ }+}+++static const char *start_capture (MatchState *ms, const char *s,+ const char *p, int what) {+ const char *res;+ int level = ms->level;+ if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");+ ms->capture[level].init = s;+ ms->capture[level].len = what;+ ms->level = level+1;+ if ((res=match(ms, s, p)) == NULL) /* match failed? */+ ms->level--; /* undo capture */+ return res;+}+++static const char *end_capture (MatchState *ms, const char *s,+ const char *p) {+ int l = capture_to_close(ms);+ const char *res;+ ms->capture[l].len = s - ms->capture[l].init; /* close capture */+ if ((res = match(ms, s, p)) == NULL) /* match failed? */+ ms->capture[l].len = CAP_UNFINISHED; /* undo capture */+ return res;+}+++static const char *match_capture (MatchState *ms, const char *s, int l) {+ size_t len;+ l = check_capture(ms, l);+ len = ms->capture[l].len;+ if ((size_t)(ms->src_end-s) >= len &&+ memcmp(ms->capture[l].init, s, len) == 0)+ return s+len;+ else return NULL;+}+++static const char *match (MatchState *ms, const char *s, const char *p) {+ if (ms->matchdepth-- == 0)+ luaL_error(ms->L, "pattern too complex");+ init: /* using goto's to optimize tail recursion */+ if (p != ms->p_end) { /* end of pattern? */+ switch (*p) {+ case '(': { /* start capture */+ if (*(p + 1) == ')') /* position capture? */+ s = start_capture(ms, s, p + 2, CAP_POSITION);+ else+ s = start_capture(ms, s, p + 1, CAP_UNFINISHED);+ break;+ }+ case ')': { /* end capture */+ s = end_capture(ms, s, p + 1);+ break;+ }+ case '$': {+ if ((p + 1) != ms->p_end) /* is the `$' the last char in pattern? */+ goto dflt; /* no; go to default */+ s = (s == ms->src_end) ? s : NULL; /* check end of string */+ break;+ }+ case L_ESC: { /* escaped sequences not in the format class[*+?-]? */+ switch (*(p + 1)) {+ case 'b': { /* balanced string? */+ s = matchbalance(ms, s, p + 2);+ if (s != NULL) {+ p += 4; goto init; /* return match(ms, s, p + 4); */+ } /* else fail (s == NULL) */+ break;+ }+ case 'f': { /* frontier? */+ const char *ep; char previous;+ p += 2;+ if (*p != '[')+ luaL_error(ms->L, "missing " LUA_QL("[") " after "+ LUA_QL("%%f") " in pattern");+ ep = classend(ms, p); /* points to what is next */+ previous = (s == ms->src_init) ? '\0' : *(s - 1);+ if (!matchbracketclass(uchar(previous), p, ep - 1) &&+ matchbracketclass(uchar(*s), p, ep - 1)) {+ p = ep; goto init; /* return match(ms, s, ep); */+ }+ s = NULL; /* match failed */+ break;+ }+ case '0': case '1': case '2': case '3':+ case '4': case '5': case '6': case '7':+ case '8': case '9': { /* capture results (%0-%9)? */+ s = match_capture(ms, s, uchar(*(p + 1)));+ if (s != NULL) {+ p += 2; goto init; /* return match(ms, s, p + 2) */+ }+ break;+ }+ default: goto dflt;+ }+ break;+ }+ default: dflt: { /* pattern class plus optional suffix */+ const char *ep = classend(ms, p); /* points to optional suffix */+ /* does not match at least once? */+ if (!singlematch(ms, s, p, ep)) {+ if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */+ p = ep + 1; goto init; /* return match(ms, s, ep + 1); */+ }+ else /* '+' or no suffix */+ s = NULL; /* fail */+ }+ else { /* matched once */+ switch (*ep) { /* handle optional suffix */+ case '?': { /* optional */+ const char *res;+ if ((res = match(ms, s + 1, ep + 1)) != NULL)+ s = res;+ else {+ p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */+ }+ break;+ }+ case '+': /* 1 or more repetitions */+ s++; /* 1 match already done */+ /* go through */+ case '*': /* 0 or more repetitions */+ s = max_expand(ms, s, p, ep);+ break;+ case '-': /* 0 or more repetitions (minimum) */+ s = min_expand(ms, s, p, ep);+ break;+ default: /* no suffix */+ s++; p = ep; goto init; /* return match(ms, s + 1, ep); */+ }+ }+ break;+ }+ }+ }+ ms->matchdepth++;+ return s;+}++++static const char *lmemfind (const char *s1, size_t l1,+ const char *s2, size_t l2) {+ if (l2 == 0) return s1; /* empty strings are everywhere */+ else if (l2 > l1) return NULL; /* avoids a negative `l1' */+ else {+ const char *init; /* to search for a `*s2' inside `s1' */+ l2--; /* 1st char will be checked by `memchr' */+ l1 = l1-l2; /* `s2' cannot be found after that */+ while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {+ init++; /* 1st char is already checked */+ if (memcmp(init, s2+1, l2) == 0)+ return init-1;+ else { /* correct `l1' and `s1' to try again */+ l1 -= init-s1;+ s1 = init;+ }+ }+ return NULL; /* not found */+ }+}+++static void push_onecapture (MatchState *ms, int i, const char *s,+ const char *e) {+ if (i >= ms->level) {+ if (i == 0) /* ms->level == 0, too */+ lua_pushlstring(ms->L, s, e - s); /* add whole match */+ else+ luaL_error(ms->L, "invalid capture index");+ }+ else {+ ptrdiff_t l = ms->capture[i].len;+ if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");+ if (l == CAP_POSITION)+ lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);+ else+ lua_pushlstring(ms->L, ms->capture[i].init, l);+ }+}+++static int push_captures (MatchState *ms, const char *s, const char *e) {+ int i;+ int nlevels = (ms->level == 0 && s) ? 1 : ms->level;+ luaL_checkstack(ms->L, nlevels, "too many captures");+ for (i = 0; i < nlevels; i++)+ push_onecapture(ms, i, s, e);+ return nlevels; /* number of strings pushed */+}+++/* check whether pattern has no special characters */+static int nospecials (const char *p, size_t l) {+ size_t upto = 0;+ do {+ if (strpbrk(p + upto, SPECIALS))+ return 0; /* pattern has a special character */+ upto += strlen(p + upto) + 1; /* may have more after \0 */+ } while (upto <= l);+ return 1; /* no special chars found */+}+++static int str_find_aux (lua_State *L, int find) {+ size_t ls, lp;+ const char *s = luaL_checklstring(L, 1, &ls);+ const char *p = luaL_checklstring(L, 2, &lp);+ size_t init = posrelat(luaL_optinteger(L, 3, 1), ls);+ if (init < 1) init = 1;+ else if (init > ls + 1) { /* start after string's end? */+ lua_pushnil(L); /* cannot find anything */+ return 1;+ }+ /* explicit request or no special characters? */+ if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {+ /* do a plain search */+ const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);+ if (s2) {+ lua_pushinteger(L, s2 - s + 1);+ lua_pushinteger(L, s2 - s + lp);+ return 2;+ }+ }+ else {+ MatchState ms;+ const char *s1 = s + init - 1;+ int anchor = (*p == '^');+ if (anchor) {+ p++; lp--; /* skip anchor character */+ }+ ms.L = L;+ ms.matchdepth = MAXCCALLS;+ ms.src_init = s;+ ms.src_end = s + ls;+ ms.p_end = p + lp;+ do {+ const char *res;+ ms.level = 0;+ lua_assert(ms.matchdepth == MAXCCALLS);+ if ((res=match(&ms, s1, p)) != NULL) {+ if (find) {+ lua_pushinteger(L, s1 - s + 1); /* start */+ lua_pushinteger(L, res - s); /* end */+ return push_captures(&ms, NULL, 0) + 2;+ }+ else+ return push_captures(&ms, s1, res);+ }+ } while (s1++ < ms.src_end && !anchor);+ }+ lua_pushnil(L); /* not found */+ return 1;+}+++static int str_find (lua_State *L) {+ return str_find_aux(L, 1);+}+++static int str_match (lua_State *L) {+ return str_find_aux(L, 0);+}+++static int gmatch_aux (lua_State *L) {+ MatchState ms;+ size_t ls, lp;+ const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);+ const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp);+ const char *src;+ ms.L = L;+ ms.matchdepth = MAXCCALLS;+ ms.src_init = s;+ ms.src_end = s+ls;+ ms.p_end = p + lp;+ for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));+ src <= ms.src_end;+ src++) {+ const char *e;+ ms.level = 0;+ lua_assert(ms.matchdepth == MAXCCALLS);+ if ((e = match(&ms, src, p)) != NULL) {+ lua_Integer newstart = e-s;+ if (e == src) newstart++; /* empty match? go at least one position */+ lua_pushinteger(L, newstart);+ lua_replace(L, lua_upvalueindex(3));+ return push_captures(&ms, src, e);+ }+ }+ return 0; /* not found */+}+++static int gmatch (lua_State *L) {+ luaL_checkstring(L, 1);+ luaL_checkstring(L, 2);+ lua_settop(L, 2);+ lua_pushinteger(L, 0);+ lua_pushcclosure(L, gmatch_aux, 3);+ return 1;+}+++static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,+ const char *e) {+ size_t l, i;+ const char *news = lua_tolstring(ms->L, 3, &l);+ for (i = 0; i < l; i++) {+ if (news[i] != L_ESC)+ luaL_addchar(b, news[i]);+ else {+ i++; /* skip ESC */+ if (!isdigit(uchar(news[i]))) {+ if (news[i] != L_ESC)+ luaL_error(ms->L, "invalid use of " LUA_QL("%c")+ " in replacement string", L_ESC);+ luaL_addchar(b, news[i]);+ }+ else if (news[i] == '0')+ luaL_addlstring(b, s, e - s);+ else {+ push_onecapture(ms, news[i] - '1', s, e);+ luaL_addvalue(b); /* add capture to accumulated result */+ }+ }+ }+}+++static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,+ const char *e, int tr) {+ lua_State *L = ms->L;+ switch (tr) {+ case LUA_TFUNCTION: {+ int n;+ lua_pushvalue(L, 3);+ n = push_captures(ms, s, e);+ lua_call(L, n, 1);+ break;+ }+ case LUA_TTABLE: {+ push_onecapture(ms, 0, s, e);+ lua_gettable(L, 3);+ break;+ }+ default: { /* LUA_TNUMBER or LUA_TSTRING */+ add_s(ms, b, s, e);+ return;+ }+ }+ if (!lua_toboolean(L, -1)) { /* nil or false? */+ lua_pop(L, 1);+ lua_pushlstring(L, s, e - s); /* keep original text */+ }+ else if (!lua_isstring(L, -1))+ luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));+ luaL_addvalue(b); /* add result to accumulator */+}+++static int str_gsub (lua_State *L) {+ size_t srcl, lp;+ const char *src = luaL_checklstring(L, 1, &srcl);+ const char *p = luaL_checklstring(L, 2, &lp);+ int tr = lua_type(L, 3);+ size_t max_s = luaL_optinteger(L, 4, srcl+1);+ int anchor = (*p == '^');+ size_t n = 0;+ MatchState ms;+ luaL_Buffer b;+ luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||+ tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,+ "string/function/table expected");+ luaL_buffinit(L, &b);+ if (anchor) {+ p++; lp--; /* skip anchor character */+ }+ ms.L = L;+ ms.matchdepth = MAXCCALLS;+ ms.src_init = src;+ ms.src_end = src+srcl;+ ms.p_end = p + lp;+ while (n < max_s) {+ const char *e;+ ms.level = 0;+ lua_assert(ms.matchdepth == MAXCCALLS);+ e = match(&ms, src, p);+ if (e) {+ n++;+ add_value(&ms, &b, src, e, tr);+ }+ if (e && e>src) /* non empty match? */+ src = e; /* skip it */+ else if (src < ms.src_end)+ luaL_addchar(&b, *src++);+ else break;+ if (anchor) break;+ }+ luaL_addlstring(&b, src, ms.src_end-src);+ luaL_pushresult(&b);+ lua_pushinteger(L, n); /* number of substitutions */+ return 2;+}++/* }====================================================== */++++/*+** {======================================================+** STRING FORMAT+** =======================================================+*/++/*+** LUA_INTFRMLEN is the length modifier for integer conversions in+** 'string.format'; LUA_INTFRM_T is the integer type corresponding to+** the previous length+*/+#if !defined(LUA_INTFRMLEN) /* { */+#if defined(LUA_USE_LONGLONG)++#define LUA_INTFRMLEN "ll"+#define LUA_INTFRM_T long long++#else++#define LUA_INTFRMLEN "l"+#define LUA_INTFRM_T long++#endif+#endif /* } */+++/*+** LUA_FLTFRMLEN is the length modifier for float conversions in+** 'string.format'; LUA_FLTFRM_T is the float type corresponding to+** the previous length+*/+#if !defined(LUA_FLTFRMLEN)++#define LUA_FLTFRMLEN ""+#define LUA_FLTFRM_T double++#endif+++/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */+#define MAX_ITEM 512+/* valid flags in a format specification */+#define FLAGS "-+ #0"+/*+** maximum size of each format specification (such as '%-099.99d')+** (+10 accounts for %99.99x plus margin of error)+*/+#define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)+++static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {+ size_t l;+ const char *s = luaL_checklstring(L, arg, &l);+ luaL_addchar(b, '"');+ while (l--) {+ if (*s == '"' || *s == '\\' || *s == '\n') {+ luaL_addchar(b, '\\');+ luaL_addchar(b, *s);+ }+ else if (*s == '\0' || iscntrl(uchar(*s))) {+ char buff[10];+ if (!isdigit(uchar(*(s+1))))+ sprintf(buff, "\\%d", (int)uchar(*s));+ else+ sprintf(buff, "\\%03d", (int)uchar(*s));+ luaL_addstring(b, buff);+ }+ else+ luaL_addchar(b, *s);+ s++;+ }+ luaL_addchar(b, '"');+}++static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {+ const char *p = strfrmt;+ while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */+ if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))+ luaL_error(L, "invalid format (repeated flags)");+ if (isdigit(uchar(*p))) p++; /* skip width */+ if (isdigit(uchar(*p))) p++; /* (2 digits at most) */+ if (*p == '.') {+ p++;+ if (isdigit(uchar(*p))) p++; /* skip precision */+ if (isdigit(uchar(*p))) p++; /* (2 digits at most) */+ }+ if (isdigit(uchar(*p)))+ luaL_error(L, "invalid format (width or precision too long)");+ *(form++) = '%';+ memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char));+ form += p - strfrmt + 1;+ *form = '\0';+ return p;+}+++/*+** add length modifier into formats+*/+static void addlenmod (char *form, const char *lenmod) {+ size_t l = strlen(form);+ size_t lm = strlen(lenmod);+ char spec = form[l - 1];+ strcpy(form + l - 1, lenmod);+ form[l + lm - 1] = spec;+ form[l + lm] = '\0';+}+++static int str_format (lua_State *L) {+ int top = lua_gettop(L);+ int arg = 1;+ size_t sfl;+ const char *strfrmt = luaL_checklstring(L, arg, &sfl);+ const char *strfrmt_end = strfrmt+sfl;+ luaL_Buffer b;+ luaL_buffinit(L, &b);+ while (strfrmt < strfrmt_end) {+ if (*strfrmt != L_ESC)+ luaL_addchar(&b, *strfrmt++);+ else if (*++strfrmt == L_ESC)+ luaL_addchar(&b, *strfrmt++); /* %% */+ else { /* format item */+ char form[MAX_FORMAT]; /* to store the format (`%...') */+ char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */+ int nb = 0; /* number of bytes in added item */+ if (++arg > top)+ luaL_argerror(L, arg, "no value");+ strfrmt = scanformat(L, strfrmt, form);+ switch (*strfrmt++) {+ case 'c': {+ nb = sprintf(buff, form, luaL_checkint(L, arg));+ break;+ }+ case 'd': case 'i': {+ lua_Number n = luaL_checknumber(L, arg);+ LUA_INTFRM_T ni = (LUA_INTFRM_T)fix32_to_int(n);+ lua_Number diff = fix32_sub(n, fix32_from_int((int)(int16_t)ni));+ luaL_argcheck(L, fix32_lt(fix32_from_int(-1), diff) && fix32_lt(diff, fix32_from_int(1)), arg,+ "not a number in proper range");+ addlenmod(form, LUA_INTFRMLEN);+ nb = sprintf(buff, form, ni);+ break;+ }+ case 'o': case 'u': case 'x': case 'X': {+ lua_Number n = luaL_checknumber(L, arg);+ unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)(unsigned)fix32_to_int(n);+ lua_Number diff = fix32_sub(n, fix32_from_int((int)(uint16_t)ni));+ luaL_argcheck(L, fix32_lt(fix32_from_int(-1), diff) && fix32_lt(diff, fix32_from_int(1)), arg,+ "not a non-negative number in proper range");+ addlenmod(form, LUA_INTFRMLEN);+ nb = sprintf(buff, form, ni);+ break;+ }+ case 'e': case 'E': case 'f':+#if defined(LUA_USE_AFORMAT)+ case 'a': case 'A':+#endif+ case 'g': case 'G': {+ addlenmod(form, LUA_FLTFRMLEN);+ nb = sprintf(buff, form, (LUA_FLTFRM_T)fix32_to_double(luaL_checknumber(L, arg)));+ break;+ }+ case 'q': {+ addquoted(L, &b, arg);+ break;+ }+ case 's': {+ size_t l;+ const char *s = luaL_tolstring(L, arg, &l);+ if (!strchr(form, '.') && l >= 100) {+ /* no precision and string is too long to be formatted;+ keep original string */+ luaL_addvalue(&b);+ break;+ }+ else {+ nb = sprintf(buff, form, s);+ lua_pop(L, 1); /* remove result from 'luaL_tolstring' */+ break;+ }+ }+ default: { /* also treat cases `pnLlh' */+ return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "+ LUA_QL("format"), *(strfrmt - 1));+ }+ }+ luaL_addsize(&b, nb);+ }+ }+ luaL_pushresult(&b);+ return 1;+}++/* }====================================================== */+++static const luaL_Reg strlib[] = {+ {"byte", str_byte},+ {"char", str_char},+ {"find", str_find},+ {"format", str_format},+ {"gmatch", gmatch},+ {"gsub", str_gsub},+ {"len", str_len},+ {"lower", str_lower},+ {"match", str_match},+ {"rep", str_rep},+ {"reverse", str_reverse},+ {"sub", str_sub},+ {"upper", str_upper},+ {NULL, NULL}+};+++static void createmetatable (lua_State *L) {+ lua_createtable(L, 0, 1); /* table to be metatable for strings */+ lua_pushliteral(L, ""); /* dummy string */+ lua_pushvalue(L, -2); /* copy table */+ lua_setmetatable(L, -2); /* set table as metatable for strings */+ lua_pop(L, 1); /* pop dummy string */+ lua_pushvalue(L, -2); /* get string library */+ lua_pushcclosure(L, str_index, 1);+ lua_setfield(L, -2, "__index"); /* numeric indexing plus string methods */+ lua_pop(L, 1); /* pop metatable */+}+++/*+** Open string library+*/+LUAMOD_API int luaopen_string (lua_State *L) {+ luaL_newlib(L, strlib);+ createmetatable(L);+ return 1;+}+diff --git a/games/numpico/src/femto8/lua/ltable.c b/games/numpico/src/femto8/lua/ltable.cnew file mode 100644index 00000000..4532cc80--- /dev/null+++ b/games/numpico/src/femto8/lua/ltable.c@@ -0,0 +1,588 @@+/*+** $Id: ltable.c,v 2.72 2012/09/11 19:37:16 roberto Exp $+** Lua tables (hash)+** See Copyright Notice in lua.h+*/+++/*+** Implementation of tables (aka arrays, objects, or hash tables).+** Tables keep its elements in two parts: an array part and a hash part.+** Non-negative integer keys are all candidates to be kept in the array+** part. The actual size of the array is the largest `n' such that at+** least half the slots between 0 and n are in use.+** Hash uses a mix of chained scatter table with Brent's variation.+** A main invariant of these tables is that, if an element is not+** in its main position (i.e. the `original' position that its hash gives+** to it), then the colliding element is in its own main position.+** Hence even when the load factor reaches 100%, performance remains good.+*/++#include <string.h>++#define ltable_c+#define LUA_CORE++#include "lua.h"++#include "ldebug.h"+#include "ldo.h"+#include "lgc.h"+#include "lmem.h"+#include "lobject.h"+#include "lstate.h"+#include "lstring.h"+#include "ltable.h"+#include "lvm.h"+++/*+** max size of array part is 2^MAXBITS+*/+#if LUAI_BITSINT >= 32+#define MAXBITS 30+#else+#define MAXBITS (LUAI_BITSINT-2)+#endif++#define MAXASIZE (1 << MAXBITS)+++#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))++#define hashstr(t,str) hashpow2(t, (str)->tsv.hash)+#define hashboolean(t,p) hashpow2(t, p)+++/*+** for some types, it is better to avoid modulus by power of 2, as+** they tend to have many 2 factors.+*/+#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))+++#define hashpointer(t,p) hashmod(t, IntPoint(p))+++#define dummynode (&dummynode_)++#define isdummy(n) ((n) == dummynode)++static const Node dummynode_ = {+ {NILCONSTANT}, /* value */+ {{NILCONSTANT, NULL}} /* key */+};+++/*+** hash for lua_Numbers+*/+static Node *hashnum (const Table *t, lua_Number n) {+ int i;+ luai_hashnum(i, n);+ if (i < 0) {+ if (cast(unsigned int, i) == 0u - i) /* use unsigned to avoid overflows */+ i = 0; /* handle INT_MIN */+ i = -i; /* must be a positive value */+ }+ return hashmod(t, i);+}++++/*+** returns the `main' position of an element in a table (that is, the index+** of its hash value)+*/+static Node *mainposition (const Table *t, const TValue *key) {+ switch (ttype(key)) {+ case LUA_TNUMBER:+ return hashnum(t, nvalue(key));+ case LUA_TLNGSTR: {+ TString *s = rawtsvalue(key);+ if (s->tsv.extra == 0) { /* no hash? */+ s->tsv.hash = luaS_hash(getstr(s), s->tsv.len, s->tsv.hash);+ s->tsv.extra = 1; /* now it has its hash */+ }+ return hashstr(t, rawtsvalue(key));+ }+ case LUA_TSHRSTR:+ return hashstr(t, rawtsvalue(key));+ case LUA_TBOOLEAN:+ return hashboolean(t, bvalue(key));+ case LUA_TLIGHTUSERDATA:+ return hashpointer(t, pvalue(key));+ case LUA_TLCF:+ return hashpointer(t, fvalue(key));+ default:+ return hashpointer(t, gcvalue(key));+ }+}+++/*+** returns the index for `key' if `key' is an appropriate key to live in+** the array part of the table, -1 otherwise.+*/+static int arrayindex (const TValue *key) {+ if (ttisnumber(key)) {+ lua_Number n = nvalue(key);+ int k;+ lua_number2int(k, n);+ if (luai_numeq(cast_num(k), n))+ return k;+ }+ return -1; /* `key' did not match some condition */+}+++/*+** returns the index of a `key' for table traversals. First goes all+** elements in the array part, then elements in the hash part. The+** beginning of a traversal is signaled by -1.+*/+static int findindex (lua_State *L, Table *t, StkId key) {+ int i;+ if (ttisnil(key)) return -1; /* first iteration */+ i = arrayindex(key);+ if (0 < i && i <= t->sizearray) /* is `key' inside array part? */+ return i-1; /* yes; that's the index (corrected to C) */+ else {+ Node *n = mainposition(t, key);+ for (;;) { /* check whether `key' is somewhere in the chain */+ /* key may be dead already, but it is ok to use it in `next' */+ if (luaV_rawequalobj(gkey(n), key) ||+ (ttisdeadkey(gkey(n)) && iscollectable(key) &&+ deadvalue(gkey(n)) == gcvalue(key))) {+ i = cast_int(n - gnode(t, 0)); /* key index in hash table */+ /* hash elements are numbered after array ones */+ return i + t->sizearray;+ }+ else n = gnext(n);+ if (n == NULL)+ luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */+ }+ }+}+++int luaH_next (lua_State *L, Table *t, StkId key) {+ int i = findindex(L, t, key); /* find original element */+ for (i++; i < t->sizearray; i++) { /* try first array part */+ if (!ttisnil(&t->array[i])) { /* a non-nil value? */+ setnvalue(key, cast_num(i+1));+ setobj2s(L, key+1, &t->array[i]);+ return 1;+ }+ }+ for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */+ if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */+ setobj2s(L, key, gkey(gnode(t, i)));+ setobj2s(L, key+1, gval(gnode(t, i)));+ return 1;+ }+ }+ return 0; /* no more elements */+}+++/*+** {=============================================================+** Rehash+** ==============================================================+*/+++static int computesizes (int nums[], int *narray) {+ int i;+ int twotoi; /* 2^i */+ int a = 0; /* number of elements smaller than 2^i */+ int na = 0; /* number of elements to go to array part */+ int n = 0; /* optimal size for array part */+ for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) {+ if (nums[i] > 0) {+ a += nums[i];+ if (a > twotoi/2) { /* more than half elements present? */+ n = twotoi; /* optimal size (till now) */+ na = a; /* all elements smaller than n will go to array part */+ }+ }+ if (a == *narray) break; /* all elements already counted */+ }+ *narray = n;+ lua_assert(*narray/2 <= na && na <= *narray);+ return na;+}+++static int countint (const TValue *key, int *nums) {+ int k = arrayindex(key);+ if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */+ nums[luaO_ceillog2(k)]++; /* count as such */+ return 1;+ }+ else+ return 0;+}+++static int numusearray (const Table *t, int *nums) {+ int lg;+ int ttlg; /* 2^lg */+ int ause = 0; /* summation of `nums' */+ int i = 1; /* count to traverse all array keys */+ for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */+ int lc = 0; /* counter */+ int lim = ttlg;+ if (lim > t->sizearray) {+ lim = t->sizearray; /* adjust upper limit */+ if (i > lim)+ break; /* no more elements to count */+ }+ /* count elements in range (2^(lg-1), 2^lg] */+ for (; i <= lim; i++) {+ if (!ttisnil(&t->array[i-1]))+ lc++;+ }+ nums[lg] += lc;+ ause += lc;+ }+ return ause;+}+++static int numusehash (const Table *t, int *nums, int *pnasize) {+ int totaluse = 0; /* total number of elements */+ int ause = 0; /* summation of `nums' */+ int i = sizenode(t);+ while (i--) {+ Node *n = &t->node[i];+ if (!ttisnil(gval(n))) {+ ause += countint(gkey(n), nums);+ totaluse++;+ }+ }+ *pnasize += ause;+ return totaluse;+}+++static void setarrayvector (lua_State *L, Table *t, int size) {+ int i;+ luaM_reallocvector(L, t->array, t->sizearray, size, TValue);+ for (i=t->sizearray; i<size; i++)+ setnilvalue(&t->array[i]);+ t->sizearray = size;+}+++static void setnodevector (lua_State *L, Table *t, int size) {+ int lsize;+ if (size == 0) { /* no elements to hash part? */+ t->node = cast(Node *, dummynode); /* use common `dummynode' */+ lsize = 0;+ }+ else {+ int i;+ lsize = luaO_ceillog2(size);+ if (lsize > MAXBITS)+ luaG_runerror(L, "table overflow");+ size = twoto(lsize);+ t->node = luaM_newvector(L, size, Node);+ for (i=0; i<size; i++) {+ Node *n = gnode(t, i);+ gnext(n) = NULL;+ setnilvalue(gkey(n));+ setnilvalue(gval(n));+ }+ }+ t->lsizenode = cast_byte(lsize);+ t->lastfree = gnode(t, size); /* all positions are free */+}+++void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize) {+ int i;+ int oldasize = t->sizearray;+ int oldhsize = t->lsizenode;+ Node *nold = t->node; /* save old hash ... */+ if (nasize > oldasize) /* array part must grow? */+ setarrayvector(L, t, nasize);+ /* create new hash part with appropriate size */+ setnodevector(L, t, nhsize);+ if (nasize < oldasize) { /* array part must shrink? */+ t->sizearray = nasize;+ /* re-insert elements from vanishing slice */+ for (i=nasize; i<oldasize; i++) {+ if (!ttisnil(&t->array[i]))+ luaH_setint(L, t, i + 1, &t->array[i]);+ }+ /* shrink array */+ luaM_reallocvector(L, t->array, oldasize, nasize, TValue);+ }+ /* re-insert elements from hash part */+ for (i = twoto(oldhsize) - 1; i >= 0; i--) {+ Node *old = nold+i;+ if (!ttisnil(gval(old))) {+ /* doesn't need barrier/invalidate cache, as entry was+ already present in the table */+ setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old));+ }+ }+ if (!isdummy(nold))+ luaM_freearray(L, nold, cast(size_t, twoto(oldhsize))); /* free old array */+}+++void luaH_resizearray (lua_State *L, Table *t, int nasize) {+ int nsize = isdummy(t->node) ? 0 : sizenode(t);+ luaH_resize(L, t, nasize, nsize);+}+++static void rehash (lua_State *L, Table *t, const TValue *ek) {+ int nasize, na;+ int nums[MAXBITS+1]; /* nums[i] = number of keys with 2^(i-1) < k <= 2^i */+ int i;+ int totaluse;+ for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */+ nasize = numusearray(t, nums); /* count keys in array part */+ totaluse = nasize; /* all those keys are integer keys */+ totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */+ /* count extra key */+ nasize += countint(ek, nums);+ totaluse++;+ /* compute new size for array part */+ na = computesizes(nums, &nasize);+ /* resize the table to new computed sizes */+ luaH_resize(L, t, nasize, totaluse - na);+}++++/*+** }=============================================================+*/+++Table *luaH_new (lua_State *L) {+ Table *t = &luaC_newobj(L, LUA_TTABLE, sizeof(Table), NULL, 0)->h;+ t->metatable = NULL;+ t->flags = cast_byte(~0);+ t->array = NULL;+ t->sizearray = 0;+ setnodevector(L, t, 0);+ return t;+}+++void luaH_free (lua_State *L, Table *t) {+ if (!isdummy(t->node))+ luaM_freearray(L, t->node, cast(size_t, sizenode(t)));+ luaM_freearray(L, t->array, t->sizearray);+ luaM_free(L, t);+}+++static Node *getfreepos (Table *t) {+ while (t->lastfree > t->node) {+ t->lastfree--;+ if (ttisnil(gkey(t->lastfree)))+ return t->lastfree;+ }+ return NULL; /* could not find a free place */+}++++/*+** inserts a new key into a hash table; first, check whether key's main+** position is free. If not, check whether colliding node is in its main+** position or not: if it is not, move colliding node to an empty place and+** put new key in its main position; otherwise (colliding node is in its main+** position), new key goes to an empty position.+*/+TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {+ Node *mp;+ if (ttisnil(key)) luaG_runerror(L, "table index is nil");+ else if (ttisnumber(key) && luai_numisnan(L, nvalue(key)))+ luaG_runerror(L, "table index is NaN");+ mp = mainposition(t, key);+ if (!ttisnil(gval(mp)) || isdummy(mp)) { /* main position is taken? */+ Node *othern;+ Node *n = getfreepos(t); /* get a free place */+ if (n == NULL) { /* cannot find a free place? */+ rehash(L, t, key); /* grow table */+ /* whatever called 'newkey' take care of TM cache and GC barrier */+ return luaH_set(L, t, key); /* insert key into grown table */+ }+ lua_assert(!isdummy(n));+ othern = mainposition(t, gkey(mp));+ if (othern != mp) { /* is colliding node out of its main position? */+ /* yes; move colliding node into free position */+ while (gnext(othern) != mp) othern = gnext(othern); /* find previous */+ gnext(othern) = n; /* redo the chain with `n' in place of `mp' */+ *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */+ gnext(mp) = NULL; /* now `mp' is free */+ setnilvalue(gval(mp));+ }+ else { /* colliding node is in its own main position */+ /* new node will go into free position */+ gnext(n) = gnext(mp); /* chain new position */+ gnext(mp) = n;+ mp = n;+ }+ }+ setobj2t(L, gkey(mp), key);+ luaC_barrierback(L, obj2gco(t), key);+ lua_assert(ttisnil(gval(mp)));+ return gval(mp);+}+++/*+** search function for integers+*/+const TValue *luaH_getint (Table *t, int key) {+ /* (1 <= key && key <= t->sizearray) */+ if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))+ return &t->array[key-1];+ else {+ lua_Number nk = cast_num(key);+ Node *n = hashnum(t, nk);+ do { /* check whether `key' is somewhere in the chain */+ if (ttisnumber(gkey(n)) && luai_numeq((lua_Number)nvalue(gkey(n)), nk))+ return gval(n); /* that's it */+ else n = gnext(n);+ } while (n);+ return luaO_nilobject;+ }+}+++/*+** search function for short strings+*/+const TValue *luaH_getstr (Table *t, TString *key) {+ Node *n = hashstr(t, key);+ lua_assert(key->tsv.tt == LUA_TSHRSTR);+ do { /* check whether `key' is somewhere in the chain */+ if (ttisshrstring(gkey(n)) && eqshrstr(rawtsvalue(gkey(n)), key))+ return gval(n); /* that's it */+ else n = gnext(n);+ } while (n);+ return luaO_nilobject;+}+++/*+** main search function+*/+const TValue *luaH_get (Table *t, const TValue *key) {+ switch (ttype(key)) {+ case LUA_TSHRSTR: return luaH_getstr(t, rawtsvalue(key));+ case LUA_TNIL: return luaO_nilobject;+ case LUA_TNUMBER: {+ int k;+ lua_Number n = nvalue(key);+ lua_number2int(k, n);+ if (luai_numeq(cast_num(k), n)) /* index is int? */+ return luaH_getint(t, k); /* use specialized version */+ /* else go through */+ }+ default: {+ Node *n = mainposition(t, key);+ do { /* check whether `key' is somewhere in the chain */+ if (luaV_rawequalobj(gkey(n), key))+ return gval(n); /* that's it */+ else n = gnext(n);+ } while (n);+ return luaO_nilobject;+ }+ }+}+++/*+** beware: when using this function you probably need to check a GC+** barrier and invalidate the TM cache.+*/+TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {+ const TValue *p = luaH_get(t, key);+ if (p != luaO_nilobject)+ return cast(TValue *, p);+ else return luaH_newkey(L, t, key);+}+++void luaH_setint (lua_State *L, Table *t, int key, TValue *value) {+ const TValue *p = luaH_getint(t, key);+ TValue *cell;+ if (p != luaO_nilobject)+ cell = cast(TValue *, p);+ else {+ TValue k;+ setnvalue(&k, cast_num(key));+ cell = luaH_newkey(L, t, &k);+ }+ setobj2t(L, cell, value);+}+++static int unbound_search (Table *t, unsigned int j) {+ unsigned int i = j; /* i is zero or a present index */+ j++;+ /* find `i' and `j' such that i is present and j is not */+ while (!ttisnil(luaH_getint(t, j))) {+ i = j;+ j *= 2;+ if (j > cast(unsigned int, MAX_INT)) { /* overflow? */+ /* table was built with bad purposes: resort to linear search */+ i = 1;+ while (!ttisnil(luaH_getint(t, i))) i++;+ return i - 1;+ }+ }+ /* now do a binary search between them */+ while (j - i > 1) {+ unsigned int m = (i+j)/2;+ if (ttisnil(luaH_getint(t, m))) j = m;+ else i = m;+ }+ return i;+}+++/*+** Try to find a boundary in table `t'. A `boundary' is an integer index+** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).+*/+int luaH_getn (Table *t) {+ unsigned int j = t->sizearray;+ if (j > 0 && ttisnil(&t->array[j - 1])) {+ /* there is a boundary in the array part: (binary) search for it */+ unsigned int i = 0;+ while (j - i > 1) {+ unsigned int m = (i+j)/2;+ if (ttisnil(&t->array[m - 1])) j = m;+ else i = m;+ }+ return i;+ }+ /* else must find a boundary in hash part */+ else if (isdummy(t->node)) /* hash part is empty? */+ return j; /* that is easy... */+ else return unbound_search(t, j);+}++++#if defined(LUA_DEBUG)++Node *luaH_mainposition (const Table *t, const TValue *key) {+ return mainposition(t, key);+}++int luaH_isdummy (Node *n) { return isdummy(n); }++#endifdiff --git a/games/numpico/src/femto8/lua/ltable.h b/games/numpico/src/femto8/lua/ltable.hnew file mode 100644index 00000000..b28b6e62--- /dev/null+++ b/games/numpico/src/femto8/lua/ltable.h@@ -0,0 +1,45 @@+/*+** $Id: ltable.h,v 2.16.1.1 2013/04/12 18:48:47 roberto Exp roberto $+** Lua tables (hash)+** See Copyright Notice in lua.h+*/++#ifndef ltable_h+#define ltable_h++#include "lobject.h"+++#define gnode(t,i) (&(t)->node[i])+#define gkey(n) (&(n)->i_key.tvk)+#define gval(n) (&(n)->i_val)+#define gnext(n) ((n)->i_key.nk.next)++#define invalidateTMcache(t) ((t)->flags = 0)++/* returns the key, given the value of a table entry */+#define keyfromval(v) \+ (gkey(cast(Node *, cast(char *, (v)) - offsetof(Node, i_val))))+++LUAI_FUNC const TValue *luaH_getint (Table *t, int key);+LUAI_FUNC void luaH_setint (lua_State *L, Table *t, int key, TValue *value);+LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key);+LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key);+LUAI_FUNC TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key);+LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key);+LUAI_FUNC Table *luaH_new (lua_State *L);+LUAI_FUNC void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize);+LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, int nasize);+LUAI_FUNC void luaH_free (lua_State *L, Table *t);+LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key);+LUAI_FUNC int luaH_getn (Table *t);+++#if defined(LUA_DEBUG)+LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key);+LUAI_FUNC int luaH_isdummy (Node *n);+#endif+++#endifdiff --git a/games/numpico/src/femto8/lua/ltablib.c b/games/numpico/src/femto8/lua/ltablib.cnew file mode 100644index 00000000..56abfe1c--- /dev/null+++ b/games/numpico/src/femto8/lua/ltablib.c@@ -0,0 +1,285 @@+/*+** $Id: ltablib.c,v 1.65.1.1 2013/04/12 18:48:47 roberto Exp roberto $+** Library for Table Manipulation+** See Copyright Notice in lua.h+*/+++#include <limits.h>+#include <stddef.h>++#define ltablib_c+#define LUA_LIB++#include "lua.h"++#include "lauxlib.h"+#include "lualib.h"+++#define aux_getn(L,n) (luaL_checktype(L, n, LUA_TTABLE), luaL_len(L, n))++++#if defined(LUA_COMPAT_MAXN)+static int maxn (lua_State *L) {+ lua_Number max = 0;+ luaL_checktype(L, 1, LUA_TTABLE);+ lua_pushnil(L); /* first key */+ while (lua_next(L, 1)) {+ lua_pop(L, 1); /* remove value */+ if (lua_type(L, -1) == LUA_TNUMBER) {+ lua_Number v = lua_tonumber(L, -1);+ if (v > max) max = v;+ }+ }+ lua_pushnumber(L, max);+ return 1;+}+#endif+++static int tinsert (lua_State *L) {+ int e = aux_getn(L, 1) + 1; /* first empty element */+ int pos; /* where to insert new element */+ switch (lua_gettop(L)) {+ case 2: { /* called with only 2 arguments */+ pos = e; /* insert new element at the end */+ break;+ }+ case 3: {+ int i;+ pos = luaL_checkint(L, 2); /* 2nd argument is the position */+ luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds");+ for (i = e; i > pos; i--) { /* move up elements */+ lua_rawgeti(L, 1, i-1);+ lua_rawseti(L, 1, i); /* t[i] = t[i-1] */+ }+ break;+ }+ default: {+ return luaL_error(L, "wrong number of arguments to " LUA_QL("insert"));+ }+ }+ lua_rawseti(L, 1, pos); /* t[pos] = v */+ return 0;+}+++static int tremove (lua_State *L) {+ int size = aux_getn(L, 1);+ int pos = luaL_optint(L, 2, size);+ if (pos != size) /* validate 'pos' if given */+ luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds");+ lua_rawgeti(L, 1, pos); /* result = t[pos] */+ for ( ; pos < size; pos++) {+ lua_rawgeti(L, 1, pos+1);+ lua_rawseti(L, 1, pos); /* t[pos] = t[pos+1] */+ }+ lua_pushnil(L);+ lua_rawseti(L, 1, pos); /* t[pos] = nil */+ return 1;+}+++static void addfield (lua_State *L, luaL_Buffer *b, int i) {+ lua_rawgeti(L, 1, i);+ if (!lua_isstring(L, -1))+ luaL_error(L, "invalid value (%s) at index %d in table for "+ LUA_QL("concat"), luaL_typename(L, -1), i);+ luaL_addvalue(b);+}+++static int tconcat (lua_State *L) {+ luaL_Buffer b;+ size_t lsep;+ int i, last;+ const char *sep = luaL_optlstring(L, 2, "", &lsep);+ luaL_checktype(L, 1, LUA_TTABLE);+ i = luaL_optint(L, 3, 1);+ last = luaL_opt(L, luaL_checkint, 4, luaL_len(L, 1));+ luaL_buffinit(L, &b);+ for (; i < last; i++) {+ addfield(L, &b, i);+ luaL_addlstring(&b, sep, lsep);+ }+ if (i == last) /* add last value (if interval was not empty) */+ addfield(L, &b, i);+ luaL_pushresult(&b);+ return 1;+}+++/*+** {======================================================+** Pack/unpack+** =======================================================+*/++static int pack (lua_State *L) {+ int n = lua_gettop(L); /* number of elements to pack */+ lua_createtable(L, n, 1); /* create result table */+ lua_pushinteger(L, n);+ lua_setfield(L, -2, "n"); /* t.n = number of elements */+ if (n > 0) { /* at least one element? */+ int i;+ lua_pushvalue(L, 1);+ lua_rawseti(L, -2, 1); /* insert first element */+ lua_replace(L, 1); /* move table into index 1 */+ for (i = n; i >= 2; i--) /* assign other elements */+ lua_rawseti(L, 1, i);+ }+ return 1; /* return table */+}+++static int unpack (lua_State *L) {+ int i, e;+ unsigned int n;+ luaL_checktype(L, 1, LUA_TTABLE);+ i = luaL_optint(L, 2, 1);+ e = luaL_opt(L, luaL_checkint, 3, luaL_len(L, 1));+ if (i > e) return 0; /* empty range */+ n = (unsigned int)e - (unsigned int)i; /* number of elements minus 1 */+ if (n > (INT_MAX - 10) || !lua_checkstack(L, ++n))+ return luaL_error(L, "too many results to unpack");+ lua_rawgeti(L, 1, i); /* push arg[i] (avoiding overflow problems) */+ while (i++ < e) /* push arg[i + 1...e] */+ lua_rawgeti(L, 1, i);+ return n;+}++/* }====================================================== */++++/*+** {======================================================+** Quicksort+** (based on `Algorithms in MODULA-3', Robert Sedgewick;+** Addison-Wesley, 1993.)+** =======================================================+*/+++static void set2 (lua_State *L, int i, int j) {+ lua_rawseti(L, 1, i);+ lua_rawseti(L, 1, j);+}++static int sort_comp (lua_State *L, int a, int b) {+ if (!lua_isnil(L, 2)) { /* function? */+ int res;+ lua_pushvalue(L, 2);+ lua_pushvalue(L, a-1); /* -1 to compensate function */+ lua_pushvalue(L, b-2); /* -2 to compensate function and `a' */+ lua_call(L, 2, 1);+ res = lua_toboolean(L, -1);+ lua_pop(L, 1);+ return res;+ }+ else /* a < b? */+ return lua_compare(L, a, b, LUA_OPLT);+}++static void auxsort (lua_State *L, int l, int u) {+ while (l < u) { /* for tail recursion */+ int i, j;+ /* sort elements a[l], a[(l+u)/2] and a[u] */+ lua_rawgeti(L, 1, l);+ lua_rawgeti(L, 1, u);+ if (sort_comp(L, -1, -2)) /* a[u] < a[l]? */+ set2(L, l, u); /* swap a[l] - a[u] */+ else+ lua_pop(L, 2);+ if (u-l == 1) break; /* only 2 elements */+ i = (l+u)/2;+ lua_rawgeti(L, 1, i);+ lua_rawgeti(L, 1, l);+ if (sort_comp(L, -2, -1)) /* a[i]<a[l]? */+ set2(L, i, l);+ else {+ lua_pop(L, 1); /* remove a[l] */+ lua_rawgeti(L, 1, u);+ if (sort_comp(L, -1, -2)) /* a[u]<a[i]? */+ set2(L, i, u);+ else+ lua_pop(L, 2);+ }+ if (u-l == 2) break; /* only 3 elements */+ lua_rawgeti(L, 1, i); /* Pivot */+ lua_pushvalue(L, -1);+ lua_rawgeti(L, 1, u-1);+ set2(L, i, u-1);+ /* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */+ i = l; j = u-1;+ for (;;) { /* invariant: a[l..i] <= P <= a[j..u] */+ /* repeat ++i until a[i] >= P */+ while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) {+ if (i>=u) luaL_error(L, "invalid order function for sorting");+ lua_pop(L, 1); /* remove a[i] */+ }+ /* repeat --j until a[j] <= P */+ while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) {+ if (j<=l) luaL_error(L, "invalid order function for sorting");+ lua_pop(L, 1); /* remove a[j] */+ }+ if (j<i) {+ lua_pop(L, 3); /* pop pivot, a[i], a[j] */+ break;+ }+ set2(L, i, j);+ }+ lua_rawgeti(L, 1, u-1);+ lua_rawgeti(L, 1, i);+ set2(L, u-1, i); /* swap pivot (a[u-1]) with a[i] */+ /* a[l..i-1] <= a[i] == P <= a[i+1..u] */+ /* adjust so that smaller half is in [j..i] and larger one in [l..u] */+ if (i-l < u-i) {+ j=l; i=i-1; l=i+2;+ }+ else {+ j=i+1; i=u; u=j-2;+ }+ auxsort(L, j, i); /* call recursively the smaller one */+ } /* repeat the routine for the larger one */+}++static int sort (lua_State *L) {+ int n = aux_getn(L, 1);+ luaL_checkstack(L, 40, ""); /* assume array is smaller than 2^40 */+ if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */+ luaL_checktype(L, 2, LUA_TFUNCTION);+ lua_settop(L, 2); /* make sure there is two arguments */+ auxsort(L, 1, n);+ return 0;+}++/* }====================================================== */+++static const luaL_Reg tab_funcs[] = {+ {"concat", tconcat},+#if defined(LUA_COMPAT_MAXN)+ {"maxn", maxn},+#endif+ {"insert", tinsert},+ {"pack", pack},+ {"unpack", unpack},+ {"remove", tremove},+ {"sort", sort},+ {NULL, NULL}+};+++LUAMOD_API int luaopen_table (lua_State *L) {+ luaL_newlib(L, tab_funcs);+#if defined(LUA_COMPAT_UNPACK)+ /* _G.unpack = table.unpack */+ lua_getfield(L, -1, "unpack");+ lua_setglobal(L, "unpack");+#endif+ return 1;+}+diff --git a/games/numpico/src/femto8/lua/ltm.c b/games/numpico/src/femto8/lua/ltm.cnew file mode 100644index 00000000..620f4f81--- /dev/null+++ b/games/numpico/src/femto8/lua/ltm.c@@ -0,0 +1,79 @@+/*+** $Id: ltm.c,v 2.14 2011/06/02 19:31:40 roberto Exp $+** Tag methods+** See Copyright Notice in lua.h+*/+++#include <string.h>++#define ltm_c+#define LUA_CORE++#include "lua.h"++#include "lobject.h"+#include "lstate.h"+#include "lstring.h"+#include "ltable.h"+#include "ltm.h"+++static const char udatatypename[] = "userdata";++LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTAGS] = {+ "no value",+ "nil", "boolean", udatatypename, "number",+ "string", "table", "function", udatatypename, "thread",+ "proto", "upval" /* these last two cases are used for tests only */+};+++void luaT_init (lua_State *L) {+ static const char *const luaT_eventname[] = { /* ORDER TM */+ "__index", "__newindex",+ "__gc", "__mode", "__len", "__eq",+ "__add", "__sub", "__mul", "__div", "__mod",+ "__pow", "_idiv", "__and", "__or", "__xor",+ "__shl", "__shr", "__lshr", "__rotl", "rotr",+ "__unm", "__not", "__peek", "__peek2", "__peek4",+ "__lt", "__le", "__concat", "__call"+ };+ int i;+ for (i=0; i<TM_N; i++) {+ G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]);+ luaS_fix(G(L)->tmname[i]); /* never collect these names */+ }+}+++/*+** function to be used with macro "fasttm": optimized for absence of+** tag methods+*/+const TValue *luaT_gettm (Table *events, TMS event, TString *ename) {+ const TValue *tm = luaH_getstr(events, ename);+ lua_assert(event <= TM_EQ);+ if (ttisnil(tm)) { /* no tag method? */+ events->flags |= cast_byte(1u<<event); /* cache this fact */+ return NULL;+ }+ else return tm;+}+++const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) {+ Table *mt;+ switch (ttypenv(o)) {+ case LUA_TTABLE:+ mt = hvalue(o)->metatable;+ break;+ case LUA_TUSERDATA:+ mt = uvalue(o)->metatable;+ break;+ default:+ mt = G(L)->mt[ttypenv(o)];+ }+ return (mt ? luaH_getstr(mt, G(L)->tmname[event]) : luaO_nilobject);+}+diff --git a/games/numpico/src/femto8/lua/ltm.h b/games/numpico/src/femto8/lua/ltm.hnew file mode 100644index 00000000..3c772bcf--- /dev/null+++ b/games/numpico/src/femto8/lua/ltm.h@@ -0,0 +1,70 @@+/*+** $Id: ltm.h,v 2.11 2011/02/28 17:32:10 roberto Exp $+** Tag methods+** See Copyright Notice in lua.h+*/++#ifndef ltm_h+#define ltm_h+++#include "lobject.h"+++/*+* WARNING: if you change the order of this enumeration,+* grep "ORDER TM"+*/+typedef enum {+ TM_INDEX,+ TM_NEWINDEX,+ TM_GC,+ TM_MODE,+ TM_LEN,+ TM_EQ, /* last tag method with `fast' access */+ TM_ADD,+ TM_SUB,+ TM_MUL,+ TM_DIV,+ TM_MOD,+ TM_POW,+ TM_IDIV,+ TM_BAND,+ TM_BOR,+ TM_BXOR,+ TM_SHL,+ TM_SHR,+ TM_LSHR,+ TM_ROTL,+ TM_ROTR,+ TM_UNM,+ TM_BNOT,+ TM_PEEK,+ TM_PEEK2,+ TM_PEEK4,+ TM_LT,+ TM_LE,+ TM_CONCAT,+ TM_CALL,+ TM_N /* number of elements in the enum */+} TMS;++++#define gfasttm(g,et,e) ((et) == NULL ? NULL : \+ ((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e]))++#define fasttm(l,et,e) gfasttm(G(l), et, e)++#define ttypename(x) luaT_typenames_[(x) + 1]+#define objtypename(x) ttypename(ttypenv(x))++LUAI_DDEC const char *const luaT_typenames_[LUA_TOTALTAGS];+++LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename);+LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o,+ TMS event);+LUAI_FUNC void luaT_init (lua_State *L);++#endifdiff --git a/games/numpico/src/femto8/lua/lua.h b/games/numpico/src/femto8/lua/lua.hnew file mode 100644index 00000000..25fd9974--- /dev/null+++ b/games/numpico/src/femto8/lua/lua.h@@ -0,0 +1,459 @@+/*+** $Id: lua.h,v 1.285.1.3 2014/05/07 14:15:55 roberto Exp roberto $+** Lua - A Scripting Language+** Lua.org, PUC-Rio, Brazil (http://www.lua.org)+** See Copyright Notice at the end of this file+*/+++#ifndef lua_h+#define lua_h++#include <stdarg.h>+#include <stddef.h>+++#include "luaconf.h"+++#define LUA_VERSION_MAJOR "5"+#define LUA_VERSION_MINOR "2"+#define LUA_VERSION_NUM 502+#define LUA_VERSION_RELEASE "4"++#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR+#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE+#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2015 Lua.org, PUC-Rio"+#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"+++/* mark for precompiled code ('<esc>Lua') */+#define LUA_SIGNATURE "\033Lua"++/* option for multiple returns in 'lua_pcall' and 'lua_call' */+#define LUA_MULTRET (-1)+++/*+** pseudo-indices+*/+#define LUA_REGISTRYINDEX LUAI_FIRSTPSEUDOIDX+#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i))+++/* thread status */+#define LUA_OK 0+#define LUA_YIELD 1+#define LUA_ERRRUN 2+#define LUA_ERRSYNTAX 3+#define LUA_ERRMEM 4+#define LUA_ERRGCMM 5+#define LUA_ERRERR 6+++typedef struct lua_State lua_State;++typedef int (*lua_CFunction) (lua_State *L);+++/*+** functions that read/write blocks when loading/dumping Lua chunks+*/+typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz);++typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud);+++/*+** prototype for memory-allocation functions+*/+typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);+++/*+** basic types+*/+#define LUA_TNONE (-1)++#define LUA_TNIL 0+#define LUA_TBOOLEAN 1+#define LUA_TLIGHTUSERDATA 2+#define LUA_TNUMBER 3+#define LUA_TSTRING 4+#define LUA_TTABLE 5+#define LUA_TFUNCTION 6+#define LUA_TUSERDATA 7+#define LUA_TTHREAD 8++#define LUA_NUMTAGS 9++++/* minimum Lua stack available to a C function */+#define LUA_MINSTACK 20+++/* predefined values in the registry */+#define LUA_RIDX_MAINTHREAD 1+#define LUA_RIDX_GLOBALS 2+#define LUA_RIDX_LAST LUA_RIDX_GLOBALS+++/* type of numbers in Lua */+typedef LUA_NUMBER lua_Number;+++/* type for integer functions */+typedef LUA_INTEGER lua_Integer;++/* unsigned integer type */+typedef LUA_UNSIGNED lua_Unsigned;++++/*+** generic extra include file+*/+#if defined(LUA_USER_H)+#include LUA_USER_H+#endif+++/*+** RCS ident string+*/+extern const char lua_ident[];+++/*+** state manipulation+*/+LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud);+LUA_API void (lua_close) (lua_State *L);+LUA_API lua_State *(lua_newthread) (lua_State *L);++LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf);+++LUA_API const lua_Number *(lua_version) (lua_State *L);+++/*+** basic stack manipulation+*/+LUA_API int (lua_absindex) (lua_State *L, int idx);+LUA_API int (lua_gettop) (lua_State *L);+LUA_API void (lua_settop) (lua_State *L, int idx);+LUA_API void (lua_pushvalue) (lua_State *L, int idx);+LUA_API void (lua_remove) (lua_State *L, int idx);+LUA_API void (lua_insert) (lua_State *L, int idx);+LUA_API void (lua_replace) (lua_State *L, int idx);+LUA_API void (lua_copy) (lua_State *L, int fromidx, int toidx);+LUA_API int (lua_checkstack) (lua_State *L, int sz);++LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n);+++/*+** access functions (stack -> C)+*/++LUA_API int (lua_isnumber) (lua_State *L, int idx);+LUA_API int (lua_isstring) (lua_State *L, int idx);+LUA_API int (lua_iscfunction) (lua_State *L, int idx);+LUA_API int (lua_isuserdata) (lua_State *L, int idx);+LUA_API int (lua_type) (lua_State *L, int idx);+LUA_API const char *(lua_typename) (lua_State *L, int tp);++LUA_API lua_Number (lua_tonumberx) (lua_State *L, int idx, int *isnum);+LUA_API lua_Integer (lua_tointegerx) (lua_State *L, int idx, int *isnum);+LUA_API lua_Unsigned (lua_tounsignedx) (lua_State *L, int idx, int *isnum);+LUA_API int (lua_toboolean) (lua_State *L, int idx);+LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len);+LUA_API size_t (lua_rawlen) (lua_State *L, int idx);+LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx);+LUA_API void *(lua_touserdata) (lua_State *L, int idx);+LUA_API lua_State *(lua_tothread) (lua_State *L, int idx);+LUA_API const void *(lua_topointer) (lua_State *L, int idx);+++/*+** Comparison and arithmetic functions+*/++#define LUA_OPADD 0 /* ORDER TM */+#define LUA_OPSUB 1+#define LUA_OPMUL 2+#define LUA_OPDIV 3+#define LUA_OPMOD 4+#define LUA_OPPOW 5+#define LUA_OPIDIV 6+#define LUA_OPBAND 7+#define LUA_OPBOR 8+#define LUA_OPBXOR 9+#define LUA_OPSHL 10+#define LUA_OPSHR 11+#define LUA_OPLSHR 12+#define LUA_OPROTL 13+#define LUA_OPROTR 14+#define LUA_OPUNM 15+#define LUA_OPBNOT 16+#define LUA_OPPEEK 17+#define LUA_OPPEEK2 18+#define LUA_OPPEEK4 19++LUA_API void (lua_arith) (lua_State *L, int op);++#define LUA_OPEQ 0+#define LUA_OPLT 1+#define LUA_OPLE 2++LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2);+LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op);+++/*+** push functions (C -> stack)+*/+LUA_API void (lua_pushnil) (lua_State *L);+LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n);+LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n);+LUA_API void (lua_pushunsigned) (lua_State *L, lua_Unsigned n);+LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t l);+LUA_API const char *(lua_pushstring) (lua_State *L, const char *s);+LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt,+ va_list argp);+LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...);+LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n);+LUA_API void (lua_pushboolean) (lua_State *L, int b);+LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p);+LUA_API int (lua_pushthread) (lua_State *L);+++/*+** get functions (Lua -> stack)+*/+LUA_API void (lua_getglobal) (lua_State *L, const char *var);+LUA_API void (lua_gettable) (lua_State *L, int idx);+LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k);+LUA_API void (lua_rawget) (lua_State *L, int idx);+LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n);+LUA_API void (lua_rawgetp) (lua_State *L, int idx, const void *p);+LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec);+LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz);+LUA_API int (lua_getmetatable) (lua_State *L, int objindex);+LUA_API void (lua_getuservalue) (lua_State *L, int idx);+++/*+** set functions (stack -> Lua)+*/+LUA_API void (lua_setglobal) (lua_State *L, const char *var);+LUA_API void (lua_settable) (lua_State *L, int idx);+LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k);+LUA_API void (lua_rawset) (lua_State *L, int idx);+LUA_API void (lua_rawseti) (lua_State *L, int idx, int n);+LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p);+LUA_API int (lua_setmetatable) (lua_State *L, int objindex);+LUA_API void (lua_setuservalue) (lua_State *L, int idx);++LUA_API void (lua_setpico8memory) (lua_State *L, unsigned char const *p);++/*+** 'load' and 'call' functions (load and run Lua code)+*/+LUA_API void (lua_callk) (lua_State *L, int nargs, int nresults, int ctx,+ lua_CFunction k);+#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL)++LUA_API int (lua_getctx) (lua_State *L, int *ctx);++LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc,+ int ctx, lua_CFunction k);+#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL)++LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt,+ const char *chunkname,+ const char *mode);++LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data);+++/*+** coroutine functions+*/+LUA_API int (lua_yieldk) (lua_State *L, int nresults, int ctx,+ lua_CFunction k);+#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL)+LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg);+LUA_API int (lua_status) (lua_State *L);++/*+** garbage-collection function and options+*/++#define LUA_GCSTOP 0+#define LUA_GCRESTART 1+#define LUA_GCCOLLECT 2+#define LUA_GCCOUNT 3+#define LUA_GCCOUNTB 4+#define LUA_GCSTEP 5+#define LUA_GCSETPAUSE 6+#define LUA_GCSETSTEPMUL 7+#define LUA_GCSETMAJORINC 8+#define LUA_GCISRUNNING 9+#define LUA_GCGEN 10+#define LUA_GCINC 11++LUA_API int (lua_gc) (lua_State *L, int what, int data);+++/*+** miscellaneous functions+*/++LUA_API int (lua_error) (lua_State *L);++LUA_API int (lua_next) (lua_State *L, int idx);++LUA_API void (lua_concat) (lua_State *L, int n);+LUA_API void (lua_len) (lua_State *L, int idx);++LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud);+LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud);++++/*+** ===============================================================+** some useful macros+** ===============================================================+*/++#define lua_tonumber(L,i) lua_tonumberx(L,i,NULL)+#define lua_tointeger(L,i) lua_tointegerx(L,i,NULL)+#define lua_tounsigned(L,i) lua_tounsignedx(L,i,NULL)++#define lua_pop(L,n) lua_settop(L, -(n)-1)++#define lua_newtable(L) lua_createtable(L, 0, 0)++#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))++#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0)++#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION)+#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE)+#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA)+#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL)+#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN)+#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD)+#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE)+#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0)++#define lua_pushliteral(L, s) \+ lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1)++#define lua_pushglobaltable(L) \+ lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS)++#define lua_tostring(L,i) lua_tolstring(L, (i), NULL)+#define lua_to_or_default(L, w, i, d) lua_gettop(L) >= i ? lua_to##w(L, i) : d++++/*+** {======================================================================+** Debug API+** =======================================================================+*/+++/*+** Event codes+*/+#define LUA_HOOKCALL 0+#define LUA_HOOKRET 1+#define LUA_HOOKLINE 2+#define LUA_HOOKCOUNT 3+#define LUA_HOOKTAILCALL 4+++/*+** Event masks+*/+#define LUA_MASKCALL (1 << LUA_HOOKCALL)+#define LUA_MASKRET (1 << LUA_HOOKRET)+#define LUA_MASKLINE (1 << LUA_HOOKLINE)+#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT)++typedef struct lua_Debug lua_Debug; /* activation record */+++/* Functions to be called by the debugger in specific events */+typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);+++LUA_API int (lua_getstack) (lua_State *L, int level, lua_Debug *ar);+LUA_API int (lua_getinfo) (lua_State *L, const char *what, lua_Debug *ar);+LUA_API const char *(lua_getlocal) (lua_State *L, const lua_Debug *ar, int n);+LUA_API const char *(lua_setlocal) (lua_State *L, const lua_Debug *ar, int n);+LUA_API const char *(lua_getupvalue) (lua_State *L, int funcindex, int n);+LUA_API const char *(lua_setupvalue) (lua_State *L, int funcindex, int n);++LUA_API void *(lua_upvalueid) (lua_State *L, int fidx, int n);+LUA_API void (lua_upvaluejoin) (lua_State *L, int fidx1, int n1,+ int fidx2, int n2);++LUA_API int (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count);+LUA_API lua_Hook (lua_gethook) (lua_State *L);+LUA_API int (lua_gethookmask) (lua_State *L);+LUA_API int (lua_gethookcount) (lua_State *L);+++struct lua_Debug {+ int event;+ const char *name; /* (n) */+ const char *namewhat; /* (n) 'global', 'local', 'field', 'method' */+ const char *what; /* (S) 'Lua', 'C', 'main', 'tail' */+ const char *source; /* (S) */+ int currentline; /* (l) */+ int linedefined; /* (S) */+ int lastlinedefined; /* (S) */+ unsigned char nups; /* (u) number of upvalues */+ unsigned char nparams;/* (u) number of parameters */+ char isvararg; /* (u) */+ char istailcall; /* (t) */+ char short_src[LUA_IDSIZE]; /* (S) */+ /* private part */+ struct CallInfo *i_ci; /* active function */+};++/* }====================================================================== */+++/******************************************************************************+* Copyright (C) 1994-2015 Lua.org, PUC-Rio.+*+* Permission is hereby granted, free of charge, to any person obtaining+* a copy of this software and associated documentation files (the+* "Software"), to deal in the Software without restriction, including+* without limitation the rights to use, copy, modify, merge, publish,+* distribute, sublicense, and/or sell copies of the Software, and to+* permit persons to whom the Software is furnished to do so, subject to+* the following conditions:+*+* The above copyright notice and this permission notice shall be+* included in all copies or substantial portions of the Software.+*+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,+* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE+* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+******************************************************************************/+++#endifdiff --git a/games/numpico/src/femto8/lua/luaconf.h b/games/numpico/src/femto8/lua/luaconf.hnew file mode 100644index 00000000..c0b108f7--- /dev/null+++ b/games/numpico/src/femto8/lua/luaconf.h@@ -0,0 +1,735 @@+/*+** $Id: luaconf.h,v 1.176.1.1 2013/04/12 18:48:47 roberto Exp roberto $+** Configuration file for Lua+** See Copyright Notice in lua.h+*/+++#ifndef lconfig_h+#define lconfig_h++#include <limits.h>+#include <stddef.h>+++/*+** ==================================================================+** Search for "@@" to find all configurable definitions.+** ===================================================================+*/+++/*+@@ LUA_ANSI controls the use of non-ansi features.+** CHANGE it (define it) if you want Lua to avoid the use of any+** non-ansi feature or library.+*/+#if !defined(LUA_ANSI) && defined(__STRICT_ANSI__)+#define LUA_ANSI+#endif+++#if !defined(LUA_ANSI) && defined(_WIN32) && !defined(_WIN32_WCE)+#define LUA_WIN /* enable goodies for regular Windows platforms */+#endif++#if defined(LUA_WIN)+#define LUA_DL_DLL+#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */+#endif++++#if defined(LUA_USE_LINUX)+#define LUA_USE_POSIX+#define LUA_USE_DLOPEN /* needs an extra library: -ldl */+#define LUA_USE_READLINE /* needs some extra libraries */+#define LUA_USE_STRTODHEX /* assume 'strtod' handles hex formats */+#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */+#define LUA_USE_LONGLONG /* assume support for long long */+#endif++#if defined(LUA_USE_MACOSX)+#define LUA_USE_POSIX+#define LUA_USE_DLOPEN /* does not need -ldl */+#define LUA_USE_READLINE /* needs an extra library: -lreadline */+#define LUA_USE_STRTODHEX /* assume 'strtod' handles hex formats */+#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */+#define LUA_USE_LONGLONG /* assume support for long long */+#endif++++/*+@@ LUA_USE_POSIX includes all functionality listed as X/Open System+@* Interfaces Extension (XSI).+** CHANGE it (define it) if your system is XSI compatible.+*/+#if defined(LUA_USE_POSIX)+#define LUA_USE_MKSTEMP+#define LUA_USE_ISATTY+#define LUA_USE_POPEN+#define LUA_USE_ULONGJMP+#define LUA_USE_GMTIME_R+#endif++++/*+@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for+@* Lua libraries.+@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for+@* C libraries.+** CHANGE them if your machine has a non-conventional directory+** hierarchy or if you want to install your libraries in+** non-conventional directories.+*/+#if defined(_WIN32) /* { */+/*+** In Windows, any exclamation mark ('!') in the path is replaced by the+** path of the directory of the executable file of the current process.+*/+#define LUA_LDIR "!\\lua\\"+#define LUA_CDIR "!\\"+#define LUA_PATH_DEFAULT \+ LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \+ LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" ".\\?.lua"+#define LUA_CPATH_DEFAULT \+ LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll;" ".\\?.dll"++#else /* }{ */++#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR "/"+#define LUA_ROOT "/usr/local/"+#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR+#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR+#define LUA_PATH_DEFAULT \+ LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \+ LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" "./?.lua"+#define LUA_CPATH_DEFAULT \+ LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so"+#endif /* } */+++/*+@@ LUA_DIRSEP is the directory separator (for submodules).+** CHANGE it if your machine does not use "/" as the directory separator+** and is not Windows. (On Windows Lua automatically uses "\".)+*/+#if defined(_WIN32)+#define LUA_DIRSEP "\\"+#else+#define LUA_DIRSEP "/"+#endif+++/*+@@ LUA_ENV is the name of the variable that holds the current+@@ environment, used to access global names.+** CHANGE it if you do not like this name.+*/+#define LUA_ENV "_ENV"+++/*+@@ LUA_API is a mark for all core API functions.+@@ LUALIB_API is a mark for all auxiliary library functions.+@@ LUAMOD_API is a mark for all standard library opening functions.+** CHANGE them if you need to define those functions in some special way.+** For instance, if you want to create one Windows DLL with the core and+** the libraries, you may want to use the following definition (define+** LUA_BUILD_AS_DLL to get it).+*/+#if defined(LUA_BUILD_AS_DLL) /* { */++#if defined(LUA_CORE) || defined(LUA_LIB) /* { */+#define LUA_API __declspec(dllexport)+#else /* }{ */+#define LUA_API __declspec(dllimport)+#endif /* } */++#else /* }{ */++#define LUA_API extern++#endif /* } */+++/* more often than not the libs go together with the core */+#define LUALIB_API LUA_API+#define LUAMOD_API LUALIB_API+++/*+@@ LUAI_FUNC is a mark for all extern functions that are not to be+@* exported to outside modules.+@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables+@* that are not to be exported to outside modules (LUAI_DDEF for+@* definitions and LUAI_DDEC for declarations).+** CHANGE them if you need to mark them in some special way. Elf/gcc+** (versions 3.2 and later) mark them as "hidden" to optimize access+** when Lua is compiled as a shared library. Not all elf targets support+** this attribute. Unfortunately, gcc does not offer a way to check+** whether the target offers that support, and those without support+** give a warning about it. To avoid these warnings, change to the+** default definition.+*/+#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \+ defined(__ELF__) /* { */+#define LUAI_FUNC __attribute__((visibility("hidden"))) extern+#define LUAI_DDEC LUAI_FUNC+#define LUAI_DDEF /* empty */++#else /* }{ */+#define LUAI_FUNC extern+#define LUAI_DDEC extern+#define LUAI_DDEF /* empty */+#endif /* } */++++/*+@@ LUA_QL describes how error messages quote program elements.+** CHANGE it if you want a different appearance.+*/+#define LUA_QL(x) "'" x "'"+#define LUA_QS LUA_QL("%s")+++/*+@@ LUA_IDSIZE gives the maximum size for the description of the source+@* of a function in debug information.+** CHANGE it if you want a different size.+*/+#define LUA_IDSIZE 60+++/*+@@ luai_writestring/luai_writeline define how 'print' prints its results.+** They are only used in libraries and the stand-alone program. (The #if+** avoids including 'stdio.h' everywhere.)+*/+#if defined(LUA_LIB) || defined(lua_c)+#include <stdio.h>+#define luai_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)+#define luai_writeline() (luai_writestring("\n", 1), fflush(stdout))+#endif++/*+@@ luai_writestringerror defines how to print error messages.+** (A format string with one argument is enough for Lua...)+*/+#define luai_writestringerror(s,p) \+ (fprintf(stderr, (s), (p)), fflush(stderr))+++/*+@@ LUAI_MAXSHORTLEN is the maximum length for short strings, that is,+** strings that are internalized. (Cannot be smaller than reserved words+** or tags for metamethods, as these strings must be internalized;+** #("function") = 8, #("__newindex") = 10.)+*/+#define LUAI_MAXSHORTLEN 40++++/*+** {==================================================================+** Compatibility with previous versions+** ===================================================================+*/++/*+@@ LUA_COMPAT_ALL controls all compatibility options.+** You can define it to get all options, or change specific options+** to fit your specific needs.+*/+#if defined(LUA_COMPAT_ALL) /* { */++/*+@@ LUA_COMPAT_UNPACK controls the presence of global 'unpack'.+** You can replace it with 'table.unpack'.+*/+#define LUA_COMPAT_UNPACK++/*+@@ LUA_COMPAT_LOADERS controls the presence of table 'package.loaders'.+** You can replace it with 'package.searchers'.+*/+#define LUA_COMPAT_LOADERS++/*+@@ macro 'lua_cpcall' emulates deprecated function lua_cpcall.+** You can call your C function directly (with light C functions).+*/+#define lua_cpcall(L,f,u) \+ (lua_pushcfunction(L, (f)), \+ lua_pushlightuserdata(L,(u)), \+ lua_pcall(L,1,0,0))+++/*+@@ LUA_COMPAT_LOG10 defines the function 'log10' in the math library.+** You can rewrite 'log10(x)' as 'log(x, 10)'.+*/+#define LUA_COMPAT_LOG10++/*+@@ LUA_COMPAT_LOADSTRING defines the function 'loadstring' in the base+** library. You can rewrite 'loadstring(s)' as 'load(s)'.+*/+#define LUA_COMPAT_LOADSTRING++/*+@@ LUA_COMPAT_MAXN defines the function 'maxn' in the table library.+*/+#define LUA_COMPAT_MAXN++/*+@@ The following macros supply trivial compatibility for some+** changes in the API. The macros themselves document how to+** change your code to avoid using them.+*/+#define lua_strlen(L,i) lua_rawlen(L, (i))++#define lua_objlen(L,i) lua_rawlen(L, (i))++#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ)+#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT)++/*+@@ LUA_COMPAT_MODULE controls compatibility with previous+** module functions 'module' (Lua) and 'luaL_register' (C).+*/+#define LUA_COMPAT_MODULE++#endif /* } */++/* }================================================================== */++++/*+@@ LUAI_BITSINT defines the number of bits in an int.+** CHANGE here if Lua cannot automatically detect the number of bits of+** your machine. Probably you do not need to change this.+*/+/* avoid overflows in comparison */+#if INT_MAX-20 < 32760 /* { */+#define LUAI_BITSINT 16+#elif INT_MAX > 2147483640L /* }{ */+/* int has at least 32 bits */+#define LUAI_BITSINT 32+#else /* }{ */+#error "you must define LUA_BITSINT with number of bits in an integer"+#endif /* } */+++/*+@@ LUA_INT32 is a signed integer with exactly 32 bits.+@@ LUAI_UMEM is an unsigned integer big enough to count the total+@* memory used by Lua.+@@ LUAI_MEM is a signed integer big enough to count the total memory+@* used by Lua.+** CHANGE here if for some weird reason the default definitions are not+** good enough for your machine. Probably you do not need to change+** this.+*/+#if LUAI_BITSINT >= 32 /* { */+#define LUA_INT32 int+#define LUAI_UMEM size_t+#define LUAI_MEM ptrdiff_t+#else /* }{ */+/* 16-bit ints */+#define LUA_INT32 long+#define LUAI_UMEM unsigned long+#define LUAI_MEM long+#endif /* } */+++/*+@@ LUAI_MAXSTACK limits the size of the Lua stack.+** CHANGE it if you need a different limit. This limit is arbitrary;+** its only purpose is to stop Lua from consuming unlimited stack+** space (and to reserve some numbers for pseudo-indices).+*/+#if LUAI_BITSINT >= 32+#define LUAI_MAXSTACK 1000000+#else+#define LUAI_MAXSTACK 15000+#endif++/* reserve some space for error handling */+#define LUAI_FIRSTPSEUDOIDX (-LUAI_MAXSTACK - 1000)+++++/*+@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system.+** CHANGE it if it uses too much C-stack space.+*/+#define LUAL_BUFFERSIZE BUFSIZ+++++/*+** {==================================================================+@@ LUA_NUMBER is the type of numbers in Lua.+** CHANGE the following definitions only if you want to build Lua+** with a number type different from double. You may also need to+** change lua_number2int & lua_number2integer.+** ===================================================================+*/++#define LUA_NUMBER_DOUBLE+#define LUA_NUMBER double++/*+@@ LUAI_UACNUMBER is the result of an 'usual argument conversion'+@* over a number.+*/+#define LUAI_UACNUMBER double+++/*+@@ LUA_NUMBER_SCAN is the format for reading numbers.+@@ LUA_NUMBER_FMT is the format for writing numbers.+@@ lua_number2str converts a number to a string.+@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion.+*/+#define LUA_NUMBER_SCAN "%lf"+#define LUA_NUMBER_FMT "%.14g"+#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n))+#define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */+++/*+@@ l_mathop allows the addition of an 'l' or 'f' to all math operations+*/+#define l_mathop(x) (x)+++/*+@@ lua_str2number converts a decimal numeric string to a number.+@@ lua_strx2number converts an hexadecimal numeric string to a number.+** In C99, 'strtod' does both conversions. C89, however, has no function+** to convert floating hexadecimal strings to numbers. For these+** systems, you can leave 'lua_strx2number' undefined and Lua will+** provide its own implementation.+*/+#define lua_str2number(s,p) strtod((s), (p))++#if defined(LUA_USE_STRTODHEX)+#define lua_strx2number(s,p) strtod((s), (p))+#endif+++/*+@@ The luai_num* macros define the primitive operations over numbers.+*/++/* the following operations need the math library */+#if defined(lobject_c) || defined(lvm_c)+#include <math.h>+#define luai_nummod(L,a,b) ((a)%(b))+#define luai_numpow(L,a,b) (l_mathop(pow)(a,b))+#endif++/* these are quite standard operations */+#if defined(LUA_CORE)+#define luai_numadd(L,a,b) ((a)+(b))+#define luai_numsub(L,a,b) ((a)-(b))+#define luai_nummul(L,a,b) ((a)*(b))+#define luai_numdiv(L,a,b) ((a)/(b))+#define luai_numunm(L,a) (-(a))+#define luai_numeq(a,b) ((a)==(b))+#define luai_numlt(L,a,b) ((a)<(b))+#define luai_numle(L,a,b) ((a)<=(b))+#define luai_numisnan(L,a) (!luai_numeq((a), (a)))+#endif++++/*+@@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger.+** CHANGE that if ptrdiff_t is not adequate on your machine. (On most+** machines, ptrdiff_t gives a good choice between int or long.)+*/+#define LUA_INTEGER ptrdiff_t++/*+@@ LUA_UNSIGNED is the integral type used by lua_pushunsigned/lua_tounsigned.+** It must have at least 32 bits.+*/+#define LUA_UNSIGNED unsigned LUA_INT32++++/*+** Some tricks with doubles+*/++#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) /* { */+/*+** The next definitions activate some tricks to speed up the+** conversion from doubles to integer types, mainly to LUA_UNSIGNED.+**+@@ LUA_MSASMTRICK uses Microsoft assembler to avoid clashes with a+** DirectX idiosyncrasy.+**+@@ LUA_IEEE754TRICK uses a trick that should work on any machine+** using IEEE754 with a 32-bit integer type.+**+@@ LUA_IEEELL extends the trick to LUA_INTEGER; should only be+** defined when LUA_INTEGER is a 32-bit integer.+**+@@ LUA_IEEEENDIAN is the endianness of doubles in your machine+** (0 for little endian, 1 for big endian); if not defined, Lua will+** check it dynamically for LUA_IEEE754TRICK (but not for LUA_NANTRICK).+**+@@ LUA_NANTRICK controls the use of a trick to pack all types into+** a single double value, using NaN values to represent non-number+** values. The trick only works on 32-bit machines (ints and pointers+** are 32-bit values) with numbers represented as IEEE 754-2008 doubles+** with conventional endianess (12345678 or 87654321), in CPUs that do+** not produce signaling NaN values (all NaNs are quiet).+*/++/* Microsoft compiler on a Pentium (32 bit) ? */+#if defined(LUA_WIN) && defined(_MSC_VER) && defined(_M_IX86) /* { */++#define LUA_MSASMTRICK+#define LUA_IEEEENDIAN 0+#define LUA_NANTRICK+++/* pentium 32 bits? */+#elif defined(__i386__) || defined(__i386) || defined(__X86__) /* }{ */++#define LUA_IEEE754TRICK+#define LUA_IEEELL+#define LUA_IEEEENDIAN 0+#define LUA_NANTRICK++/* pentium 64 bits? */+#elif defined(__x86_64) /* }{ */++#define LUA_IEEE754TRICK+#define LUA_IEEEENDIAN 0++#elif defined(__POWERPC__) || defined(__ppc__) /* }{ */++#define LUA_IEEE754TRICK+#define LUA_IEEEENDIAN 1++#else /* }{ */++/* assume IEEE754 and a 32-bit integer type */+#define LUA_IEEE754TRICK++#endif /* } */++#endif /* } */++/* }================================================================== */+++++/* =================================================================== */++/*+** Local configuration. You can use this space to add your redefinitions+** without modifying the main part of the file.+*/+++#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include "fix32.h"++#undef LUA_USE_STRTODHEX+#undef LUA_USE_LONGLONG+#undef LUA_INTEGER+#undef LUA_UNSIGNED+#undef LUA_NUMBER_DOUBLE+#undef LUA_NUMBER+#undef LUA_IEEE754TRICK+#undef LUA_MSASMTRICK+#undef LUAI_UACNUMBER+#undef LUA_NANTRICK++#undef lua_number2str+#undef l_mathop+#undef lua_str2number++#undef LUA_NUMBER_SCAN+#undef LUA_NUMBER_FMT+#undef LUAI_MAXNUMBER2STR++#undef luai_nummod+#undef luai_numpow+#undef luai_numadd+#undef luai_numsub+#undef luai_nummul+#undef luai_numdiv+#undef luai_numunm+#undef luai_numeq+#undef luai_numlt+#undef luai_numle+#undef luai_numisnan++#define LUA_PROGNAME "nextp8"+#define LUA_INTEGER int16_t+#define LUA_UNSIGNED uint16_t+#define LUA_NUMBER fix32_t+#define LUAI_UACNUMBER fix32_t+#define LUA_NBITS 16+#define LUAI_MAXNUMBER2STR 32++#define LUA_USE_LONGJMP++#define LUA_COMPAT_UNPACK++/*+** lua_str2number: parse a decimal string to fix32_t, as strtod and fix32_from_double would (the+** integer part wraps at 65536, the fraction is cut, not rounded), without strtod (NumPico: newlib's+** needs malloc)+*/+static inline fix32_t lua_str2number_fn(const char *s, char **endptr) {+ const char *p = s;+ while (*p == ' ' || (*p >= '\t' && *p <= '\r')) p++;+ int neg = 0, any = 0;+ if (*p == '-') neg = 1, p++;+ else if (*p == '+') p++;+ uint32_t ip = 0;+ uint64_t frac = 0, scale = 1;+ while (*p >= '0' && *p <= '9') ip = (ip * 10 + (uint32_t)(*p++ - '0')) & 0xffff, any = 1;+ if (*p == '.') {+ p++;+ while (*p >= '0' && *p <= '9') {+ if (scale < 1000000000u) frac = frac * 10 + (uint64_t)(*p - '0'), scale *= 10;+ p++, any = 1;+ }+ }+ if (!any) {+ *endptr = (char *)s;+ return 0;+ }+ uint32_t bits = (ip << 16) + (uint32_t)((frac << 16) / scale);+ if (*p == 'e' || *p == 'E') {+ const char *q = p + 1;+ int eneg = 0, e = 0, digits = 0;+ if (*q == '-') eneg = 1, q++;+ else if (*q == '+') q++;+ while (*q >= '0' && *q <= '9') e = e * 10 + (*q++ - '0'), digits = 1;+ if (digits) {+ double d = (double)ip + (double)frac / (double)scale;+ while (e-- > 0 && d < 1e12) d = eneg ? d / 10 : d * 10;+ bits = (uint32_t)(int64_t)(d * 65536.0);+ p = q;+ }+ }+ *endptr = (char *)p;+ return (fix32_t)(neg ? 0u - bits : bits);+}++/* (NumPico: strings hash from a fixed seed, not the time) */+#define luai_makeseed() 0x50384e50u+#define lua_str2number(s,p) lua_str2number_fn((s), (p))++/*+** lua_number2str: convert fix32_t to string.+** Returns the length written (matching the C++ lambda that was here before).+*/+static inline int lua_number2str_fn(char *s, fix32_t n) {+ int negative = (n < 0);+ /* Get absolute value: for negative n, use -n (two's complement) */+ unsigned x = negative ? (unsigned)(-n) : (unsigned)n;+ unsigned w = x >> 16;+ unsigned frac = x & 0xffff;++ /*+ * Convert fractional part to decimal string with 4 decimal places.+ * frac is in [0, 65535], representing frac/65536.+ * For very small values (frac <= 6), the scaled value is < 1, so we truncate.+ * For larger values, use standard rounding to nearest.+ */+ unsigned f;+ if (frac <= 6U) {+ /* Very small values: truncate */+ f = frac * 10000U / 65536U;+ } else {+ /* Larger values: round to nearest */+ f = (frac * 10000U + 32768U) / 65536U;+ }++ /* Handle carry when fractional part rounds to 10000 */+ if (f >= 10000U) {+ f -= 10000U;+ w++;+ }++ int i = sprintf(s, "%s%d.%04d", negative ? "-" : "", w, f);+ while (i > 0 && s[i - 1] == '0') s[--i] = '\0';+ if (i > 0 && s[i - 1] == '.') s[--i] = '\0';+ return i;+}+#define lua_number2str(s,n) lua_number2str_fn((s), (n))++/*+** Arithmetic macros using our pure C fix32 functions.+*/+#if defined(lobject_c) || defined(lvm_c)+#include <math.h>+#endif++/* these are used everywhere in LUA_CORE */+#if defined(LUA_CORE)+#define luai_numadd(L,a,b) fix32_add((a),(b))+#define luai_numsub(L,a,b) fix32_sub((a),(b))+#define luai_nummul(L,a,b) fix32_mul((a),(b))+#define luai_numdiv(L,a,b) fix32_div((a),(b))+#define luai_numunm(L,a) fix32_neg(a)+#define luai_numeq(a,b) fix32_eq((a),(b))+#define luai_numlt(L,a,b) fix32_lt((a),(b))+#define luai_numle(L,a,b) fix32_le((a),(b))+#define luai_numisnan(L,a) (0) /* fix32 has no NaN */+#endif++#define luai_nummod(L,a,b) fix32_mod((a),(b))+#define luai_numpow(L,a,b) fix32_pow((a),(b))+#define luai_numidiv(L,a,b) fix32_idiv((a),(b))++/* Bitwise operations on fix32 */+#define luai_numband(L,a,b) fix32_band((a),(b))+#define luai_numbor(L,a,b) fix32_bor((a),(b))+#define luai_numbxor(L,a,b) fix32_bxor((a),(b))+#define luai_numshl(L,a,b) fix32_shl((a), fix32_to_int(b))+#define luai_numshr(L,a,b) fix32_shr((a), fix32_to_int(b))+#define luai_numlshr(L,a,b) fix32_lshr((a), fix32_to_int(b))+#define luai_numrotl(L,a,b) fix32_rotl((a), fix32_to_int(b))+#define luai_numrotr(L,a,b) fix32_rotr((a), fix32_to_int(b))+#define luai_numbnot(L,a) fix32_bnot(a)+#define luai_numpeek(L,a) (luaV_peek(L,a,1))+#define luai_numpeek2(L,a) (luaV_peek(L,a,2))+#define luai_numpeek4(L,a) (luaV_peek(L,a,4))++/*+** Hash for fix32 numbers.+** Multiply by golden ratio in fix32, take raw bits.+*/+#define luai_hashnum(i,n) \+ (i = (int)fix32_bits(fix32_mul((n), fix32_from_bits((int32_t)2654435769u))))++/*+** l_mathop is not used in fix32 mode, but define it to avoid errors+** in dead code paths.+*/+#define l_mathop(x) (x)++#endif+diff --git a/games/numpico/src/femto8/lua/lualib.h b/games/numpico/src/femto8/lua/lualib.hnew file mode 100644index 00000000..6c1d307a--- /dev/null+++ b/games/numpico/src/femto8/lua/lualib.h@@ -0,0 +1,57 @@+/*+** $Id: lualib.h,v 1.43 2011/12/08 12:11:37 roberto Exp $+** Lua standard libraries+** See Copyright Notice in lua.h+*/+++#ifndef lualib_h+#define lualib_h++#include "lua.h"++++LUAMOD_API int (luaopen_base) (lua_State *L);++LUAMOD_API int (luaopen_pico8) (lua_State *L);++#define LUA_COLIBNAME "coroutine"+LUAMOD_API int (luaopen_coroutine) (lua_State *L);++#define LUA_TABLIBNAME "table"+LUAMOD_API int (luaopen_table) (lua_State *L);++#define LUA_IOLIBNAME "io"+LUAMOD_API int (luaopen_io) (lua_State *L);++#define LUA_OSLIBNAME "os"+LUAMOD_API int (luaopen_os) (lua_State *L);++#define LUA_STRLIBNAME "string"+LUAMOD_API int (luaopen_string) (lua_State *L);++#define LUA_BITLIBNAME "bit32"+LUAMOD_API int (luaopen_bit32) (lua_State *L);++#define LUA_MATHLIBNAME "math"+LUAMOD_API int (luaopen_math) (lua_State *L);++#define LUA_DBLIBNAME "debug"+LUAMOD_API int (luaopen_debug) (lua_State *L);++#define LUA_LOADLIBNAME "package"+LUAMOD_API int (luaopen_package) (lua_State *L);+++/* open all previous libraries */+LUALIB_API void (luaL_openlibs) (lua_State *L);++++#if !defined(lua_assert)+#define lua_assert(x) ((void)0)+#endif+++#endifdiff --git a/games/numpico/src/femto8/lua/lundump.h b/games/numpico/src/femto8/lua/lundump.hnew file mode 100644index 00000000..2b8accec--- /dev/null+++ b/games/numpico/src/femto8/lua/lundump.h@@ -0,0 +1,28 @@+/*+** $Id: lundump.h,v 1.39 2012/05/08 13:53:33 roberto Exp $+** load precompiled Lua chunks+** See Copyright Notice in lua.h+*/++#ifndef lundump_h+#define lundump_h++#include "lobject.h"+#include "lzio.h"++/* load one chunk; from lundump.c */+LUAI_FUNC Closure* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name);++/* make header; from lundump.c */+LUAI_FUNC void luaU_header (lu_byte* h);++/* dump one chunk; from ldump.c */+LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip);++/* data to catch conversion errors */+#define LUAC_TAIL "\x19\x93\r\n\x1a\n"++/* size in bytes of header of binary files */+#define LUAC_HEADERSIZE (sizeof(LUA_SIGNATURE)-sizeof(char)+2+6+sizeof(LUAC_TAIL)-sizeof(char))++#endifdiff --git a/games/numpico/src/femto8/lua/lvm.c b/games/numpico/src/femto8/lua/lvm.cnew file mode 100644index 00000000..9f05d238--- /dev/null+++ b/games/numpico/src/femto8/lua/lvm.c@@ -0,0 +1,976 @@+/*+** $Id: lvm.c,v 2.155 2013/03/16 21:10:18 roberto Exp $+** Lua virtual machine+** See Copyright Notice in lua.h+*/+++#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <stdint.h>++#define lvm_c+#define LUA_CORE++#include "lua.h"++#include "ldebug.h"+#include "ldo.h"+#include "lfunc.h"+#include "lgc.h"+#include "lobject.h"+#include "lopcodes.h"+#include "lstate.h"+#include "lstring.h"+#include "ltable.h"+#include "ltm.h"+#include "lvm.h"++++/* limit for table tag-method chains (to avoid loops) */+#define MAXTAGLOOP 100+++const TValue *luaV_tonumber (const TValue *obj, TValue *n) {+ lua_Number num;+ if (ttisnumber(obj)) return obj;+ if (ttisstring(obj) && luaO_str2d(svalue(obj), tsvalue(obj)->len, &num)) {+ setnvalue(n, num);+ return n;+ }+ else+ return NULL;+}+++int luaV_tostring (lua_State *L, StkId obj) {+ if (!ttisnumber(obj))+ return 0;+ else {+ char s[LUAI_MAXNUMBER2STR];+ lua_Number n = nvalue(obj);+ int l = lua_number2str(s, n);+ setsvalue2s(L, obj, luaS_newlstr(L, s, l));+ return 1;+ }+}+++static void traceexec (lua_State *L) {+ CallInfo *ci = L->ci;+ lu_byte mask = L->hookmask;+ int counthook = ((mask & LUA_MASKCOUNT) && L->hookcount == 0);+ if (counthook)+ resethookcount(L); /* reset count */+ if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */+ ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */+ return; /* do not call hook again (VM yielded, so it did not move) */+ }+ if (counthook)+ luaD_hook(L, LUA_HOOKCOUNT, -1); /* call count hook */+ if (mask & LUA_MASKLINE) {+ Proto *p = ci_func(ci)->p;+ int npc = pcRel(ci->u.l.savedpc, p);+ int newline = getfuncline(p, npc);+ if (npc == 0 || /* call linehook when enter a new function, */+ ci->u.l.savedpc <= L->oldpc || /* when jump back (loop), or when */+ newline != getfuncline(p, pcRel(L->oldpc, p))) /* enter a new line */+ luaD_hook(L, LUA_HOOKLINE, newline); /* call line hook */+ }+ L->oldpc = ci->u.l.savedpc;+ if (L->status == LUA_YIELD) { /* did hook yield? */+ if (counthook)+ L->hookcount = 1; /* undo decrement to zero */+ ci->u.l.savedpc--; /* undo increment (resume will increment it again) */+ ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */+ ci->func = L->top - 1; /* protect stack below results */+ luaD_throw(L, LUA_YIELD);+ }+}+++static void callTM (lua_State *L, const TValue *f, const TValue *p1,+ const TValue *p2, TValue *p3, int hasres) {+ ptrdiff_t result = savestack(L, p3);+ setobj2s(L, L->top++, f); /* push function */+ setobj2s(L, L->top++, p1); /* 1st argument */+ setobj2s(L, L->top++, p2); /* 2nd argument */+ if (!hasres) /* no result? 'p3' is third argument */+ setobj2s(L, L->top++, p3); /* 3rd argument */+ /* metamethod may yield only when called from Lua code */+ luaD_call(L, L->top - (4 - hasres), hasres, isLua(L->ci));+ if (hasres) { /* if has result, move it to its place */+ p3 = restorestack(L, result);+ setobjs2s(L, p3, --L->top);+ }+}+++void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) {+ // PICO-8 0.2.5 changelog: sub(str,pos,pos) can be written as str[pos]+ if (ttisstring(t)) {+ const char *s = svalue(t);+ size_t ls = tsvalue(t)->len;+ int k = fix32_to_int(nvalue(key));+ size_t idx = k > 0 ? k - 1 : ls + k;+ if (idx >= ls)+ setnilvalue(val);+ else+ setsvalue2s(L, val, luaS_newlstr(L, s + idx, 1));+ return;+ }+ int loop;+ for (loop = 0; loop < MAXTAGLOOP; loop++) {+ const TValue *tm;+ if (ttistable(t)) { /* `t' is a table? */+ Table *h = hvalue(t);+ const TValue *res = luaH_get(h, key); /* do a primitive get */+ if (!ttisnil(res) || /* result is not nil? */+ (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */+ setobj2s(L, val, res);+ return;+ }+ /* else will try the tag method */+ }+ else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX)))+ luaG_typeerror(L, t, "index");+ if (ttisfunction(tm)) {+ callTM(L, tm, t, key, val, 1);+ return;+ }+ t = tm; /* else repeat with 'tm' */+ }+ luaG_runerror(L, "loop in gettable");+}+++void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) {+ int loop;+ for (loop = 0; loop < MAXTAGLOOP; loop++) {+ const TValue *tm;+ if (ttistable(t)) { /* `t' is a table? */+ Table *h = hvalue(t);+ TValue *oldval = cast(TValue *, luaH_get(h, key));+ /* if previous value is not nil, there must be a previous entry+ in the table; moreover, a metamethod has no relevance */+ if (!ttisnil(oldval) ||+ /* previous value is nil; must check the metamethod */+ ((tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL &&+ /* no metamethod; is there a previous entry in the table? */+ (oldval != luaO_nilobject ||+ /* no previous entry; must create one. (The next test is+ always true; we only need the assignment.) */+ (oldval = luaH_newkey(L, h, key), 1)))) {+ /* no metamethod and (now) there is an entry with given key */+ setobj2t(L, oldval, val); /* assign new value to that entry */+ invalidateTMcache(h);+ luaC_barrierback(L, obj2gco(h), val);+ return;+ }+ /* else will try the metamethod */+ }+ else /* not a table; check metamethod */+ if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX)))+ luaG_typeerror(L, t, "index");+ /* there is a metamethod */+ if (ttisfunction(tm)) {+ callTM(L, tm, t, key, val, 0);+ return;+ }+ t = tm; /* else repeat with 'tm' */+ }+ luaG_runerror(L, "loop in settable");+}+++static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2,+ StkId res, TMS event) {+ const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */+ if (ttisnil(tm))+ tm = luaT_gettmbyobj(L, p2, event); /* try second operand */+ if (ttisnil(tm)) return 0;+ callTM(L, tm, p1, p2, res, 1);+ return 1;+}+++static const TValue *get_equalTM (lua_State *L, Table *mt1, Table *mt2,+ TMS event) {+ const TValue *tm1 = fasttm(L, mt1, event);+ const TValue *tm2;+ if (tm1 == NULL) return NULL; /* no metamethod */+ if (mt1 == mt2) return tm1; /* same metatables => same metamethods */+ tm2 = fasttm(L, mt2, event);+ if (tm2 == NULL) return NULL; /* no metamethod */+ if (luaV_rawequalobj(tm1, tm2)) /* same metamethods? */+ return tm1;+ return NULL;+}+++static int call_orderTM (lua_State *L, const TValue *p1, const TValue *p2,+ TMS event) {+ if (!call_binTM(L, p1, p2, L->top, event))+ return -1; /* no metamethod */+ else+ return !l_isfalse(L->top);+}+++/* (NumPico keeps PICO-8's memory up to 0x7fff: past it reads 0, and the sprite sheet and the+ screen stay at 0x0000 or 0x6000) */+static unsigned char PEEK(unsigned char const *ram, unsigned address)+{+ address &= 0xffff;+ if (!ram)+ return 0;+ if (address < 0x2000)+ address = (ram[0x5f54] == 0x60 ? 0x6000 : 0) | (address & 0x1fff);+ else if (address >= 0x6000 && address < 0x8000)+ address = (ram[0x5f55] == 0x00 ? 0 : 0x6000) | (address & 0x1fff);+ return address < 0x8000 ? ram[address] : 0;+}++lua_Number luaV_peek(struct lua_State *L, lua_Number a, int count)+{+ unsigned char const *p = G(L)->pico8memory;+ int address = fix32_to_int(a) & 0xffff;+ uint32_t ret = 0;+ switch (count) {+ case 4:+ ret |= PEEK(p, address + 1) << 8;+ ret |= PEEK(p, address);+ address += 2;+ case 2:+ ret |= PEEK(p, address + 1) << 24;+ case 1:+ ret |= PEEK(p, address) << 16;+ break;+ }+ return fix32_from_bits(ret);+}+++static int l_strcmp (const TString *ls, const TString *rs) {+ const char *l = getstr(ls);+ size_t ll = ls->tsv.len;+ const char *r = getstr(rs);+ size_t lr = rs->tsv.len;+ for (;;) {+ int temp = strcmp(l, r); /* (NumPico: strcoll in the C locale) */+ if (temp != 0) return temp;+ else { /* strings are equal up to a `\0' */+ size_t len = strlen(l); /* index of first `\0' in both strings */+ if (len == lr) /* r is finished? */+ return (len == ll) ? 0 : 1;+ else if (len == ll) /* l is finished? */+ return -1; /* l is smaller than r (because r is not finished) */+ /* both strings longer than `len'; go on comparing (after the `\0') */+ len++;+ l += len; ll -= len; r += len; lr -= len;+ }+ }+}+++int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {+ int res;+ if (ttisnumber(l) && ttisnumber(r))+ return luai_numlt(L, nvalue(l), nvalue(r));+ else if (ttisstring(l) && ttisstring(r))+ return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0;+ else if ((res = call_orderTM(L, l, r, TM_LT)) < 0)+ luaG_ordererror(L, l, r);+ return res;+}+++int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) {+ int res;+ if (ttisnumber(l) && ttisnumber(r))+ return luai_numle(L, nvalue(l), nvalue(r));+ else if (ttisstring(l) && ttisstring(r))+ return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0;+ else if ((res = call_orderTM(L, l, r, TM_LE)) >= 0) /* first try `le' */+ return res;+ else if ((res = call_orderTM(L, r, l, TM_LT)) < 0) /* else try `lt' */+ luaG_ordererror(L, l, r);+ return !res;+}+++/*+** equality of Lua values. L == NULL means raw equality (no metamethods)+*/+int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2) {+ const TValue *tm;+ lua_assert(ttisequal(t1, t2));+ switch (ttype(t1)) {+ case LUA_TNIL: return 1;+ case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2));+ case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */+ case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);+ case LUA_TLCF: return fvalue(t1) == fvalue(t2);+ case LUA_TSHRSTR: return eqshrstr(rawtsvalue(t1), rawtsvalue(t2));+ case LUA_TLNGSTR: return luaS_eqlngstr(rawtsvalue(t1), rawtsvalue(t2));+ case LUA_TUSERDATA: {+ if (uvalue(t1) == uvalue(t2)) return 1;+ else if (L == NULL) return 0;+ tm = get_equalTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ);+ break; /* will try TM */+ }+ case LUA_TTABLE: {+ if (hvalue(t1) == hvalue(t2)) return 1;+ else if (L == NULL) return 0;+ tm = get_equalTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);+ break; /* will try TM */+ }+ default:+ lua_assert(iscollectable(t1));+ return gcvalue(t1) == gcvalue(t2);+ }+ if (tm == NULL) return 0; /* no TM? */+ callTM(L, tm, t1, t2, L->top, 1); /* call TM */+ return !l_isfalse(L->top);+}+++void luaV_concat (lua_State *L, int total) {+ lua_assert(total >= 2);+ do {+ StkId top = L->top;+ int n = 2; /* number of elements handled in this pass (at least 2) */+ if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) {+ if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT))+ luaG_concaterror(L, top-2, top-1);+ }+ else if (tsvalue(top-1)->len == 0) /* second operand is empty? */+ (void)tostring(L, top - 2); /* result is first operand */+ else if (ttisstring(top-2) && tsvalue(top-2)->len == 0) {+ setobjs2s(L, top - 2, top - 1); /* result is second op. */+ }+ else {+ /* at least two non-empty string values; get as many as possible */+ size_t tl = tsvalue(top-1)->len;+ char *buffer;+ int i;+ /* collect total length */+ for (i = 1; i < total && tostring(L, top-i-1); i++) {+ size_t l = tsvalue(top-i-1)->len;+ if (l >= (MAX_SIZET/sizeof(char)) - tl)+ luaG_runerror(L, "string length overflow");+ tl += l;+ }+ buffer = luaZ_openspace(L, &G(L)->buff, tl);+ tl = 0;+ n = i;+ do { /* concat all strings */+ size_t l = tsvalue(top-i)->len;+ memcpy(buffer+tl, svalue(top-i), l * sizeof(char));+ tl += l;+ } while (--i > 0);+ setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));+ }+ total -= n-1; /* got 'n' strings to create 1 new */+ L->top -= n-1; /* popped 'n' strings and pushed one */+ } while (total > 1); /* repeat until only 1 result left */+}+++void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {+ const TValue *tm;+ switch (ttypenv(rb)) {+ case LUA_TTABLE: {+ Table *h = hvalue(rb);+ tm = fasttm(L, h->metatable, TM_LEN);+ if (tm) break; /* metamethod? break switch to call it */+ setnvalue(ra, cast_num(luaH_getn(h))); /* else primitive len */+ return;+ }+ case LUA_TSTRING: {+ setnvalue(ra, cast_num((int)(uint64_t)tsvalue(rb)->len));+ return;+ }+ default: { /* try metamethod */+ tm = luaT_gettmbyobj(L, rb, TM_LEN);+ if (ttisnil(tm)) /* no metamethod? */+ luaG_typeerror(L, rb, "get length of");+ break;+ }+ }+ callTM(L, tm, rb, rb, ra, 1);+}+++void luaV_arith (lua_State *L, StkId ra, const TValue *rb,+ const TValue *rc, TMS op) {+ TValue tempb, tempc;+ const TValue *b, *c;+ if ((b = luaV_tonumber(rb, &tempb)) != NULL &&+ (c = luaV_tonumber(rc, &tempc)) != NULL) {+ lua_Number res = luaO_arith(L, op - TM_ADD + LUA_OPADD, nvalue(b), nvalue(c));+ setnvalue(ra, res);+ }+ else if (!call_binTM(L, rb, rc, ra, op))+ luaG_aritherror(L, rb, rc);+}+++/*+** check whether cached closure in prototype 'p' may be reused, that is,+** whether there is a cached closure with the same upvalues needed by+** new closure to be created.+*/+static Closure *getcached (Proto *p, UpVal **encup, StkId base) {+ Closure *c = p->cache;+ if (c != NULL) { /* is there a cached closure? */+ int nup = p->sizeupvalues;+ Upvaldesc *uv = p->upvalues;+ int i;+ for (i = 0; i < nup; i++) { /* check whether it has right upvalues */+ TValue *v = uv[i].instack ? base + uv[i].idx : encup[uv[i].idx]->v;+ if (c->l.upvals[i]->v != v)+ return NULL; /* wrong upvalue; cannot reuse closure */+ }+ }+ return c; /* return cached closure (or NULL if no cached closure) */+}+++/*+** create a new Lua closure, push it in the stack, and initialize+** its upvalues. Note that the call to 'luaC_barrierproto' must come+** before the assignment to 'p->cache', as the function needs the+** original value of that field.+*/+static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base,+ StkId ra) {+ int nup = p->sizeupvalues;+ Upvaldesc *uv = p->upvalues;+ int i;+ Closure *ncl = luaF_newLclosure(L, nup);+ ncl->l.p = p;+ setclLvalue(L, ra, ncl); /* anchor new closure in stack */+ for (i = 0; i < nup; i++) { /* fill in its upvalues */+ if (uv[i].instack) /* upvalue refers to local variable? */+ ncl->l.upvals[i] = luaF_findupval(L, base + uv[i].idx);+ else /* get upvalue from enclosing function */+ ncl->l.upvals[i] = encup[uv[i].idx];+ }+ luaC_barrierproto(L, p, ncl);+ p->cache = ncl; /* save it on cache for reuse */+}+++/*+** finish execution of an opcode interrupted by an yield+*/+void luaV_finishOp (lua_State *L) {+ CallInfo *ci = L->ci;+ StkId base = ci->u.l.base;+ Instruction inst = *(ci->u.l.savedpc - 1); /* interrupted instruction */+ OpCode op = GET_OPCODE(inst);+ switch (op) { /* finish its execution */+ case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV:+ case OP_MOD: case OP_POW: case OP_IDIV: case OP_BAND:+ case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR:+ case OP_LSHR: case OP_ROTL: case OP_ROTR:+ case OP_UNM: case OP_BNOT: case OP_LEN:+ case OP_GETTABUP: case OP_GETTABLE: case OP_SELF: {+ setobjs2s(L, base + GETARG_A(inst), --L->top);+ break;+ }+ case OP_LE: case OP_LT: case OP_EQ: {+ int res = !l_isfalse(L->top - 1);+ L->top--;+ /* metamethod should not be called when operand is K */+ lua_assert(!ISK(GETARG_B(inst)));+ if (op == OP_LE && /* "<=" using "<" instead? */+ ttisnil(luaT_gettmbyobj(L, base + GETARG_B(inst), TM_LE)))+ res = !res; /* invert result */+ lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP);+ if (res != GETARG_A(inst)) /* condition failed? */+ ci->u.l.savedpc++; /* skip jump instruction */+ break;+ }+ case OP_CONCAT: {+ StkId top = L->top - 1; /* top when 'call_binTM' was called */+ int b = GETARG_B(inst); /* first element to concatenate */+ int total = cast_int(top - 1 - (base + b)); /* yet to concatenate */+ setobj2s(L, top - 2, top); /* put TM result in proper position */+ if (total > 1) { /* are there elements to concat? */+ L->top = top - 1; /* top is one after last element (at top-2) */+ luaV_concat(L, total); /* concat them (may yield again) */+ }+ /* move final result to final position */+ setobj2s(L, ci->u.l.base + GETARG_A(inst), L->top - 1);+ L->top = ci->top; /* restore top */+ break;+ }+ case OP_TFORCALL: {+ lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_TFORLOOP);+ L->top = ci->top; /* correct top */+ break;+ }+ case OP_CALL: {+ if (GETARG_C(inst) - 1 >= 0) /* nresults >= 0? */+ L->top = ci->top; /* adjust results */+ break;+ }+ case OP_TAILCALL: case OP_SETTABUP: case OP_SETTABLE:+ break;+ default: lua_assert(0);+ }+}++++/*+** some macros for common tasks in `luaV_execute'+*/++#if !defined luai_runtimecheck+#define luai_runtimecheck(L, c) /* void */+#endif+++#define RA(i) (base+GETARG_A(i))+/* to be used after possible stack reallocation */+#define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i))+#define RC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i))+#define RKB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \+ ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i))+#define RKC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \+ ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i))+#define KBx(i) \+ (k + (GETARG_Bx(i) != 0 ? GETARG_Bx(i) - 1 : GETARG_Ax(*ci->u.l.savedpc++)))+++/* execute a jump instruction */+#define dojump(ci,i,e) \+ { int a = GETARG_A(i); \+ if (a > 0) luaF_close(L, ci->u.l.base + a - 1); \+ ci->u.l.savedpc += GETARG_sBx(i) + e; }++/* for test instructions, execute the jump instruction that follows it */+#define donextjump(ci) { i = *ci->u.l.savedpc; dojump(ci, i, 1); }+++#define Protect(x) { {x;}; base = ci->u.l.base; }++#define checkGC(L,c) \+ Protect( luaC_condGC(L,{L->top = (c); /* limit of live values */ \+ luaC_step(L); \+ L->top = ci->top;}) /* restore top */ \+ luai_threadyield(L); )+++#define arith_op(op,tm) { \+ TValue *rb = RKB(i); \+ TValue *rc = RKC(i); \+ if (ttisnumber(rb) && ttisnumber(rc)) { \+ lua_Number nb = nvalue(rb), nc = nvalue(rc); \+ setnvalue(ra, op(L, nb, nc)); \+ } \+ else { Protect(luaV_arith(L, ra, rb, rc, tm)); } }++#define unary_op(op,tm) {\+ TValue *rb = RB(i); \+ if (ttisnumber(rb)) { \+ lua_Number nb = nvalue(rb); \+ setnvalue(ra, op(L, nb)); \+ } \+ else { Protect(luaV_arith(L, ra, rb, rb, tm)); } }++#define vmdispatch(o) switch(o)+#define vmcase(l,b) case l: {b} break;+#define vmcasenb(l,b) case l: {b} /* nb = no break */++void luaV_execute (lua_State *L) {+ CallInfo *ci = L->ci;+ LClosure *cl;+ TValue *k;+ StkId base;+ newframe: /* reentry point when frame changes (call/return) */+ lua_assert(ci == L->ci);+ cl = clLvalue(ci->func);+ k = cl->p->k;+ base = ci->u.l.base;+ /* main loop of interpreter */+ for (;;) {+ Instruction i = *(ci->u.l.savedpc++);+ StkId ra;+ if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&+ (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {+ Protect(traceexec(L));+ }+ /* WARNING: several calls may realloc the stack and invalidate `ra' */+ ra = RA(i);+ lua_assert(base == ci->u.l.base);+ lua_assert(base <= L->top && L->top < L->stack + L->stacksize);+ vmdispatch (GET_OPCODE(i)) {+ vmcase(OP_MOVE,+ setobjs2s(L, ra, RB(i));+ )+ vmcase(OP_LOADK,+ TValue *rb = k + GETARG_Bx(i);+ setobj2s(L, ra, rb);+ )+ vmcase(OP_LOADKX,+ TValue *rb;+ lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);+ rb = k + GETARG_Ax(*ci->u.l.savedpc++);+ setobj2s(L, ra, rb);+ )+ vmcase(OP_LOADBOOL,+ setbvalue(ra, GETARG_B(i));+ if (GETARG_C(i)) ci->u.l.savedpc++; /* skip next instruction (if C) */+ )+ vmcase(OP_LOADNIL,+ int b = GETARG_B(i);+ do {+ setnilvalue(ra++);+ } while (b--);+ )+ vmcase(OP_GETUPVAL,+ int b = GETARG_B(i);+ setobj2s(L, ra, cl->upvals[b]->v);+ )+ vmcase(OP_GETTABUP,+ int b = GETARG_B(i);+ Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra));+ )+ vmcase(OP_GETTABLE,+ Protect(luaV_gettable(L, RB(i), RKC(i), ra));+ )+ vmcase(OP_GETGLOBALTABLE,+ Table *reg = hvalue(&G(L)->l_registry);+ const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);+ Protect(luaV_gettable(L, gt, RKB(i), ra));+ )+ vmcase(OP_SETTABUP,+ int a = GETARG_A(i);+ Protect(luaV_settable(L, cl->upvals[a]->v, RKB(i), RKC(i)));+ )+ vmcase(OP_SETUPVAL,+ UpVal *uv = cl->upvals[GETARG_B(i)];+ setobj(L, uv->v, ra);+ luaC_barrier(L, uv, ra);+ )+ vmcase(OP_SETTABLE,+ Protect(luaV_settable(L, ra, RKB(i), RKC(i)));+ )+ vmcase(OP_SETGLOBALTABLE,+ Table *reg = hvalue(&G(L)->l_registry);+ const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);+ Protect(luaV_settable(L, gt, RKB(i), ra));+ )+ vmcase(OP_NEWTABLE,+ int b = GETARG_B(i);+ int c = GETARG_C(i);+ Table *t = luaH_new(L);+ sethvalue(L, ra, t);+ if (b != 0 || c != 0)+ luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c));+ checkGC(L, ra + 1);+ )+ vmcase(OP_SELF,+ StkId rb = RB(i);+ setobjs2s(L, ra+1, rb);+ Protect(luaV_gettable(L, rb, RKC(i), ra));+ )+ vmcase(OP_ADD,+ arith_op(luai_numadd, TM_ADD);+ )+ vmcase(OP_SUB,+ arith_op(luai_numsub, TM_SUB);+ )+ vmcase(OP_MUL,+ arith_op(luai_nummul, TM_MUL);+ )+ vmcase(OP_DIV,+ arith_op(luai_numdiv, TM_DIV);+ )+ vmcase(OP_MOD,+ arith_op(luai_nummod, TM_MOD);+ )+ vmcase(OP_POW,+ arith_op(luai_numpow, TM_POW);+ )+ vmcase(OP_IDIV,+ arith_op(luai_numidiv, TM_IDIV);+ )+ vmcase(OP_BAND,+ arith_op(luai_numband, TM_BAND);+ )+ vmcase(OP_BOR,+ arith_op(luai_numbor, TM_BOR);+ )+ vmcase(OP_BXOR,+ arith_op(luai_numbxor, TM_BXOR);+ )+ vmcase(OP_SHL,+ arith_op(luai_numshl, TM_SHL);+ )+ vmcase(OP_SHR,+ arith_op(luai_numshr, TM_SHR);+ )+ vmcase(OP_LSHR,+ arith_op(luai_numlshr, TM_LSHR);+ )+ vmcase(OP_ROTL,+ arith_op(luai_numrotl, TM_ROTL);+ )+ vmcase(OP_ROTR,+ arith_op(luai_numrotr, TM_ROTR);+ )+ vmcase(OP_UNM,+ unary_op(luai_numunm, TM_UNM);+ )+ vmcase(OP_BNOT,+ unary_op(luai_numbnot, TM_BNOT);+ )+ vmcase(OP_PEEK,+ unary_op(luai_numpeek, TM_PEEK);+ )+ vmcase(OP_PEEK2,+ unary_op(luai_numpeek2, TM_PEEK2);+ )+ vmcase(OP_PEEK4,+ unary_op(luai_numpeek4, TM_PEEK4);+ )+ vmcase(OP_NOT,+ TValue *rb = RB(i);+ int res = l_isfalse(rb); /* next assignment may change this value */+ setbvalue(ra, res);+ )+ vmcase(OP_LEN,+ Protect(luaV_objlen(L, ra, RB(i)));+ )+ vmcase(OP_CONCAT,+ int b = GETARG_B(i);+ int c = GETARG_C(i);+ StkId rb;+ L->top = base + c + 1; /* mark the end of concat operands */+ Protect(luaV_concat(L, c - b + 1));+ ra = RA(i); /* 'luav_concat' may invoke TMs and move the stack */+ rb = b + base;+ setobjs2s(L, ra, rb);+ checkGC(L, (ra >= rb ? ra + 1 : rb));+ L->top = ci->top; /* restore top */+ )+ vmcase(OP_JMP,+ dojump(ci, i, 0);+ )+ vmcase(OP_EQ,+ TValue *rb = RKB(i);+ TValue *rc = RKC(i);+ Protect(+ if (cast_int(equalobj(L, rb, rc)) != GETARG_A(i))+ ci->u.l.savedpc++;+ else+ donextjump(ci);+ )+ )+ vmcase(OP_LT,+ Protect(+ if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i))+ ci->u.l.savedpc++;+ else+ donextjump(ci);+ )+ )+ vmcase(OP_LE,+ Protect(+ if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i))+ ci->u.l.savedpc++;+ else+ donextjump(ci);+ )+ )+ vmcase(OP_TEST,+ if (GETARG_C(i) ? l_isfalse(ra) : !l_isfalse(ra))+ ci->u.l.savedpc++;+ else+ donextjump(ci);+ )+ vmcase(OP_TESTSET,+ TValue *rb = RB(i);+ if (GETARG_C(i) ? l_isfalse(rb) : !l_isfalse(rb))+ ci->u.l.savedpc++;+ else {+ setobjs2s(L, ra, rb);+ donextjump(ci);+ }+ )+ vmcase(OP_CALL,+ int b = GETARG_B(i);+ int nresults = GETARG_C(i) - 1;+ if (b != 0) L->top = ra+b; /* else previous instruction set top */+ if (luaD_precall(L, ra, nresults)) { /* C function? */+ if (nresults >= 0) L->top = ci->top; /* adjust results */+ base = ci->u.l.base;+ }+ else { /* Lua function */+ ci = L->ci;+ ci->callstatus |= CIST_REENTRY;+ goto newframe; /* restart luaV_execute over new Lua function */+ }+ )+ vmcase(OP_TAILCALL,+ int b = GETARG_B(i);+ if (b != 0) L->top = ra+b; /* else previous instruction set top */+ lua_assert(GETARG_C(i) - 1 == LUA_MULTRET);+ if (luaD_precall(L, ra, LUA_MULTRET)) /* C function? */+ base = ci->u.l.base;+ else {+ /* tail call: put called frame (n) in place of caller one (o) */+ CallInfo *nci = L->ci; /* called frame */+ CallInfo *oci = nci->previous; /* caller frame */+ StkId nfunc = nci->func; /* called function */+ StkId ofunc = oci->func; /* caller function */+ /* last stack slot filled by 'precall' */+ StkId lim = nci->u.l.base + getproto(nfunc)->numparams;+ int aux;+ /* close all upvalues from previous call */+ if (cl->p->sizep > 0) luaF_close(L, oci->u.l.base);+ /* move new frame into old one */+ for (aux = 0; nfunc + aux < lim; aux++)+ setobjs2s(L, ofunc + aux, nfunc + aux);+ oci->u.l.base = ofunc + (nci->u.l.base - nfunc); /* correct base */+ oci->top = L->top = ofunc + (L->top - nfunc); /* correct top */+ oci->u.l.savedpc = nci->u.l.savedpc;+ oci->callstatus |= CIST_TAIL; /* function was tail called */+ ci = L->ci = oci; /* remove new frame */+ lua_assert(L->top == oci->u.l.base + getproto(ofunc)->maxstacksize);+ goto newframe; /* restart luaV_execute over new Lua function */+ }+ )+ vmcasenb(OP_RETURN,+ int b = GETARG_B(i);+ if (b != 0) L->top = ra+b-1;+ if (cl->p->sizep > 0) luaF_close(L, base);+ b = luaD_poscall(L, ra);+ if (!(ci->callstatus & CIST_REENTRY)) /* 'ci' still the called one */+ return; /* external invocation: return */+ else { /* invocation via reentry: continue execution */+ ci = L->ci;+ if (b) L->top = ci->top;+ lua_assert(isLua(ci));+ lua_assert(GET_OPCODE(*((ci)->u.l.savedpc - 1)) == OP_CALL);+ goto newframe; /* restart luaV_execute over new Lua function */+ }+ )+ vmcase(OP_FORLOOP,+ lua_Number step = nvalue(ra+2);+ lua_Number prev = nvalue(ra); /* index before increment */+ lua_Number idx = luai_numadd(L, prev, step); /* increment index */+ lua_Number limit = nvalue(ra+1);+ /* fix32 addition wraps on overflow. Detect when idx wrapped past the+ representable range: for a positive step idx should never decrease,+ and for a negative step it should never increase. When a wrap is+ detected AND prev was still inside the loop bounds, the loop is+ done (we overflowed past the limit rather than wrapping back to+ init as FORPREP does for loops starting at FIX32_MIN). */+ int wrapped = luai_numlt(L, 0, step)+ ? (luai_numlt(L, idx, prev) && luai_numle(L, prev, limit))+ : (luai_numlt(L, prev, idx) && luai_numle(L, limit, prev));+ if (!wrapped && (luai_numlt(L, 0, step) ? luai_numle(L, idx, limit)+ : luai_numle(L, limit, idx))) {+ ci->u.l.savedpc += GETARG_sBx(i); /* jump back */+ setnvalue(ra, idx); /* update internal index... */+ setnvalue(ra+3, idx); /* ...and external index */+ }+ )+ vmcase(OP_FORPREP,+ const TValue *init = ra;+ const TValue *plimit = ra+1;+ const TValue *pstep = ra+2;+ if (!tonumber(init, ra))+ luaG_runerror(L, LUA_QL("for") " initial value must be a number");+ else if (!tonumber(plimit, ra+1))+ luaG_runerror(L, LUA_QL("for") " limit must be a number");+ else if (!tonumber(pstep, ra+2))+ luaG_runerror(L, LUA_QL("for") " step must be a number");+ setnvalue(ra, luai_numsub(L, nvalue(ra), nvalue(pstep)));+ ci->u.l.savedpc += GETARG_sBx(i);+ )+ vmcasenb(OP_TFORCALL,+ StkId cb = ra + 3; /* call base */+ setobjs2s(L, cb+2, ra+2);+ setobjs2s(L, cb+1, ra+1);+ setobjs2s(L, cb, ra);+ L->top = cb + 3; /* func. + 2 args (state and index) */+ Protect(luaD_call(L, cb, GETARG_C(i), 1));+ L->top = ci->top;+ i = *(ci->u.l.savedpc++); /* go to next instruction */+ ra = RA(i);+ lua_assert(GET_OPCODE(i) == OP_TFORLOOP);+ goto l_tforloop;+ )+ vmcase(OP_TFORLOOP,+ l_tforloop:+ if (!ttisnil(ra + 1)) { /* continue loop? */+ setobjs2s(L, ra, ra + 1); /* save control variable */+ ci->u.l.savedpc += GETARG_sBx(i); /* jump back */+ }+ )+ vmcase(OP_SETLIST,+ int n = GETARG_B(i);+ int c = GETARG_C(i);+ int last;+ Table *h;+ if (n == 0) n = cast_int(L->top - ra) - 1;+ if (c == 0) {+ lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);+ c = GETARG_Ax(*ci->u.l.savedpc++);+ }+ luai_runtimecheck(L, ttistable(ra));+ h = hvalue(ra);+ last = ((c-1)*LFIELDS_PER_FLUSH) + n;+ if (last > h->sizearray) /* needs more space? */+ luaH_resizearray(L, h, last); /* pre-allocate it at once */+ for (; n > 0; n--) {+ TValue *val = ra+n;+ luaH_setint(L, h, last--, val);+ luaC_barrierback(L, obj2gco(h), val);+ }+ L->top = ci->top; /* correct top (in case of previous open call) */+ )+ vmcase(OP_CLOSURE,+ Proto *p = cl->p->p[GETARG_Bx(i)];+ Closure *ncl = getcached(p, cl->upvals, base); /* cached closure */+ if (ncl == NULL) /* no match? */+ pushclosure(L, p, cl->upvals, base, ra); /* create a new one */+ else+ setclLvalue(L, ra, ncl); /* push cashed closure */+ checkGC(L, ra + 1);+ )+ vmcase(OP_VARARG,+ int b = GETARG_B(i) - 1;+ int j;+ int n = cast_int(base - ci->func) - cl->p->numparams - 1;+ if (b < 0) { /* B == 0? */+ b = n; /* get all var. arguments */+ Protect(luaD_checkstack(L, n));+ ra = RA(i); /* previous call may change the stack */+ L->top = ra + n;+ }+ for (j = 0; j < b; j++) {+ if (j < n) {+ setobjs2s(L, ra + j, base - n + j);+ }+ else {+ setnilvalue(ra + j);+ }+ }+ )+ vmcase(OP_EXTRAARG,+ lua_assert(0);+ )+ }+ }+}+diff --git a/games/numpico/src/femto8/lua/lvm.h b/games/numpico/src/femto8/lua/lvm.hnew file mode 100644index 00000000..920c64bb--- /dev/null+++ b/games/numpico/src/femto8/lua/lvm.h@@ -0,0 +1,45 @@+/*+** $Id: lvm.h,v 2.18 2013/01/08 14:06:55 roberto Exp $+** Lua virtual machine+** See Copyright Notice in lua.h+*/++#ifndef lvm_h+#define lvm_h+++#include "ldo.h"+#include "lobject.h"+#include "ltm.h"+++#define tostring(L,o) (ttisstring(o) || (luaV_tostring(L, o)))++#define tonumber(o,n) (ttisnumber(o) || (((o) = luaV_tonumber(o,n)) != NULL))++#define equalobj(L,o1,o2) (ttisequal(o1, o2) && luaV_equalobj_(L, o1, o2))++#define luaV_rawequalobj(o1,o2) equalobj(NULL,o1,o2)+++/* not to called directly */+LUAI_FUNC int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2);+++LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);+LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r);+LUAI_FUNC const TValue *luaV_tonumber (const TValue *obj, TValue *n);+LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj);+LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key,+ StkId val);+LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key,+ StkId val);+LUAI_FUNC void luaV_finishOp (lua_State *L);+LUAI_FUNC void luaV_execute (lua_State *L);+LUAI_FUNC void luaV_concat (lua_State *L, int total);+LUAI_FUNC void luaV_arith (lua_State *L, StkId ra, const TValue *rb,+ const TValue *rc, TMS op);+LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb);++LUAI_FUNC lua_Number luaV_peek(struct lua_State *L, lua_Number a, int count);+#endifdiff --git a/games/numpico/src/femto8/lua/lzio.c b/games/numpico/src/femto8/lua/lzio.cnew file mode 100644index 00000000..8b77054e--- /dev/null+++ b/games/numpico/src/femto8/lua/lzio.c@@ -0,0 +1,76 @@+/*+** $Id: lzio.c,v 1.35 2012/05/14 13:34:18 roberto Exp $+** Buffered streams+** See Copyright Notice in lua.h+*/+++#include <string.h>++#define lzio_c+#define LUA_CORE++#include "lua.h"++#include "llimits.h"+#include "lmem.h"+#include "lstate.h"+#include "lzio.h"+++int luaZ_fill (ZIO *z) {+ size_t size;+ lua_State *L = z->L;+ const char *buff;+ lua_unlock(L);+ buff = z->reader(L, z->data, &size);+ lua_lock(L);+ if (buff == NULL || size == 0)+ return EOZ;+ z->n = size - 1; /* discount char being returned */+ z->p = buff;+ return cast_uchar(*(z->p++));+}+++void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {+ z->L = L;+ z->reader = reader;+ z->data = data;+ z->n = 0;+ z->p = NULL;+}+++/* --------------------------------------------------------------- read --- */+size_t luaZ_read (ZIO *z, void *b, size_t n) {+ while (n) {+ size_t m;+ if (z->n == 0) { /* no bytes in buffer? */+ if (luaZ_fill(z) == EOZ) /* try to read more */+ return n; /* no more input; return number of missing bytes */+ else {+ z->n++; /* luaZ_fill consumed first byte; put it back */+ z->p--;+ }+ }+ m = (n <= z->n) ? n : z->n; /* min. between n and z->n */+ memcpy(b, z->p, m);+ z->n -= m;+ z->p += m;+ b = (char *)b + m;+ n -= m;+ }+ return 0;+}++/* ------------------------------------------------------------------------ */+char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n) {+ if (n > buff->buffsize) {+ if (n < LUA_MINBUFFER) n = LUA_MINBUFFER;+ luaZ_resizebuffer(L, buff, n);+ }+ return buff->buffer;+}++diff --git a/games/numpico/src/femto8/lua/lzio.h b/games/numpico/src/femto8/lua/lzio.hnew file mode 100644index 00000000..08682301--- /dev/null+++ b/games/numpico/src/femto8/lua/lzio.h@@ -0,0 +1,65 @@+/*+** $Id: lzio.h,v 1.26 2011/07/15 12:48:03 roberto Exp $+** Buffered streams+** See Copyright Notice in lua.h+*/+++#ifndef lzio_h+#define lzio_h++#include "lua.h"++#include "lmem.h"+++#define EOZ (-1) /* end of stream */++typedef struct Zio ZIO;++#define zgetc(z) (((z)->n--)>0 ? cast_uchar(*(z)->p++) : luaZ_fill(z))+++typedef struct Mbuffer {+ char *buffer;+ size_t n;+ size_t buffsize;+} Mbuffer;++#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0)++#define luaZ_buffer(buff) ((buff)->buffer)+#define luaZ_sizebuffer(buff) ((buff)->buffsize)+#define luaZ_bufflen(buff) ((buff)->n)++#define luaZ_resetbuffer(buff) ((buff)->n = 0)+++#define luaZ_resizebuffer(L, buff, size) \+ (luaM_reallocvector(L, (buff)->buffer, (buff)->buffsize, size, char), \+ (buff)->buffsize = size)++#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0)+++LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n);+LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader,+ void *data);+LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n); /* read next n bytes */++++/* --------- Private Part ------------------ */++struct Zio {+ size_t n; /* bytes still unread */+ const char *p; /* current position in buffer */+ lua_Reader reader; /* reader function */+ void* data; /* additional data */+ lua_State *L; /* Lua state (for reader) */+};+++LUAI_FUNC int luaZ_fill (ZIO *z);++#endifdiff --git a/games/numpico/src/femto8/lua/trigtables.h b/games/numpico/src/femto8/lua/trigtables.hnew file mode 100644index 00000000..d7615616--- /dev/null+++ b/games/numpico/src/femto8/lua/trigtables.h@@ -0,0 +1,412 @@+//+// ZEPTO-8 — Fantasy console emulator+//+// Copyright © 2016–2024 Sam Hocevar <[email protected]>+//+// This program is free software. It comes without any warranty, to+// the extent permitted by applicable law. You can redistribute it+// and/or modify it under the terms of the Do What the Fuck You Want+// to Public License, Version 2, as published by the WTFPL Task Force.+// See http://www.wtfpl.net/ for more details.+//+++#include <ctype.h>++// This table was generated using the following PICO-8 code:+// for i = 0,0.25,0x.0004 do x = i * -4 - sin(i) printh('0x'..sub(tostr(x,1),8,11)..', ') end+static uint16_t sintable[] =+{+ 0x0000, 0x0009, 0x0012, 0x001b, 0x0025, 0x002e, 0x0037, 0x0040, 0x0049, 0x0052, 0x005b, 0x0064, 0x006e, 0x0077, 0x0080, 0x0089,+ 0x0092, 0x009b, 0x00a4, 0x00ae, 0x00b7, 0x00c0, 0x00c9, 0x00d2, 0x00db, 0x00e4, 0x00ed, 0x00f7, 0x0100, 0x0109, 0x0112, 0x011b,+ 0x0124, 0x012d, 0x0136, 0x0140, 0x0149, 0x0152, 0x015b, 0x0164, 0x016d, 0x0176, 0x0180, 0x0189, 0x0192, 0x019b, 0x01a4, 0x01ad,+ 0x01b6, 0x01bf, 0x01c9, 0x01d2, 0x01db, 0x01e4, 0x01ed, 0x01f6, 0x01ff, 0x0208, 0x0212, 0x021b, 0x0224, 0x022d, 0x0236, 0x023f,+ 0x0248, 0x0251, 0x025b, 0x0264, 0x026d, 0x0276, 0x027f, 0x0288, 0x0291, 0x029a, 0x02a4, 0x02ad, 0x02b6, 0x02bf, 0x02c8, 0x02d1,+ 0x02da, 0x02e3, 0x02ed, 0x02f6, 0x02ff, 0x0308, 0x0311, 0x031a, 0x0323, 0x032c, 0x0335, 0x033f, 0x0348, 0x0351, 0x035a, 0x0363,+ 0x036c, 0x0375, 0x037e, 0x0388, 0x0391, 0x039a, 0x03a3, 0x03ac, 0x03b5, 0x03be, 0x03c7, 0x03d0, 0x03da, 0x03e3, 0x03ec, 0x03f5,+ 0x03fe, 0x0407, 0x0410, 0x0419, 0x0422, 0x042c, 0x0435, 0x043e, 0x0447, 0x0450, 0x0459, 0x0462, 0x046b, 0x0474, 0x047d, 0x0487,+ 0x0490, 0x0499, 0x04a2, 0x04ab, 0x04b4, 0x04bd, 0x04c6, 0x04cf, 0x04d9, 0x04e2, 0x04eb, 0x04f4, 0x04fd, 0x0506, 0x050f, 0x0518,+ 0x0521, 0x052a, 0x0533, 0x053d, 0x0546, 0x054f, 0x0558, 0x0561, 0x056a, 0x0573, 0x057c, 0x0585, 0x058e, 0x0597, 0x05a1, 0x05aa,+ 0x05b3, 0x05bc, 0x05c5, 0x05ce, 0x05d7, 0x05e0, 0x05e9, 0x05f2, 0x05fb, 0x0604, 0x060e, 0x0617, 0x0620, 0x0629, 0x0632, 0x063b,+ 0x0644, 0x064d, 0x0656, 0x065f, 0x0668, 0x0671, 0x067a, 0x0684, 0x068d, 0x0696, 0x069f, 0x06a8, 0x06b1, 0x06ba, 0x06c3, 0x06cc,+ 0x06d5, 0x06de, 0x06e7, 0x06f0, 0x06f9, 0x0702, 0x070c, 0x0715, 0x071e, 0x0727, 0x0730, 0x0739, 0x0742, 0x074b, 0x0754, 0x075d,+ 0x0766, 0x076f, 0x0778, 0x0781, 0x078a, 0x0793, 0x079c, 0x07a5, 0x07ae, 0x07b8, 0x07c1, 0x07ca, 0x07d3, 0x07dc, 0x07e5, 0x07ee,+ 0x07f7, 0x0800, 0x0809, 0x0812, 0x081b, 0x0824, 0x082d, 0x0836, 0x083f, 0x0848, 0x0851, 0x085a, 0x0863, 0x086c, 0x0875, 0x087e,+ 0x0887, 0x0890, 0x0899, 0x08a2, 0x08ab, 0x08b4, 0x08bd, 0x08c7, 0x08d0, 0x08d9, 0x08e2, 0x08eb, 0x08f4, 0x08fd, 0x0906, 0x090f,+ 0x0918, 0x0921, 0x092a, 0x0933, 0x093c, 0x0945, 0x094e, 0x0957, 0x0960, 0x0969, 0x0972, 0x097b, 0x0984, 0x098d, 0x0996, 0x099f,+ 0x09a8, 0x09b1, 0x09ba, 0x09c3, 0x09cc, 0x09d5, 0x09de, 0x09e7, 0x09f0, 0x09f9, 0x0a02, 0x0a0b, 0x0a14, 0x0a1d, 0x0a26, 0x0a2f,+ 0x0a38, 0x0a41, 0x0a49, 0x0a52, 0x0a5b, 0x0a64, 0x0a6d, 0x0a76, 0x0a7f, 0x0a88, 0x0a91, 0x0a9a, 0x0aa3, 0x0aac, 0x0ab5, 0x0abe,+ 0x0ac7, 0x0ad0, 0x0ad9, 0x0ae2, 0x0aeb, 0x0af4, 0x0afd, 0x0b06, 0x0b0f, 0x0b18, 0x0b21, 0x0b2a, 0x0b33, 0x0b3b, 0x0b44, 0x0b4d,+ 0x0b56, 0x0b5f, 0x0b68, 0x0b71, 0x0b7a, 0x0b83, 0x0b8c, 0x0b95, 0x0b9e, 0x0ba7, 0x0bb0, 0x0bb9, 0x0bc2, 0x0bca, 0x0bd3, 0x0bdc,+ 0x0be5, 0x0bee, 0x0bf7, 0x0c00, 0x0c09, 0x0c12, 0x0c1b, 0x0c24, 0x0c2d, 0x0c36, 0x0c3e, 0x0c47, 0x0c50, 0x0c59, 0x0c62, 0x0c6b,+ 0x0c74, 0x0c7d, 0x0c86, 0x0c8f, 0x0c97, 0x0ca0, 0x0ca9, 0x0cb2, 0x0cbb, 0x0cc4, 0x0ccd, 0x0cd6, 0x0cdf, 0x0ce8, 0x0cf0, 0x0cf9,+ 0x0d02, 0x0d0b, 0x0d14, 0x0d1d, 0x0d26, 0x0d2f, 0x0d37, 0x0d40, 0x0d49, 0x0d52, 0x0d5b, 0x0d64, 0x0d6d, 0x0d76, 0x0d7e, 0x0d87,+ 0x0d90, 0x0d99, 0x0da2, 0x0dab, 0x0db4, 0x0dbc, 0x0dc5, 0x0dce, 0x0dd7, 0x0de0, 0x0de9, 0x0df2, 0x0dfa, 0x0e03, 0x0e0c, 0x0e15,+ 0x0e1e, 0x0e27, 0x0e2f, 0x0e38, 0x0e41, 0x0e4a, 0x0e53, 0x0e5c, 0x0e64, 0x0e6d, 0x0e76, 0x0e7f, 0x0e88, 0x0e90, 0x0e99, 0x0ea2,+ 0x0eab, 0x0eb4, 0x0ebd, 0x0ec5, 0x0ece, 0x0ed7, 0x0ee0, 0x0ee9, 0x0ef1, 0x0efa, 0x0f03, 0x0f0c, 0x0f15, 0x0f1d, 0x0f26, 0x0f2f,+ 0x0f38, 0x0f41, 0x0f49, 0x0f52, 0x0f5b, 0x0f64, 0x0f6c, 0x0f75, 0x0f7e, 0x0f87, 0x0f90, 0x0f98, 0x0fa1, 0x0faa, 0x0fb3, 0x0fbb,+ 0x0fc4, 0x0fcd, 0x0fd6, 0x0fde, 0x0fe7, 0x0ff0, 0x0ff9, 0x1001, 0x100a, 0x1013, 0x101c, 0x1024, 0x102d, 0x1036, 0x103f, 0x1047,+ 0x1050, 0x1059, 0x1062, 0x106a, 0x1073, 0x107c, 0x1085, 0x108d, 0x1096, 0x109f, 0x10a7, 0x10b0, 0x10b9, 0x10c2, 0x10ca, 0x10d3,+ 0x10dc, 0x10e4, 0x10ed, 0x10f6, 0x10ff, 0x1107, 0x1110, 0x1119, 0x1121, 0x112a, 0x1133, 0x113b, 0x1144, 0x114d, 0x1155, 0x115e,+ 0x1167, 0x116f, 0x1178, 0x1181, 0x118a, 0x1192, 0x119b, 0x11a4, 0x11ac, 0x11b5, 0x11be, 0x11c6, 0x11cf, 0x11d7, 0x11e0, 0x11e9,+ 0x11f1, 0x11fa, 0x1203, 0x120b, 0x1214, 0x121d, 0x1225, 0x122e, 0x1237, 0x123f, 0x1248, 0x1250, 0x1259, 0x1262, 0x126a, 0x1273,+ 0x127c, 0x1284, 0x128d, 0x1295, 0x129e, 0x12a7, 0x12af, 0x12b8, 0x12c0, 0x12c9, 0x12d2, 0x12da, 0x12e3, 0x12eb, 0x12f4, 0x12fd,+ 0x1305, 0x130e, 0x1316, 0x131f, 0x1328, 0x1330, 0x1339, 0x1341, 0x134a, 0x1352, 0x135b, 0x1364, 0x136c, 0x1375, 0x137d, 0x1386,+ 0x138e, 0x1397, 0x13a0, 0x13a8, 0x13b1, 0x13b9, 0x13c2, 0x13ca, 0x13d3, 0x13db, 0x13e4, 0x13ec, 0x13f5, 0x13fd, 0x1406, 0x140e,+ 0x1417, 0x1420, 0x1428, 0x1431, 0x1439, 0x1442, 0x144a, 0x1453, 0x145b, 0x1464, 0x146c, 0x1475, 0x147d, 0x1486, 0x148e, 0x1497,+ 0x149f, 0x14a8, 0x14b0, 0x14b9, 0x14c1, 0x14ca, 0x14d2, 0x14da, 0x14e3, 0x14eb, 0x14f4, 0x14fc, 0x1505, 0x150d, 0x1516, 0x151e,+ 0x1527, 0x152f, 0x1538, 0x1540, 0x1548, 0x1551, 0x1559, 0x1562, 0x156a, 0x1573, 0x157b, 0x1583, 0x158c, 0x1594, 0x159d, 0x15a5,+ 0x15ae, 0x15b6, 0x15be, 0x15c7, 0x15cf, 0x15d8, 0x15e0, 0x15e8, 0x15f1, 0x15f9, 0x1602, 0x160a, 0x1612, 0x161b, 0x1623, 0x162c,+ 0x1634, 0x163c, 0x1645, 0x164d, 0x1655, 0x165e, 0x1666, 0x166f, 0x1677, 0x167f, 0x1688, 0x1690, 0x1698, 0x16a1, 0x16a9, 0x16b1,+ 0x16ba, 0x16c2, 0x16ca, 0x16d3, 0x16db, 0x16e3, 0x16ec, 0x16f4, 0x16fc, 0x1705, 0x170d, 0x1715, 0x171e, 0x1726, 0x172e, 0x1737,+ 0x173f, 0x1747, 0x174f, 0x1758, 0x1760, 0x1768, 0x1771, 0x1779, 0x1781, 0x178a, 0x1792, 0x179a, 0x17a2, 0x17ab, 0x17b3, 0x17bb,+ 0x17c3, 0x17cc, 0x17d4, 0x17dc, 0x17e4, 0x17ed, 0x17f5, 0x17fd, 0x1805, 0x180e, 0x1816, 0x181e, 0x1826, 0x182f, 0x1837, 0x183f,+ 0x1847, 0x1850, 0x1858, 0x1860, 0x1868, 0x1870, 0x1879, 0x1881, 0x1889, 0x1891, 0x1899, 0x18a2, 0x18aa, 0x18b2, 0x18ba, 0x18c2,+ 0x18cb, 0x18d3, 0x18db, 0x18e3, 0x18eb, 0x18f3, 0x18fc, 0x1904, 0x190c, 0x1914, 0x191c, 0x1924, 0x192c, 0x1935, 0x193d, 0x1945,+ 0x194d, 0x1955, 0x195d, 0x1965, 0x196e, 0x1976, 0x197e, 0x1986, 0x198e, 0x1996, 0x199e, 0x19a6, 0x19af, 0x19b7, 0x19bf, 0x19c7,+ 0x19cf, 0x19d7, 0x19df, 0x19e7, 0x19ef, 0x19f7, 0x19ff, 0x1a08, 0x1a10, 0x1a18, 0x1a20, 0x1a28, 0x1a30, 0x1a38, 0x1a40, 0x1a48,+ 0x1a50, 0x1a58, 0x1a60, 0x1a68, 0x1a70, 0x1a78, 0x1a80, 0x1a88, 0x1a90, 0x1a98, 0x1aa0, 0x1aa8, 0x1ab1, 0x1ab9, 0x1ac1, 0x1ac9,+ 0x1ad1, 0x1ad9, 0x1ae1, 0x1ae9, 0x1af1, 0x1af9, 0x1b01, 0x1b09, 0x1b10, 0x1b18, 0x1b20, 0x1b28, 0x1b30, 0x1b38, 0x1b40, 0x1b48,+ 0x1b50, 0x1b58, 0x1b60, 0x1b68, 0x1b70, 0x1b78, 0x1b80, 0x1b88, 0x1b90, 0x1b98, 0x1ba0, 0x1ba8, 0x1bb0, 0x1bb7, 0x1bbf, 0x1bc7,+ 0x1bcf, 0x1bd7, 0x1bdf, 0x1be7, 0x1bef, 0x1bf7, 0x1bff, 0x1c07, 0x1c0e, 0x1c16, 0x1c1e, 0x1c26, 0x1c2e, 0x1c36, 0x1c3e, 0x1c46,+ 0x1c4d, 0x1c55, 0x1c5d, 0x1c65, 0x1c6d, 0x1c75, 0x1c7d, 0x1c84, 0x1c8c, 0x1c94, 0x1c9c, 0x1ca4, 0x1cac, 0x1cb3, 0x1cbb, 0x1cc3,+ 0x1ccb, 0x1cd3, 0x1cdb, 0x1ce2, 0x1cea, 0x1cf2, 0x1cfa, 0x1d02, 0x1d09, 0x1d11, 0x1d19, 0x1d21, 0x1d28, 0x1d30, 0x1d38, 0x1d40,+ 0x1d48, 0x1d4f, 0x1d57, 0x1d5f, 0x1d67, 0x1d6e, 0x1d76, 0x1d7e, 0x1d86, 0x1d8d, 0x1d95, 0x1d9d, 0x1da4, 0x1dac, 0x1db4, 0x1dbc,+ 0x1dc3, 0x1dcb, 0x1dd3, 0x1ddb, 0x1de2, 0x1dea, 0x1df2, 0x1df9, 0x1e01, 0x1e09, 0x1e10, 0x1e18, 0x1e20, 0x1e27, 0x1e2f, 0x1e37,+ 0x1e3e, 0x1e46, 0x1e4e, 0x1e55, 0x1e5d, 0x1e65, 0x1e6c, 0x1e74, 0x1e7c, 0x1e83, 0x1e8b, 0x1e93, 0x1e9a, 0x1ea2, 0x1ea9, 0x1eb1,+ 0x1eb9, 0x1ec0, 0x1ec8, 0x1ecf, 0x1ed7, 0x1edf, 0x1ee6, 0x1eee, 0x1ef5, 0x1efd, 0x1f05, 0x1f0c, 0x1f14, 0x1f1b, 0x1f23, 0x1f2a,+ 0x1f32, 0x1f3a, 0x1f41, 0x1f49, 0x1f50, 0x1f58, 0x1f5f, 0x1f67, 0x1f6e, 0x1f76, 0x1f7d, 0x1f85, 0x1f8c, 0x1f94, 0x1f9b, 0x1fa3,+ 0x1faa, 0x1fb2, 0x1fb9, 0x1fc1, 0x1fc8, 0x1fd0, 0x1fd7, 0x1fdf, 0x1fe6, 0x1fee, 0x1ff5, 0x1ffd, 0x2004, 0x200c, 0x2013, 0x201b,+ 0x2022, 0x202a, 0x2031, 0x2038, 0x2040, 0x2047, 0x204f, 0x2056, 0x205e, 0x2065, 0x206c, 0x2074, 0x207b, 0x2083, 0x208a, 0x2091,+ 0x2099, 0x20a0, 0x20a8, 0x20af, 0x20b6, 0x20be, 0x20c5, 0x20cc, 0x20d4, 0x20db, 0x20e3, 0x20ea, 0x20f1, 0x20f9, 0x2100, 0x2107,+ 0x210f, 0x2116, 0x211d, 0x2125, 0x212c, 0x2133, 0x213b, 0x2142, 0x2149, 0x2151, 0x2158, 0x215f, 0x2166, 0x216e, 0x2175, 0x217c,+ 0x2184, 0x218b, 0x2192, 0x2199, 0x21a1, 0x21a8, 0x21af, 0x21b6, 0x21be, 0x21c5, 0x21cc, 0x21d3, 0x21db, 0x21e2, 0x21e9, 0x21f0,+ 0x21f8, 0x21ff, 0x2206, 0x220d, 0x2214, 0x221c, 0x2223, 0x222a, 0x2231, 0x2238, 0x2240, 0x2247, 0x224e, 0x2255, 0x225c, 0x2263,+ 0x226b, 0x2272, 0x2279, 0x2280, 0x2287, 0x228e, 0x2295, 0x229d, 0x22a4, 0x22ab, 0x22b2, 0x22b9, 0x22c0, 0x22c7, 0x22ce, 0x22d6,+ 0x22dd, 0x22e4, 0x22eb, 0x22f2, 0x22f9, 0x2300, 0x2307, 0x230e, 0x2315, 0x231c, 0x2323, 0x232b, 0x2332, 0x2339, 0x2340, 0x2347,+ 0x234e, 0x2355, 0x235c, 0x2363, 0x236a, 0x2371, 0x2378, 0x237f, 0x2386, 0x238d, 0x2394, 0x239b, 0x23a2, 0x23a9, 0x23b0, 0x23b7,+ 0x23be, 0x23c5, 0x23cc, 0x23d3, 0x23da, 0x23e1, 0x23e8, 0x23ef, 0x23f6, 0x23fd, 0x2403, 0x240a, 0x2411, 0x2418, 0x241f, 0x2426,+ 0x242d, 0x2434, 0x243b, 0x2442, 0x2449, 0x2450, 0x2456, 0x245d, 0x2464, 0x246b, 0x2472, 0x2479, 0x2480, 0x2487, 0x248d, 0x2494,+ 0x249b, 0x24a2, 0x24a9, 0x24b0, 0x24b6, 0x24bd, 0x24c4, 0x24cb, 0x24d2, 0x24d9, 0x24df, 0x24e6, 0x24ed, 0x24f4, 0x24fb, 0x2501,+ 0x2508, 0x250f, 0x2516, 0x251d, 0x2523, 0x252a, 0x2531, 0x2538, 0x253e, 0x2545, 0x254c, 0x2553, 0x2559, 0x2560, 0x2567, 0x256e,+ 0x2574, 0x257b, 0x2582, 0x2588, 0x258f, 0x2596, 0x259c, 0x25a3, 0x25aa, 0x25b1, 0x25b7, 0x25be, 0x25c5, 0x25cb, 0x25d2, 0x25d9,+ 0x25df, 0x25e6, 0x25ed, 0x25f3, 0x25fa, 0x2600, 0x2607, 0x260e, 0x2614, 0x261b, 0x2622, 0x2628, 0x262f, 0x2635, 0x263c, 0x2643,+ 0x2649, 0x2650, 0x2656, 0x265d, 0x2663, 0x266a, 0x2671, 0x2677, 0x267e, 0x2684, 0x268b, 0x2691, 0x2698, 0x269e, 0x26a5, 0x26ab,+ 0x26b2, 0x26b9, 0x26bf, 0x26c6, 0x26cc, 0x26d3, 0x26d9, 0x26e0, 0x26e6, 0x26ec, 0x26f3, 0x26f9, 0x2700, 0x2706, 0x270d, 0x2713,+ 0x271a, 0x2720, 0x2727, 0x272d, 0x2733, 0x273a, 0x2740, 0x2747, 0x274d, 0x2754, 0x275a, 0x2760, 0x2767, 0x276d, 0x2774, 0x277a,+ 0x2780, 0x2787, 0x278d, 0x2793, 0x279a, 0x27a0, 0x27a7, 0x27ad, 0x27b3, 0x27ba, 0x27c0, 0x27c6, 0x27cd, 0x27d3, 0x27d9, 0x27e0,+ 0x27e6, 0x27ec, 0x27f2, 0x27f9, 0x27ff, 0x2805, 0x280c, 0x2812, 0x2818, 0x281e, 0x2825, 0x282b, 0x2831, 0x2838, 0x283e, 0x2844,+ 0x284a, 0x2850, 0x2857, 0x285d, 0x2863, 0x2869, 0x2870, 0x2876, 0x287c, 0x2882, 0x2888, 0x288f, 0x2895, 0x289b, 0x28a1, 0x28a7,+ 0x28ad, 0x28b4, 0x28ba, 0x28c0, 0x28c6, 0x28cc, 0x28d2, 0x28d9, 0x28df, 0x28e5, 0x28eb, 0x28f1, 0x28f7, 0x28fd, 0x2903, 0x2909,+ 0x2910, 0x2916, 0x291c, 0x2922, 0x2928, 0x292e, 0x2934, 0x293a, 0x2940, 0x2946, 0x294c, 0x2952, 0x2958, 0x295e, 0x2964, 0x296a,+ 0x2970, 0x2976, 0x297c, 0x2982, 0x2988, 0x298e, 0x2994, 0x299a, 0x29a0, 0x29a6, 0x29ac, 0x29b2, 0x29b8, 0x29be, 0x29c4, 0x29ca,+ 0x29d0, 0x29d6, 0x29dc, 0x29e2, 0x29e8, 0x29ee, 0x29f4, 0x29fa, 0x29ff, 0x2a05, 0x2a0b, 0x2a11, 0x2a17, 0x2a1d, 0x2a23, 0x2a29,+ 0x2a2f, 0x2a34, 0x2a3a, 0x2a40, 0x2a46, 0x2a4c, 0x2a52, 0x2a58, 0x2a5d, 0x2a63, 0x2a69, 0x2a6f, 0x2a75, 0x2a7a, 0x2a80, 0x2a86,+ 0x2a8c, 0x2a92, 0x2a97, 0x2a9d, 0x2aa3, 0x2aa9, 0x2aaf, 0x2ab4, 0x2aba, 0x2ac0, 0x2ac6, 0x2acb, 0x2ad1, 0x2ad7, 0x2adc, 0x2ae2,+ 0x2ae8, 0x2aee, 0x2af3, 0x2af9, 0x2aff, 0x2b04, 0x2b0a, 0x2b10, 0x2b15, 0x2b1b, 0x2b21, 0x2b26, 0x2b2c, 0x2b32, 0x2b37, 0x2b3d,+ 0x2b43, 0x2b48, 0x2b4e, 0x2b54, 0x2b59, 0x2b5f, 0x2b64, 0x2b6a, 0x2b70, 0x2b75, 0x2b7b, 0x2b80, 0x2b86, 0x2b8c, 0x2b91, 0x2b97,+ 0x2b9c, 0x2ba2, 0x2ba7, 0x2bad, 0x2bb2, 0x2bb8, 0x2bbd, 0x2bc3, 0x2bc9, 0x2bce, 0x2bd4, 0x2bd9, 0x2bdf, 0x2be4, 0x2bea, 0x2bef,+ 0x2bf5, 0x2bfa, 0x2bff, 0x2c05, 0x2c0a, 0x2c10, 0x2c15, 0x2c1b, 0x2c20, 0x2c26, 0x2c2b, 0x2c30, 0x2c36, 0x2c3b, 0x2c41, 0x2c46,+ 0x2c4c, 0x2c51, 0x2c56, 0x2c5c, 0x2c61, 0x2c66, 0x2c6c, 0x2c71, 0x2c77, 0x2c7c, 0x2c81, 0x2c87, 0x2c8c, 0x2c91, 0x2c97, 0x2c9c,+ 0x2ca1, 0x2ca7, 0x2cac, 0x2cb1, 0x2cb6, 0x2cbc, 0x2cc1, 0x2cc6, 0x2ccc, 0x2cd1, 0x2cd6, 0x2cdb, 0x2ce1, 0x2ce6, 0x2ceb, 0x2cf0,+ 0x2cf6, 0x2cfb, 0x2d00, 0x2d05, 0x2d0a, 0x2d10, 0x2d15, 0x2d1a, 0x2d1f, 0x2d24, 0x2d2a, 0x2d2f, 0x2d34, 0x2d39, 0x2d3e, 0x2d44,+ 0x2d49, 0x2d4e, 0x2d53, 0x2d58, 0x2d5d, 0x2d62, 0x2d67, 0x2d6d, 0x2d72, 0x2d77, 0x2d7c, 0x2d81, 0x2d86, 0x2d8b, 0x2d90, 0x2d95,+ 0x2d9a, 0x2d9f, 0x2da5, 0x2daa, 0x2daf, 0x2db4, 0x2db9, 0x2dbe, 0x2dc3, 0x2dc8, 0x2dcd, 0x2dd2, 0x2dd7, 0x2ddc, 0x2de1, 0x2de6,+ 0x2deb, 0x2df0, 0x2df5, 0x2dfa, 0x2dff, 0x2e04, 0x2e09, 0x2e0e, 0x2e13, 0x2e17, 0x2e1c, 0x2e21, 0x2e26, 0x2e2b, 0x2e30, 0x2e35,+ 0x2e3a, 0x2e3f, 0x2e44, 0x2e49, 0x2e4d, 0x2e52, 0x2e57, 0x2e5c, 0x2e61, 0x2e66, 0x2e6b, 0x2e6f, 0x2e74, 0x2e79, 0x2e7e, 0x2e83,+ 0x2e88, 0x2e8c, 0x2e91, 0x2e96, 0x2e9b, 0x2ea0, 0x2ea4, 0x2ea9, 0x2eae, 0x2eb3, 0x2eb7, 0x2ebc, 0x2ec1, 0x2ec6, 0x2eca, 0x2ecf,+ 0x2ed4, 0x2ed9, 0x2edd, 0x2ee2, 0x2ee7, 0x2eeb, 0x2ef0, 0x2ef5, 0x2ef9, 0x2efe, 0x2f03, 0x2f07, 0x2f0c, 0x2f11, 0x2f15, 0x2f1a,+ 0x2f1f, 0x2f23, 0x2f28, 0x2f2d, 0x2f31, 0x2f36, 0x2f3a, 0x2f3f, 0x2f44, 0x2f48, 0x2f4d, 0x2f51, 0x2f56, 0x2f5a, 0x2f5f, 0x2f64,+ 0x2f68, 0x2f6d, 0x2f71, 0x2f76, 0x2f7a, 0x2f7f, 0x2f83, 0x2f88, 0x2f8c, 0x2f91, 0x2f95, 0x2f9a, 0x2f9e, 0x2fa3, 0x2fa7, 0x2fac,+ 0x2fb0, 0x2fb5, 0x2fb9, 0x2fbe, 0x2fc2, 0x2fc6, 0x2fcb, 0x2fcf, 0x2fd4, 0x2fd8, 0x2fdd, 0x2fe1, 0x2fe5, 0x2fea, 0x2fee, 0x2ff2,+ 0x2ff7, 0x2ffb, 0x3000, 0x3004, 0x3008, 0x300d, 0x3011, 0x3015, 0x301a, 0x301e, 0x3022, 0x3027, 0x302b, 0x302f, 0x3033, 0x3038,+ 0x303c, 0x3040, 0x3045, 0x3049, 0x304d, 0x3051, 0x3056, 0x305a, 0x305e, 0x3062, 0x3067, 0x306b, 0x306f, 0x3073, 0x3077, 0x307c,+ 0x3080, 0x3084, 0x3088, 0x308c, 0x3090, 0x3095, 0x3099, 0x309d, 0x30a1, 0x30a5, 0x30a9, 0x30ad, 0x30b2, 0x30b6, 0x30ba, 0x30be,+ 0x30c2, 0x30c6, 0x30ca, 0x30ce, 0x30d2, 0x30d6, 0x30da, 0x30df, 0x30e3, 0x30e7, 0x30eb, 0x30ef, 0x30f3, 0x30f7, 0x30fb, 0x30ff,+ 0x3103, 0x3107, 0x310b, 0x310f, 0x3113, 0x3117, 0x311b, 0x311f, 0x3123, 0x3127, 0x312a, 0x312e, 0x3132, 0x3136, 0x313a, 0x313e,+ 0x3142, 0x3146, 0x314a, 0x314e, 0x3152, 0x3156, 0x3159, 0x315d, 0x3161, 0x3165, 0x3169, 0x316d, 0x3171, 0x3174, 0x3178, 0x317c,+ 0x3180, 0x3184, 0x3187, 0x318b, 0x318f, 0x3193, 0x3197, 0x319a, 0x319e, 0x31a2, 0x31a6, 0x31a9, 0x31ad, 0x31b1, 0x31b5, 0x31b8,+ 0x31bc, 0x31c0, 0x31c3, 0x31c7, 0x31cb, 0x31cf, 0x31d2, 0x31d6, 0x31da, 0x31dd, 0x31e1, 0x31e5, 0x31e8, 0x31ec, 0x31f0, 0x31f3,+ 0x31f7, 0x31fa, 0x31fe, 0x3202, 0x3205, 0x3209, 0x320c, 0x3210, 0x3214, 0x3217, 0x321b, 0x321e, 0x3222, 0x3225, 0x3229, 0x322c,+ 0x3230, 0x3233, 0x3237, 0x323b, 0x323e, 0x3242, 0x3245, 0x3249, 0x324c, 0x324f, 0x3253, 0x3256, 0x325a, 0x325d, 0x3261, 0x3264,+ 0x3268, 0x326b, 0x326e, 0x3272, 0x3275, 0x3279, 0x327c, 0x327f, 0x3283, 0x3286, 0x328a, 0x328d, 0x3290, 0x3294, 0x3297, 0x329a,+ 0x329e, 0x32a1, 0x32a4, 0x32a8, 0x32ab, 0x32ae, 0x32b2, 0x32b5, 0x32b8, 0x32bb, 0x32bf, 0x32c2, 0x32c5, 0x32c8, 0x32cc, 0x32cf,+ 0x32d2, 0x32d5, 0x32d9, 0x32dc, 0x32df, 0x32e2, 0x32e5, 0x32e9, 0x32ec, 0x32ef, 0x32f2, 0x32f5, 0x32f8, 0x32fc, 0x32ff, 0x3302,+ 0x3305, 0x3308, 0x330b, 0x330e, 0x3312, 0x3315, 0x3318, 0x331b, 0x331e, 0x3321, 0x3324, 0x3327, 0x332a, 0x332d, 0x3330, 0x3333,+ 0x3336, 0x3339, 0x333c, 0x333f, 0x3342, 0x3345, 0x3348, 0x334b, 0x334e, 0x3351, 0x3354, 0x3357, 0x335a, 0x335d, 0x3360, 0x3363,+ 0x3366, 0x3369, 0x336c, 0x336f, 0x3372, 0x3375, 0x3377, 0x337a, 0x337d, 0x3380, 0x3383, 0x3386, 0x3389, 0x338c, 0x338e, 0x3391,+ 0x3394, 0x3397, 0x339a, 0x339d, 0x339f, 0x33a2, 0x33a5, 0x33a8, 0x33aa, 0x33ad, 0x33b0, 0x33b3, 0x33b6, 0x33b8, 0x33bb, 0x33be,+ 0x33c1, 0x33c3, 0x33c6, 0x33c9, 0x33cb, 0x33ce, 0x33d1, 0x33d3, 0x33d6, 0x33d9, 0x33db, 0x33de, 0x33e1, 0x33e3, 0x33e6, 0x33e9,+ 0x33eb, 0x33ee, 0x33f1, 0x33f3, 0x33f6, 0x33f8, 0x33fb, 0x33fd, 0x3400, 0x3403, 0x3405, 0x3408, 0x340a, 0x340d, 0x340f, 0x3412,+ 0x3414, 0x3417, 0x3419, 0x341c, 0x341e, 0x3421, 0x3423, 0x3426, 0x3428, 0x342b, 0x342d, 0x3430, 0x3432, 0x3435, 0x3437, 0x3439,+ 0x343c, 0x343e, 0x3441, 0x3443, 0x3445, 0x3448, 0x344a, 0x344d, 0x344f, 0x3451, 0x3454, 0x3456, 0x3458, 0x345b, 0x345d, 0x345f,+ 0x3462, 0x3464, 0x3466, 0x3469, 0x346b, 0x346d, 0x346f, 0x3472, 0x3474, 0x3476, 0x3478, 0x347b, 0x347d, 0x347f, 0x3481, 0x3484,+ 0x3486, 0x3488, 0x348a, 0x348c, 0x348e, 0x3491, 0x3493, 0x3495, 0x3497, 0x3499, 0x349b, 0x349e, 0x34a0, 0x34a2, 0x34a4, 0x34a6,+ 0x34a8, 0x34aa, 0x34ac, 0x34ae, 0x34b0, 0x34b3, 0x34b5, 0x34b7, 0x34b9, 0x34bb, 0x34bd, 0x34bf, 0x34c1, 0x34c3, 0x34c5, 0x34c7,+ 0x34c9, 0x34cb, 0x34cd, 0x34cf, 0x34d1, 0x34d3, 0x34d5, 0x34d7, 0x34d8, 0x34da, 0x34dc, 0x34de, 0x34e0, 0x34e2, 0x34e4, 0x34e6,+ 0x34e8, 0x34ea, 0x34eb, 0x34ed, 0x34ef, 0x34f1, 0x34f3, 0x34f5, 0x34f7, 0x34f8, 0x34fa, 0x34fc, 0x34fe, 0x3500, 0x3501, 0x3503,+ 0x3505, 0x3507, 0x3508, 0x350a, 0x350c, 0x350e, 0x350f, 0x3511, 0x3513, 0x3515, 0x3516, 0x3518, 0x351a, 0x351b, 0x351d, 0x351f,+ 0x3520, 0x3522, 0x3524, 0x3525, 0x3527, 0x3529, 0x352a, 0x352c, 0x352d, 0x352f, 0x3531, 0x3532, 0x3534, 0x3535, 0x3537, 0x3539,+ 0x353a, 0x353c, 0x353d, 0x353f, 0x3540, 0x3542, 0x3543, 0x3545, 0x3546, 0x3548, 0x3549, 0x354b, 0x354c, 0x354e, 0x354f, 0x3551,+ 0x3552, 0x3554, 0x3555, 0x3556, 0x3558, 0x3559, 0x355b, 0x355c, 0x355d, 0x355f, 0x3560, 0x3562, 0x3563, 0x3564, 0x3566, 0x3567,+ 0x3568, 0x356a, 0x356b, 0x356c, 0x356e, 0x356f, 0x3570, 0x3571, 0x3573, 0x3574, 0x3575, 0x3576, 0x3578, 0x3579, 0x357a, 0x357b,+ 0x357d, 0x357e, 0x357f, 0x3580, 0x3581, 0x3583, 0x3584, 0x3585, 0x3586, 0x3587, 0x3588, 0x358a, 0x358b, 0x358c, 0x358d, 0x358e,+ 0x358f, 0x3590, 0x3591, 0x3593, 0x3594, 0x3595, 0x3596, 0x3597, 0x3598, 0x3599, 0x359a, 0x359b, 0x359c, 0x359d, 0x359e, 0x359f,+ 0x35a0, 0x35a1, 0x35a2, 0x35a3, 0x35a4, 0x35a5, 0x35a6, 0x35a7, 0x35a8, 0x35a9, 0x35aa, 0x35aa, 0x35ab, 0x35ac, 0x35ad, 0x35ae,+ 0x35af, 0x35b0, 0x35b1, 0x35b2, 0x35b2, 0x35b3, 0x35b4, 0x35b5, 0x35b6, 0x35b7, 0x35b7, 0x35b8, 0x35b9, 0x35ba, 0x35bb, 0x35bb,+ 0x35bc, 0x35bd, 0x35be, 0x35be, 0x35bf, 0x35c0, 0x35c1, 0x35c1, 0x35c2, 0x35c3, 0x35c3, 0x35c4, 0x35c5, 0x35c5, 0x35c6, 0x35c7,+ 0x35c7, 0x35c8, 0x35c9, 0x35c9, 0x35ca, 0x35cb, 0x35cb, 0x35cc, 0x35cc, 0x35cd, 0x35ce, 0x35ce, 0x35cf, 0x35cf, 0x35d0, 0x35d0,+ 0x35d1, 0x35d1, 0x35d2, 0x35d2, 0x35d3, 0x35d3, 0x35d4, 0x35d4, 0x35d5, 0x35d5, 0x35d6, 0x35d6, 0x35d7, 0x35d7, 0x35d8, 0x35d8,+ 0x35d8, 0x35d9, 0x35d9, 0x35da, 0x35da, 0x35da, 0x35db, 0x35db, 0x35dc, 0x35dc, 0x35dc, 0x35dd, 0x35dd, 0x35dd, 0x35de, 0x35de,+ 0x35de, 0x35de, 0x35df, 0x35df, 0x35df, 0x35e0, 0x35e0, 0x35e0, 0x35e0, 0x35e1, 0x35e1, 0x35e1, 0x35e1, 0x35e1, 0x35e2, 0x35e2,+ 0x35e2, 0x35e2, 0x35e2, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4,+ 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4,+ 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e2, 0x35e2,+ 0x35e2, 0x35e2, 0x35e2, 0x35e2, 0x35e1, 0x35e1, 0x35e1, 0x35e1, 0x35e1, 0x35e0, 0x35e0, 0x35e0, 0x35e0, 0x35df, 0x35df, 0x35df,+ 0x35de, 0x35de, 0x35de, 0x35dd, 0x35dd, 0x35dd, 0x35dc, 0x35dc, 0x35dc, 0x35db, 0x35db, 0x35db, 0x35da, 0x35da, 0x35da, 0x35d9,+ 0x35d9, 0x35d8, 0x35d8, 0x35d7, 0x35d7, 0x35d7, 0x35d6, 0x35d6, 0x35d5, 0x35d5, 0x35d4, 0x35d4, 0x35d3, 0x35d3, 0x35d2, 0x35d2,+ 0x35d1, 0x35d1, 0x35d0, 0x35cf, 0x35cf, 0x35ce, 0x35ce, 0x35cd, 0x35cd, 0x35cc, 0x35cb, 0x35cb, 0x35ca, 0x35c9, 0x35c9, 0x35c8,+ 0x35c7, 0x35c7, 0x35c6, 0x35c5, 0x35c5, 0x35c4, 0x35c3, 0x35c3, 0x35c2, 0x35c1, 0x35c1, 0x35c0, 0x35bf, 0x35be, 0x35be, 0x35bd,+ 0x35bc, 0x35bb, 0x35ba, 0x35ba, 0x35b9, 0x35b8, 0x35b7, 0x35b6, 0x35b5, 0x35b5, 0x35b4, 0x35b3, 0x35b2, 0x35b1, 0x35b0, 0x35af,+ 0x35ae, 0x35ae, 0x35ad, 0x35ac, 0x35ab, 0x35aa, 0x35a9, 0x35a8, 0x35a7, 0x35a6, 0x35a5, 0x35a4, 0x35a3, 0x35a2, 0x35a1, 0x35a0,+ 0x359f, 0x359e, 0x359d, 0x359c, 0x359b, 0x359a, 0x3599, 0x3598, 0x3597, 0x3595, 0x3594, 0x3593, 0x3592, 0x3591, 0x3590, 0x358f,+ 0x358e, 0x358c, 0x358b, 0x358a, 0x3589, 0x3588, 0x3587, 0x3585, 0x3584, 0x3583, 0x3582, 0x3580, 0x357f, 0x357e, 0x357d, 0x357b,+ 0x357a, 0x3579, 0x3578, 0x3576, 0x3575, 0x3574, 0x3572, 0x3571, 0x3570, 0x356e, 0x356d, 0x356c, 0x356a, 0x3569, 0x3567, 0x3566,+ 0x3565, 0x3563, 0x3562, 0x3560, 0x355f, 0x355e, 0x355c, 0x355b, 0x3559, 0x3558, 0x3556, 0x3555, 0x3553, 0x3552, 0x3550, 0x354f,+ 0x354d, 0x354c, 0x354a, 0x3549, 0x3547, 0x3545, 0x3544, 0x3542, 0x3541, 0x353f, 0x353e, 0x353c, 0x353a, 0x3539, 0x3537, 0x3535,+ 0x3534, 0x3532, 0x3530, 0x352f, 0x352d, 0x352b, 0x352a, 0x3528, 0x3526, 0x3525, 0x3523, 0x3521, 0x351f, 0x351e, 0x351c, 0x351a,+ 0x3518, 0x3516, 0x3515, 0x3513, 0x3511, 0x350f, 0x350d, 0x350c, 0x350a, 0x3508, 0x3506, 0x3504, 0x3502, 0x3500, 0x34ff, 0x34fd,+ 0x34fb, 0x34f9, 0x34f7, 0x34f5, 0x34f3, 0x34f1, 0x34ef, 0x34ed, 0x34eb, 0x34e9, 0x34e7, 0x34e5, 0x34e3, 0x34e1, 0x34df, 0x34dd,+ 0x34db, 0x34d9, 0x34d7, 0x34d5, 0x34d3, 0x34d1, 0x34cf, 0x34cd, 0x34cb, 0x34c9, 0x34c6, 0x34c4, 0x34c2, 0x34c0, 0x34be, 0x34bc,+ 0x34ba, 0x34b7, 0x34b5, 0x34b3, 0x34b1, 0x34af, 0x34ac, 0x34aa, 0x34a8, 0x34a6, 0x34a4, 0x34a1, 0x349f, 0x349d, 0x349a, 0x3498,+ 0x3496, 0x3494, 0x3491, 0x348f, 0x348d, 0x348a, 0x3488, 0x3486, 0x3483, 0x3481, 0x347f, 0x347c, 0x347a, 0x3477, 0x3475, 0x3473,+ 0x3470, 0x346e, 0x346b, 0x3469, 0x3466, 0x3464, 0x3461, 0x345f, 0x345c, 0x345a, 0x3458, 0x3455, 0x3452, 0x3450, 0x344d, 0x344b,+ 0x3448, 0x3446, 0x3443, 0x3441, 0x343e, 0x343b, 0x3439, 0x3436, 0x3434, 0x3431, 0x342e, 0x342c, 0x3429, 0x3426, 0x3424, 0x3421,+ 0x341e, 0x341c, 0x3419, 0x3416, 0x3414, 0x3411, 0x340e, 0x340b, 0x3409, 0x3406, 0x3403, 0x3400, 0x33fe, 0x33fb, 0x33f8, 0x33f5,+ 0x33f2, 0x33f0, 0x33ed, 0x33ea, 0x33e7, 0x33e4, 0x33e1, 0x33df, 0x33dc, 0x33d9, 0x33d6, 0x33d3, 0x33d0, 0x33cd, 0x33ca, 0x33c7,+ 0x33c4, 0x33c1, 0x33be, 0x33bb, 0x33b8, 0x33b5, 0x33b2, 0x33af, 0x33ac, 0x33a9, 0x33a6, 0x33a3, 0x33a0, 0x339d, 0x339a, 0x3397,+ 0x3394, 0x3391, 0x338e, 0x338b, 0x3388, 0x3385, 0x3381, 0x337e, 0x337b, 0x3378, 0x3375, 0x3372, 0x336f, 0x336b, 0x3368, 0x3365,+ 0x3362, 0x335f, 0x335b, 0x3358, 0x3355, 0x3352, 0x334e, 0x334b, 0x3348, 0x3345, 0x3341, 0x333e, 0x333b, 0x3337, 0x3334, 0x3331,+ 0x332d, 0x332a, 0x3327, 0x3323, 0x3320, 0x331c, 0x3319, 0x3316, 0x3312, 0x330f, 0x330b, 0x3308, 0x3305, 0x3301, 0x32fe, 0x32fa,+ 0x32f7, 0x32f3, 0x32f0, 0x32ec, 0x32e9, 0x32e5, 0x32e2, 0x32de, 0x32db, 0x32d7, 0x32d4, 0x32d0, 0x32cc, 0x32c9, 0x32c5, 0x32c2,+ 0x32be, 0x32ba, 0x32b7, 0x32b3, 0x32b0, 0x32ac, 0x32a8, 0x32a5, 0x32a1, 0x329d, 0x3299, 0x3296, 0x3292, 0x328e, 0x328b, 0x3287,+ 0x3283, 0x327f, 0x327c, 0x3278, 0x3274, 0x3270, 0x326d, 0x3269, 0x3265, 0x3261, 0x325d, 0x3259, 0x3256, 0x3252, 0x324e, 0x324a,+ 0x3246, 0x3242, 0x323e, 0x323a, 0x3237, 0x3233, 0x322f, 0x322b, 0x3227, 0x3223, 0x321f, 0x321b, 0x3217, 0x3213, 0x320f, 0x320b,+ 0x3207, 0x3203, 0x31ff, 0x31fb, 0x31f7, 0x31f3, 0x31ef, 0x31eb, 0x31e7, 0x31e2, 0x31de, 0x31da, 0x31d6, 0x31d2, 0x31ce, 0x31ca,+ 0x31c6, 0x31c1, 0x31bd, 0x31b9, 0x31b5, 0x31b1, 0x31ad, 0x31a8, 0x31a4, 0x31a0, 0x319c, 0x3197, 0x3193, 0x318f, 0x318b, 0x3186,+ 0x3182, 0x317e, 0x3179, 0x3175, 0x3171, 0x316d, 0x3168, 0x3164, 0x315f, 0x315b, 0x3157, 0x3152, 0x314e, 0x314a, 0x3145, 0x3141,+ 0x313c, 0x3138, 0x3133, 0x312f, 0x312b, 0x3126, 0x3122, 0x311d, 0x3119, 0x3114, 0x3110, 0x310b, 0x3107, 0x3102, 0x30fe, 0x30f9,+ 0x30f4, 0x30f0, 0x30eb, 0x30e7, 0x30e2, 0x30de, 0x30d9, 0x30d4, 0x30d0, 0x30cb, 0x30c6, 0x30c2, 0x30bd, 0x30b8, 0x30b4, 0x30af,+ 0x30aa, 0x30a6, 0x30a1, 0x309c, 0x3097, 0x3093, 0x308e, 0x3089, 0x3084, 0x3080, 0x307b, 0x3076, 0x3071, 0x306d, 0x3068, 0x3063,+ 0x305e, 0x3059, 0x3054, 0x304f, 0x304b, 0x3046, 0x3041, 0x303c, 0x3037, 0x3032, 0x302d, 0x3028, 0x3023, 0x301e, 0x3019, 0x3015,+ 0x3010, 0x300b, 0x3006, 0x3001, 0x2ffc, 0x2ff7, 0x2ff2, 0x2fec, 0x2fe7, 0x2fe2, 0x2fdd, 0x2fd8, 0x2fd3, 0x2fce, 0x2fc9, 0x2fc4,+ 0x2fbf, 0x2fba, 0x2fb5, 0x2faf, 0x2faa, 0x2fa5, 0x2fa0, 0x2f9b, 0x2f96, 0x2f90, 0x2f8b, 0x2f86, 0x2f81, 0x2f7c, 0x2f76, 0x2f71,+ 0x2f6c, 0x2f67, 0x2f61, 0x2f5c, 0x2f57, 0x2f51, 0x2f4c, 0x2f47, 0x2f42, 0x2f3c, 0x2f37, 0x2f32, 0x2f2c, 0x2f27, 0x2f21, 0x2f1c,+ 0x2f17, 0x2f11, 0x2f0c, 0x2f06, 0x2f01, 0x2efc, 0x2ef6, 0x2ef1, 0x2eeb, 0x2ee6, 0x2ee0, 0x2edb, 0x2ed5, 0x2ed0, 0x2eca, 0x2ec5,+ 0x2ebf, 0x2eba, 0x2eb4, 0x2eaf, 0x2ea9, 0x2ea3, 0x2e9e, 0x2e98, 0x2e93, 0x2e8d, 0x2e87, 0x2e82, 0x2e7c, 0x2e77, 0x2e71, 0x2e6b,+ 0x2e66, 0x2e60, 0x2e5a, 0x2e55, 0x2e4f, 0x2e49, 0x2e43, 0x2e3e, 0x2e38, 0x2e32, 0x2e2c, 0x2e27, 0x2e21, 0x2e1b, 0x2e15, 0x2e0f,+ 0x2e0a, 0x2e04, 0x2dfe, 0x2df8, 0x2df2, 0x2dec, 0x2de7, 0x2de1, 0x2ddb, 0x2dd5, 0x2dcf, 0x2dc9, 0x2dc3, 0x2dbd, 0x2db7, 0x2db1,+ 0x2dab, 0x2da6, 0x2da0, 0x2d9a, 0x2d94, 0x2d8e, 0x2d88, 0x2d82, 0x2d7c, 0x2d76, 0x2d6f, 0x2d69, 0x2d63, 0x2d5d, 0x2d57, 0x2d51,+ 0x2d4b, 0x2d45, 0x2d3f, 0x2d39, 0x2d33, 0x2d2c, 0x2d26, 0x2d20, 0x2d1a, 0x2d14, 0x2d0e, 0x2d07, 0x2d01, 0x2cfb, 0x2cf5, 0x2cef,+ 0x2ce8, 0x2ce2, 0x2cdc, 0x2cd6, 0x2ccf, 0x2cc9, 0x2cc3, 0x2cbc, 0x2cb6, 0x2cb0, 0x2caa, 0x2ca3, 0x2c9d, 0x2c96, 0x2c90, 0x2c8a,+ 0x2c83, 0x2c7d, 0x2c77, 0x2c70, 0x2c6a, 0x2c63, 0x2c5d, 0x2c56, 0x2c50, 0x2c4a, 0x2c43, 0x2c3d, 0x2c36, 0x2c30, 0x2c29, 0x2c23,+ 0x2c1c, 0x2c16, 0x2c0f, 0x2c08, 0x2c02, 0x2bfb, 0x2bf5, 0x2bee, 0x2be8, 0x2be1, 0x2bda, 0x2bd4, 0x2bcd, 0x2bc7, 0x2bc0, 0x2bb9,+ 0x2bb3, 0x2bac, 0x2ba5, 0x2b9f, 0x2b98, 0x2b91, 0x2b8a, 0x2b84, 0x2b7d, 0x2b76, 0x2b6f, 0x2b69, 0x2b62, 0x2b5b, 0x2b54, 0x2b4e,+ 0x2b47, 0x2b40, 0x2b39, 0x2b32, 0x2b2b, 0x2b25, 0x2b1e, 0x2b17, 0x2b10, 0x2b09, 0x2b02, 0x2afb, 0x2af4, 0x2aed, 0x2ae7, 0x2ae0,+ 0x2ad9, 0x2ad2, 0x2acb, 0x2ac4, 0x2abd, 0x2ab6, 0x2aaf, 0x2aa8, 0x2aa1, 0x2a9a, 0x2a93, 0x2a8c, 0x2a85, 0x2a7d, 0x2a76, 0x2a6f,+ 0x2a68, 0x2a61, 0x2a5a, 0x2a53, 0x2a4c, 0x2a45, 0x2a3d, 0x2a36, 0x2a2f, 0x2a28, 0x2a21, 0x2a1a, 0x2a12, 0x2a0b, 0x2a04, 0x29fd,+ 0x29f5, 0x29ee, 0x29e7, 0x29e0, 0x29d8, 0x29d1, 0x29ca, 0x29c3, 0x29bb, 0x29b4, 0x29ad, 0x29a5, 0x299e, 0x2997, 0x298f, 0x2988,+ 0x2980, 0x2979, 0x2972, 0x296a, 0x2963, 0x295b, 0x2954, 0x294c, 0x2945, 0x293e, 0x2936, 0x292f, 0x2927, 0x2920, 0x2918, 0x2911,+ 0x2909, 0x2901, 0x28fa, 0x28f2, 0x28eb, 0x28e3, 0x28dc, 0x28d4, 0x28cc, 0x28c5, 0x28bd, 0x28b6, 0x28ae, 0x28a6, 0x289f, 0x2897,+ 0x288f, 0x2888, 0x2880, 0x2878, 0x2871, 0x2869, 0x2861, 0x2859, 0x2852, 0x284a, 0x2842, 0x283a, 0x2833, 0x282b, 0x2823, 0x281b,+ 0x2813, 0x280b, 0x2804, 0x27fc, 0x27f4, 0x27ec, 0x27e4, 0x27dc, 0x27d4, 0x27cd, 0x27c5, 0x27bd, 0x27b5, 0x27ad, 0x27a5, 0x279d,+ 0x2795, 0x278d, 0x2785, 0x277d, 0x2775, 0x276d, 0x2765, 0x275d, 0x2755, 0x274d, 0x2745, 0x273d, 0x2735, 0x272d, 0x2724, 0x271c,+ 0x2714, 0x270c, 0x2704, 0x26fc, 0x26f4, 0x26ec, 0x26e3, 0x26db, 0x26d3, 0x26cb, 0x26c3, 0x26ba, 0x26b2, 0x26aa, 0x26a2, 0x269a,+ 0x2691, 0x2689, 0x2681, 0x2678, 0x2670, 0x2668, 0x2660, 0x2657, 0x264f, 0x2647, 0x263e, 0x2636, 0x262d, 0x2625, 0x261d, 0x2614,+ 0x260c, 0x2603, 0x25fb, 0x25f3, 0x25ea, 0x25e2, 0x25d9, 0x25d1, 0x25c8, 0x25c0, 0x25b7, 0x25af, 0x25a6, 0x259e, 0x2595, 0x258d,+ 0x2584, 0x257c, 0x2573, 0x256a, 0x2562, 0x2559, 0x2551, 0x2548, 0x253f, 0x2537, 0x252e, 0x2525, 0x251d, 0x2514, 0x250b, 0x2503,+ 0x24fa, 0x24f1, 0x24e9, 0x24e0, 0x24d7, 0x24ce, 0x24c6, 0x24bd, 0x24b4, 0x24ab, 0x24a3, 0x249a, 0x2491, 0x2488, 0x247f, 0x2476,+ 0x246e, 0x2465, 0x245c, 0x2453, 0x244a, 0x2441, 0x2438, 0x242f, 0x2426, 0x241e, 0x2415, 0x240c, 0x2403, 0x23fa, 0x23f1, 0x23e8,+ 0x23df, 0x23d6, 0x23cd, 0x23c4, 0x23bb, 0x23b2, 0x23a9, 0x23a0, 0x2396, 0x238d, 0x2384, 0x237b, 0x2372, 0x2369, 0x2360, 0x2357,+ 0x234e, 0x2344, 0x233b, 0x2332, 0x2329, 0x2320, 0x2317, 0x230d, 0x2304, 0x22fb, 0x22f2, 0x22e8, 0x22df, 0x22d6, 0x22cd, 0x22c3,+ 0x22ba, 0x22b1, 0x22a7, 0x229e, 0x2295, 0x228b, 0x2282, 0x2279, 0x226f, 0x2266, 0x225d, 0x2253, 0x224a, 0x2240, 0x2237, 0x222e,+ 0x2224, 0x221b, 0x2211, 0x2208, 0x21fe, 0x21f5, 0x21eb, 0x21e2, 0x21d8, 0x21cf, 0x21c5, 0x21bc, 0x21b2, 0x21a9, 0x219f, 0x2195,+ 0x218c, 0x2182, 0x2179, 0x216f, 0x2165, 0x215c, 0x2152, 0x2148, 0x213f, 0x2135, 0x212b, 0x2122, 0x2118, 0x210e, 0x2105, 0x20fb,+ 0x20f1, 0x20e7, 0x20de, 0x20d4, 0x20ca, 0x20c0, 0x20b6, 0x20ad, 0x20a3, 0x2099, 0x208f, 0x2085, 0x207b, 0x2072, 0x2068, 0x205e,+ 0x2054, 0x204a, 0x2040, 0x2036, 0x202c, 0x2022, 0x2018, 0x200e, 0x2005, 0x1ffb, 0x1ff1, 0x1fe7, 0x1fdd, 0x1fd3, 0x1fc9, 0x1fbf,+ 0x1fb4, 0x1faa, 0x1fa0, 0x1f96, 0x1f8c, 0x1f82, 0x1f78, 0x1f6e, 0x1f64, 0x1f5a, 0x1f50, 0x1f45, 0x1f3b, 0x1f31, 0x1f27, 0x1f1d,+ 0x1f13, 0x1f08, 0x1efe, 0x1ef4, 0x1eea, 0x1ee0, 0x1ed5, 0x1ecb, 0x1ec1, 0x1eb6, 0x1eac, 0x1ea2, 0x1e98, 0x1e8d, 0x1e83, 0x1e79,+ 0x1e6e, 0x1e64, 0x1e5a, 0x1e4f, 0x1e45, 0x1e3a, 0x1e30, 0x1e26, 0x1e1b, 0x1e11, 0x1e06, 0x1dfc, 0x1df2, 0x1de7, 0x1ddd, 0x1dd2,+ 0x1dc8, 0x1dbd, 0x1db3, 0x1da8, 0x1d9e, 0x1d93, 0x1d88, 0x1d7e, 0x1d73, 0x1d69, 0x1d5e, 0x1d54, 0x1d49, 0x1d3e, 0x1d34, 0x1d29,+ 0x1d1f, 0x1d14, 0x1d09, 0x1cff, 0x1cf4, 0x1ce9, 0x1cde, 0x1cd4, 0x1cc9, 0x1cbe, 0x1cb4, 0x1ca9, 0x1c9e, 0x1c93, 0x1c89, 0x1c7e,+ 0x1c73, 0x1c68, 0x1c5d, 0x1c53, 0x1c48, 0x1c3d, 0x1c32, 0x1c27, 0x1c1c, 0x1c11, 0x1c07, 0x1bfc, 0x1bf1, 0x1be6, 0x1bdb, 0x1bd0,+ 0x1bc5, 0x1bba, 0x1baf, 0x1ba4, 0x1b99, 0x1b8e, 0x1b83, 0x1b78, 0x1b6d, 0x1b62, 0x1b57, 0x1b4c, 0x1b41, 0x1b36, 0x1b2b, 0x1b20,+ 0x1b15, 0x1b0a, 0x1aff, 0x1af3, 0x1ae8, 0x1add, 0x1ad2, 0x1ac7, 0x1abc, 0x1ab0, 0x1aa5, 0x1a9a, 0x1a8f, 0x1a84, 0x1a78, 0x1a6d,+ 0x1a62, 0x1a57, 0x1a4b, 0x1a40, 0x1a35, 0x1a2a, 0x1a1e, 0x1a13, 0x1a08, 0x19fc, 0x19f1, 0x19e6, 0x19da, 0x19cf, 0x19c4, 0x19b8,+ 0x19ad, 0x19a1, 0x1996, 0x198b, 0x197f, 0x1974, 0x1968, 0x195d, 0x1951, 0x1946, 0x193a, 0x192f, 0x1923, 0x1918, 0x190c, 0x1901,+ 0x18f5, 0x18ea, 0x18de, 0x18d2, 0x18c7, 0x18bb, 0x18b0, 0x18a4, 0x1898, 0x188d, 0x1881, 0x1876, 0x186a, 0x185e, 0x1853, 0x1847,+ 0x183b, 0x182f, 0x1824, 0x1818, 0x180c, 0x1801, 0x17f5, 0x17e9, 0x17dd, 0x17d1, 0x17c6, 0x17ba, 0x17ae, 0x17a2, 0x1796, 0x178b,+ 0x177f, 0x1773, 0x1767, 0x175b, 0x174f, 0x1743, 0x1737, 0x172b, 0x1720, 0x1714, 0x1708, 0x16fc, 0x16f0, 0x16e4, 0x16d8, 0x16cc,+ 0x16c0, 0x16b4, 0x16a8, 0x169c, 0x1690, 0x1684, 0x1678, 0x166c, 0x165f, 0x1653, 0x1647, 0x163b, 0x162f, 0x1623, 0x1617, 0x160b,+ 0x15fe, 0x15f2, 0x15e6, 0x15da, 0x15ce, 0x15c2, 0x15b5, 0x15a9, 0x159d, 0x1591, 0x1584, 0x1578, 0x156c, 0x1560, 0x1553, 0x1547,+ 0x153b, 0x152e, 0x1522, 0x1516, 0x1509, 0x14fd, 0x14f1, 0x14e4, 0x14d8, 0x14cb, 0x14bf, 0x14b3, 0x14a6, 0x149a, 0x148d, 0x1481,+ 0x1474, 0x1468, 0x145c, 0x144f, 0x1443, 0x1436, 0x1429, 0x141d, 0x1410, 0x1404, 0x13f7, 0x13eb, 0x13de, 0x13d2, 0x13c5, 0x13b8,+ 0x13ac, 0x139f, 0x1393, 0x1386, 0x1379, 0x136d, 0x1360, 0x1353, 0x1347, 0x133a, 0x132d, 0x1320, 0x1314, 0x1307, 0x12fa, 0x12ed,+ 0x12e1, 0x12d4, 0x12c7, 0x12ba, 0x12ae, 0x12a1, 0x1294, 0x1287, 0x127a, 0x126d, 0x1261, 0x1254, 0x1247, 0x123a, 0x122d, 0x1220,+ 0x1213, 0x1206, 0x11f9, 0x11ec, 0x11df, 0x11d2, 0x11c5, 0x11b8, 0x11ab, 0x119e, 0x1191, 0x1184, 0x1177, 0x116a, 0x115d, 0x1150,+ 0x1143, 0x1136, 0x1129, 0x111c, 0x110f, 0x1102, 0x10f5, 0x10e7, 0x10da, 0x10cd, 0x10c0, 0x10b3, 0x10a6, 0x1098, 0x108b, 0x107e,+ 0x1071, 0x1063, 0x1056, 0x1049, 0x103c, 0x102e, 0x1021, 0x1014, 0x1007, 0x0ff9, 0x0fec, 0x0fdf, 0x0fd1, 0x0fc4, 0x0fb7, 0x0fa9,+ 0x0f9c, 0x0f8e, 0x0f81, 0x0f74, 0x0f66, 0x0f59, 0x0f4b, 0x0f3e, 0x0f30, 0x0f23, 0x0f15, 0x0f08, 0x0efa, 0x0eed, 0x0edf, 0x0ed2,+ 0x0ec4, 0x0eb7, 0x0ea9, 0x0e9c, 0x0e8e, 0x0e81, 0x0e73, 0x0e65, 0x0e58, 0x0e4a, 0x0e3d, 0x0e2f, 0x0e21, 0x0e14, 0x0e06, 0x0df8,+ 0x0deb, 0x0ddd, 0x0dcf, 0x0dc1, 0x0db4, 0x0da6, 0x0d98, 0x0d8b, 0x0d7d, 0x0d6f, 0x0d61, 0x0d53, 0x0d46, 0x0d38, 0x0d2a, 0x0d1c,+ 0x0d0e, 0x0d00, 0x0cf3, 0x0ce5, 0x0cd7, 0x0cc9, 0x0cbb, 0x0cad, 0x0c9f, 0x0c91, 0x0c83, 0x0c75, 0x0c68, 0x0c5a, 0x0c4c, 0x0c3e,+ 0x0c30, 0x0c22, 0x0c14, 0x0c06, 0x0bf8, 0x0bea, 0x0bdb, 0x0bcd, 0x0bbf, 0x0bb1, 0x0ba3, 0x0b95, 0x0b87, 0x0b79, 0x0b6b, 0x0b5d,+ 0x0b4e, 0x0b40, 0x0b32, 0x0b24, 0x0b16, 0x0b08, 0x0af9, 0x0aeb, 0x0add, 0x0acf, 0x0ac0, 0x0ab2, 0x0aa4, 0x0a96, 0x0a87, 0x0a79,+ 0x0a6b, 0x0a5c, 0x0a4e, 0x0a40, 0x0a31, 0x0a23, 0x0a15, 0x0a06, 0x09f8, 0x09ea, 0x09db, 0x09cd, 0x09be, 0x09b0, 0x09a2, 0x0993,+ 0x0985, 0x0976, 0x0968, 0x0959, 0x094b, 0x093c, 0x092e, 0x091f, 0x0911, 0x0902, 0x08f4, 0x08e5, 0x08d6, 0x08c8, 0x08b9, 0x08ab,+ 0x089c, 0x088d, 0x087f, 0x0870, 0x0862, 0x0853, 0x0844, 0x0836, 0x0827, 0x0818, 0x0809, 0x07fb, 0x07ec, 0x07dd, 0x07cf, 0x07c0,+ 0x07b1, 0x07a2, 0x0794, 0x0785, 0x0776, 0x0767, 0x0758, 0x0749, 0x073b, 0x072c, 0x071d, 0x070e, 0x06ff, 0x06f0, 0x06e1, 0x06d2,+ 0x06c4, 0x06b5, 0x06a6, 0x0697, 0x0688, 0x0679, 0x066a, 0x065b, 0x064c, 0x063d, 0x062e, 0x061f, 0x0610, 0x0601, 0x05f2, 0x05e3,+ 0x05d4, 0x05c5, 0x05b5, 0x05a6, 0x0597, 0x0588, 0x0579, 0x056a, 0x055b, 0x054c, 0x053c, 0x052d, 0x051e, 0x050f, 0x0500, 0x04f0,+ 0x04e1, 0x04d2, 0x04c3, 0x04b3, 0x04a4, 0x0495, 0x0486, 0x0476, 0x0467, 0x0458, 0x0448, 0x0439, 0x042a, 0x041a, 0x040b, 0x03fc,+ 0x03ec, 0x03dd, 0x03cd, 0x03be, 0x03af, 0x039f, 0x0390, 0x0380, 0x0371, 0x0361, 0x0352, 0x0342, 0x0333, 0x0323, 0x0314, 0x0304,+ 0x02f5, 0x02e5, 0x02d6, 0x02c6, 0x02b7, 0x02a7, 0x0297, 0x0288, 0x0278, 0x0269, 0x0259, 0x0249, 0x023a, 0x022a, 0x021a, 0x020b,+ 0x01fb, 0x01eb, 0x01dc, 0x01cc, 0x01bc, 0x01ac, 0x019d, 0x018d, 0x017d, 0x016d, 0x015e, 0x014e, 0x013e, 0x012e, 0x011e, 0x010f,+ 0x00ff, 0x00ef, 0x00df, 0x00cf, 0x00bf, 0x00af, 0x00a0, 0x0090, 0x0080, 0x0070, 0x0060, 0x0050, 0x0040, 0x0030, 0x0020, 0x0010,+ 0x0000,+};++// This table was generated using the following PICO-8 code:+// for i=0,1,0x.002 do printh('0x'..sub(tostr(atan2(1,-i),1),8,13)) end+static uint16_t atantable[] =+{+ 0x0000, 0x0005, 0x000a, 0x000f, 0x0014, 0x0019, 0x001f, 0x0024, 0x0029, 0x002e, 0x0033, 0x0038, 0x003d, 0x0042, 0x0047, 0x004c,+ 0x0051, 0x0057, 0x005c, 0x0061, 0x0066, 0x006b, 0x0070, 0x0075, 0x007a, 0x007f, 0x0084, 0x008a, 0x008f, 0x0094, 0x0099, 0x009e,+ 0x00a3, 0x00a8, 0x00ad, 0x00b2, 0x00b7, 0x00bc, 0x00c2, 0x00c7, 0x00cc, 0x00d1, 0x00d6, 0x00db, 0x00e0, 0x00e5, 0x00ea, 0x00ef,+ 0x00f4, 0x00fa, 0x00ff, 0x0104, 0x0109, 0x010e, 0x0113, 0x0118, 0x011d, 0x0122, 0x0127, 0x012c, 0x0131, 0x0137, 0x013c, 0x0141,+ 0x0146, 0x014b, 0x0150, 0x0155, 0x015a, 0x015f, 0x0164, 0x0169, 0x016f, 0x0174, 0x0179, 0x017e, 0x0183, 0x0188, 0x018d, 0x0192,+ 0x0197, 0x019c, 0x01a1, 0x01a6, 0x01ac, 0x01b1, 0x01b6, 0x01bb, 0x01c0, 0x01c5, 0x01ca, 0x01cf, 0x01d4, 0x01d9, 0x01de, 0x01e3,+ 0x01e9, 0x01ee, 0x01f3, 0x01f8, 0x01fd, 0x0202, 0x0207, 0x020c, 0x0211, 0x0216, 0x021b, 0x0220, 0x0226, 0x022b, 0x0230, 0x0235,+ 0x023a, 0x023f, 0x0244, 0x0249, 0x024e, 0x0253, 0x0258, 0x025d, 0x0262, 0x0268, 0x026d, 0x0272, 0x0277, 0x027c, 0x0281, 0x0286,+ 0x028b, 0x0290, 0x0295, 0x029a, 0x029f, 0x02a4, 0x02a9, 0x02af, 0x02b4, 0x02b9, 0x02be, 0x02c3, 0x02c8, 0x02cd, 0x02d2, 0x02d7,+ 0x02dc, 0x02e1, 0x02e6, 0x02eb, 0x02f0, 0x02f6, 0x02fb, 0x0300, 0x0305, 0x030a, 0x030f, 0x0314, 0x0319, 0x031e, 0x0323, 0x0328,+ 0x032d, 0x0332, 0x0337, 0x033c, 0x0341, 0x0347, 0x034c, 0x0351, 0x0356, 0x035b, 0x0360, 0x0365, 0x036a, 0x036f, 0x0374, 0x0379,+ 0x037e, 0x0383, 0x0388, 0x038d, 0x0392, 0x0397, 0x039c, 0x03a2, 0x03a7, 0x03ac, 0x03b1, 0x03b6, 0x03bb, 0x03c0, 0x03c5, 0x03ca,+ 0x03cf, 0x03d4, 0x03d9, 0x03de, 0x03e3, 0x03e8, 0x03ed, 0x03f2, 0x03f7, 0x03fc, 0x0401, 0x0407, 0x040c, 0x0411, 0x0416, 0x041b,+ 0x0420, 0x0425, 0x042a, 0x042f, 0x0434, 0x0439, 0x043e, 0x0443, 0x0448, 0x044d, 0x0452, 0x0457, 0x045c, 0x0461, 0x0466, 0x046b,+ 0x0470, 0x0475, 0x047a, 0x047f, 0x0484, 0x0489, 0x048e, 0x0494, 0x0499, 0x049e, 0x04a3, 0x04a8, 0x04ad, 0x04b2, 0x04b7, 0x04bc,+ 0x04c1, 0x04c6, 0x04cb, 0x04d0, 0x04d5, 0x04da, 0x04df, 0x04e4, 0x04e9, 0x04ee, 0x04f3, 0x04f8, 0x04fd, 0x0502, 0x0507, 0x050c,+ 0x0511, 0x0516, 0x051b, 0x0520, 0x0525, 0x052a, 0x052f, 0x0534, 0x0539, 0x053e, 0x0543, 0x0548, 0x054d, 0x0552, 0x0557, 0x055c,+ 0x0561, 0x0566, 0x056b, 0x0570, 0x0575, 0x057a, 0x057f, 0x0584, 0x0589, 0x058e, 0x0593, 0x0598, 0x059d, 0x05a2, 0x05a7, 0x05ac,+ 0x05b1, 0x05b6, 0x05bb, 0x05c0, 0x05c5, 0x05ca, 0x05cf, 0x05d4, 0x05d9, 0x05de, 0x05e3, 0x05e8, 0x05ed, 0x05f2, 0x05f7, 0x05fc,+ 0x0601, 0x0606, 0x060b, 0x0610, 0x0615, 0x061a, 0x061f, 0x0624, 0x0629, 0x062e, 0x0633, 0x0638, 0x063d, 0x0642, 0x0647, 0x064c,+ 0x0651, 0x0656, 0x065b, 0x0660, 0x0665, 0x066a, 0x066e, 0x0673, 0x0678, 0x067d, 0x0682, 0x0687, 0x068c, 0x0691, 0x0696, 0x069b,+ 0x06a0, 0x06a5, 0x06aa, 0x06af, 0x06b4, 0x06b9, 0x06be, 0x06c3, 0x06c8, 0x06cd, 0x06d2, 0x06d7, 0x06dc, 0x06e1, 0x06e5, 0x06ea,+ 0x06ef, 0x06f4, 0x06f9, 0x06fe, 0x0703, 0x0708, 0x070d, 0x0712, 0x0717, 0x071c, 0x0721, 0x0726, 0x072b, 0x0730, 0x0735, 0x0739,+ 0x073e, 0x0743, 0x0748, 0x074d, 0x0752, 0x0757, 0x075c, 0x0761, 0x0766, 0x076b, 0x0770, 0x0775, 0x077a, 0x077e, 0x0783, 0x0788,+ 0x078d, 0x0792, 0x0797, 0x079c, 0x07a1, 0x07a6, 0x07ab, 0x07b0, 0x07b5, 0x07b9, 0x07be, 0x07c3, 0x07c8, 0x07cd, 0x07d2, 0x07d7,+ 0x07dc, 0x07e1, 0x07e6, 0x07eb, 0x07ef, 0x07f4, 0x07f9, 0x07fe, 0x0803, 0x0808, 0x080d, 0x0812, 0x0817, 0x081c, 0x0820, 0x0825,+ 0x082a, 0x082f, 0x0834, 0x0839, 0x083e, 0x0843, 0x0848, 0x084c, 0x0851, 0x0856, 0x085b, 0x0860, 0x0865, 0x086a, 0x086f, 0x0873,+ 0x0878, 0x087d, 0x0882, 0x0887, 0x088c, 0x0891, 0x0896, 0x089a, 0x089f, 0x08a4, 0x08a9, 0x08ae, 0x08b3, 0x08b8, 0x08bd, 0x08c1,+ 0x08c6, 0x08cb, 0x08d0, 0x08d5, 0x08da, 0x08df, 0x08e3, 0x08e8, 0x08ed, 0x08f2, 0x08f7, 0x08fc, 0x0901, 0x0905, 0x090a, 0x090f,+ 0x0914, 0x0919, 0x091e, 0x0922, 0x0927, 0x092c, 0x0931, 0x0936, 0x093b, 0x093f, 0x0944, 0x0949, 0x094e, 0x0953, 0x0958, 0x095c,+ 0x0961, 0x0966, 0x096b, 0x0970, 0x0975, 0x0979, 0x097e, 0x0983, 0x0988, 0x098d, 0x0992, 0x0996, 0x099b, 0x09a0, 0x09a5, 0x09aa,+ 0x09ae, 0x09b3, 0x09b8, 0x09bd, 0x09c2, 0x09c6, 0x09cb, 0x09d0, 0x09d5, 0x09da, 0x09de, 0x09e3, 0x09e8, 0x09ed, 0x09f2, 0x09f6,+ 0x09fb, 0x0a00, 0x0a05, 0x0a0a, 0x0a0e, 0x0a13, 0x0a18, 0x0a1d, 0x0a22, 0x0a26, 0x0a2b, 0x0a30, 0x0a35, 0x0a39, 0x0a3e, 0x0a43,+ 0x0a48, 0x0a4d, 0x0a51, 0x0a56, 0x0a5b, 0x0a60, 0x0a64, 0x0a69, 0x0a6e, 0x0a73, 0x0a77, 0x0a7c, 0x0a81, 0x0a86, 0x0a8b, 0x0a8f,+ 0x0a94, 0x0a99, 0x0a9e, 0x0aa2, 0x0aa7, 0x0aac, 0x0ab1, 0x0ab5, 0x0aba, 0x0abf, 0x0ac4, 0x0ac8, 0x0acd, 0x0ad2, 0x0ad7, 0x0adb,+ 0x0ae0, 0x0ae5, 0x0ae9, 0x0aee, 0x0af3, 0x0af8, 0x0afc, 0x0b01, 0x0b06, 0x0b0b, 0x0b0f, 0x0b14, 0x0b19, 0x0b1e, 0x0b22, 0x0b27,+ 0x0b2c, 0x0b30, 0x0b35, 0x0b3a, 0x0b3f, 0x0b43, 0x0b48, 0x0b4d, 0x0b51, 0x0b56, 0x0b5b, 0x0b60, 0x0b64, 0x0b69, 0x0b6e, 0x0b72,+ 0x0b77, 0x0b7c, 0x0b80, 0x0b85, 0x0b8a, 0x0b8f, 0x0b93, 0x0b98, 0x0b9d, 0x0ba1, 0x0ba6, 0x0bab, 0x0baf, 0x0bb4, 0x0bb9, 0x0bbd,+ 0x0bc2, 0x0bc7, 0x0bcb, 0x0bd0, 0x0bd5, 0x0bd9, 0x0bde, 0x0be3, 0x0be7, 0x0bec, 0x0bf1, 0x0bf5, 0x0bfa, 0x0bff, 0x0c03, 0x0c08,+ 0x0c0d, 0x0c11, 0x0c16, 0x0c1b, 0x0c1f, 0x0c24, 0x0c29, 0x0c2d, 0x0c32, 0x0c37, 0x0c3b, 0x0c40, 0x0c45, 0x0c49, 0x0c4e, 0x0c53,+ 0x0c57, 0x0c5c, 0x0c60, 0x0c65, 0x0c6a, 0x0c6e, 0x0c73, 0x0c78, 0x0c7c, 0x0c81, 0x0c86, 0x0c8a, 0x0c8f, 0x0c93, 0x0c98, 0x0c9d,+ 0x0ca1, 0x0ca6, 0x0cab, 0x0caf, 0x0cb4, 0x0cb8, 0x0cbd, 0x0cc2, 0x0cc6, 0x0ccb, 0x0ccf, 0x0cd4, 0x0cd9, 0x0cdd, 0x0ce2, 0x0ce6,+ 0x0ceb, 0x0cf0, 0x0cf4, 0x0cf9, 0x0cfd, 0x0d02, 0x0d07, 0x0d0b, 0x0d10, 0x0d14, 0x0d19, 0x0d1e, 0x0d22, 0x0d27, 0x0d2b, 0x0d30,+ 0x0d34, 0x0d39, 0x0d3e, 0x0d42, 0x0d47, 0x0d4b, 0x0d50, 0x0d54, 0x0d59, 0x0d5e, 0x0d62, 0x0d67, 0x0d6b, 0x0d70, 0x0d74, 0x0d79,+ 0x0d7d, 0x0d82, 0x0d87, 0x0d8b, 0x0d90, 0x0d94, 0x0d99, 0x0d9d, 0x0da2, 0x0da6, 0x0dab, 0x0daf, 0x0db4, 0x0db9, 0x0dbd, 0x0dc2,+ 0x0dc6, 0x0dcb, 0x0dcf, 0x0dd4, 0x0dd8, 0x0ddd, 0x0de1, 0x0de6, 0x0dea, 0x0def, 0x0df3, 0x0df8, 0x0dfc, 0x0e01, 0x0e05, 0x0e0a,+ 0x0e0f, 0x0e13, 0x0e18, 0x0e1c, 0x0e21, 0x0e25, 0x0e2a, 0x0e2e, 0x0e33, 0x0e37, 0x0e3c, 0x0e40, 0x0e45, 0x0e49, 0x0e4e, 0x0e52,+ 0x0e56, 0x0e5b, 0x0e5f, 0x0e64, 0x0e68, 0x0e6d, 0x0e71, 0x0e76, 0x0e7a, 0x0e7f, 0x0e83, 0x0e88, 0x0e8c, 0x0e91, 0x0e95, 0x0e9a,+ 0x0e9e, 0x0ea3, 0x0ea7, 0x0eac, 0x0eb0, 0x0eb4, 0x0eb9, 0x0ebd, 0x0ec2, 0x0ec6, 0x0ecb, 0x0ecf, 0x0ed4, 0x0ed8, 0x0edc, 0x0ee1,+ 0x0ee5, 0x0eea, 0x0eee, 0x0ef3, 0x0ef7, 0x0efc, 0x0f00, 0x0f04, 0x0f09, 0x0f0d, 0x0f12, 0x0f16, 0x0f1b, 0x0f1f, 0x0f23, 0x0f28,+ 0x0f2c, 0x0f31, 0x0f35, 0x0f3a, 0x0f3e, 0x0f42, 0x0f47, 0x0f4b, 0x0f50, 0x0f54, 0x0f58, 0x0f5d, 0x0f61, 0x0f66, 0x0f6a, 0x0f6e,+ 0x0f73, 0x0f77, 0x0f7c, 0x0f80, 0x0f84, 0x0f89, 0x0f8d, 0x0f91, 0x0f96, 0x0f9a, 0x0f9f, 0x0fa3, 0x0fa7, 0x0fac, 0x0fb0, 0x0fb5,+ 0x0fb9, 0x0fbd, 0x0fc2, 0x0fc6, 0x0fca, 0x0fcf, 0x0fd3, 0x0fd7, 0x0fdc, 0x0fe0, 0x0fe5, 0x0fe9, 0x0fed, 0x0ff2, 0x0ff6, 0x0ffa,+ 0x0fff, 0x1003, 0x1007, 0x100c, 0x1010, 0x1014, 0x1019, 0x101d, 0x1021, 0x1026, 0x102a, 0x102e, 0x1033, 0x1037, 0x103b, 0x1040,+ 0x1044, 0x1048, 0x104d, 0x1051, 0x1055, 0x105a, 0x105e, 0x1062, 0x1067, 0x106b, 0x106f, 0x1073, 0x1078, 0x107c, 0x1080, 0x1085,+ 0x1089, 0x108d, 0x1092, 0x1096, 0x109a, 0x109e, 0x10a3, 0x10a7, 0x10ab, 0x10b0, 0x10b4, 0x10b8, 0x10bc, 0x10c1, 0x10c5, 0x10c9,+ 0x10ce, 0x10d2, 0x10d6, 0x10da, 0x10df, 0x10e3, 0x10e7, 0x10eb, 0x10f0, 0x10f4, 0x10f8, 0x10fd, 0x1101, 0x1105, 0x1109, 0x110e,+ 0x1112, 0x1116, 0x111a, 0x111f, 0x1123, 0x1127, 0x112b, 0x1130, 0x1134, 0x1138, 0x113c, 0x1140, 0x1145, 0x1149, 0x114d, 0x1151,+ 0x1156, 0x115a, 0x115e, 0x1162, 0x1166, 0x116b, 0x116f, 0x1173, 0x1177, 0x117c, 0x1180, 0x1184, 0x1188, 0x118c, 0x1191, 0x1195,+ 0x1199, 0x119d, 0x11a1, 0x11a6, 0x11aa, 0x11ae, 0x11b2, 0x11b6, 0x11bb, 0x11bf, 0x11c3, 0x11c7, 0x11cb, 0x11cf, 0x11d4, 0x11d8,+ 0x11dc, 0x11e0, 0x11e4, 0x11e9, 0x11ed, 0x11f1, 0x11f5, 0x11f9, 0x11fd, 0x1202, 0x1206, 0x120a, 0x120e, 0x1212, 0x1216, 0x121a,+ 0x121f, 0x1223, 0x1227, 0x122b, 0x122f, 0x1233, 0x1237, 0x123c, 0x1240, 0x1244, 0x1248, 0x124c, 0x1250, 0x1254, 0x1259, 0x125d,+ 0x1261, 0x1265, 0x1269, 0x126d, 0x1271, 0x1275, 0x127a, 0x127e, 0x1282, 0x1286, 0x128a, 0x128e, 0x1292, 0x1296, 0x129a, 0x129f,+ 0x12a3, 0x12a7, 0x12ab, 0x12af, 0x12b3, 0x12b7, 0x12bb, 0x12bf, 0x12c3, 0x12c7, 0x12cc, 0x12d0, 0x12d4, 0x12d8, 0x12dc, 0x12e0,+ 0x12e4, 0x12e8, 0x12ec, 0x12f0, 0x12f4, 0x12f8, 0x12fc, 0x1301, 0x1305, 0x1309, 0x130d, 0x1311, 0x1315, 0x1319, 0x131d, 0x1321,+ 0x1325, 0x1329, 0x132d, 0x1331, 0x1335, 0x1339, 0x133d, 0x1341, 0x1345, 0x1349, 0x134d, 0x1351, 0x1355, 0x135a, 0x135e, 0x1362,+ 0x1366, 0x136a, 0x136e, 0x1372, 0x1376, 0x137a, 0x137e, 0x1382, 0x1386, 0x138a, 0x138e, 0x1392, 0x1396, 0x139a, 0x139e, 0x13a2,+ 0x13a6, 0x13aa, 0x13ae, 0x13b2, 0x13b6, 0x13ba, 0x13be, 0x13c2, 0x13c6, 0x13ca, 0x13ce, 0x13d2, 0x13d6, 0x13da, 0x13de, 0x13e2,+ 0x13e6, 0x13e9, 0x13ed, 0x13f1, 0x13f5, 0x13f9, 0x13fd, 0x1401, 0x1405, 0x1409, 0x140d, 0x1411, 0x1415, 0x1419, 0x141d, 0x1421,+ 0x1425, 0x1429, 0x142d, 0x1431, 0x1435, 0x1439, 0x143d, 0x1440, 0x1444, 0x1448, 0x144c, 0x1450, 0x1454, 0x1458, 0x145c, 0x1460,+ 0x1464, 0x1468, 0x146c, 0x1470, 0x1473, 0x1477, 0x147b, 0x147f, 0x1483, 0x1487, 0x148b, 0x148f, 0x1493, 0x1497, 0x149b, 0x149e,+ 0x14a2, 0x14a6, 0x14aa, 0x14ae, 0x14b2, 0x14b6, 0x14ba, 0x14be, 0x14c1, 0x14c5, 0x14c9, 0x14cd, 0x14d1, 0x14d5, 0x14d9, 0x14dd,+ 0x14e0, 0x14e4, 0x14e8, 0x14ec, 0x14f0, 0x14f4, 0x14f8, 0x14fb, 0x14ff, 0x1503, 0x1507, 0x150b, 0x150f, 0x1513, 0x1516, 0x151a,+ 0x151e, 0x1522, 0x1526, 0x152a, 0x152d, 0x1531, 0x1535, 0x1539, 0x153d, 0x1541, 0x1544, 0x1548, 0x154c, 0x1550, 0x1554, 0x1558,+ 0x155b, 0x155f, 0x1563, 0x1567, 0x156b, 0x156e, 0x1572, 0x1576, 0x157a, 0x157e, 0x1581, 0x1585, 0x1589, 0x158d, 0x1591, 0x1594,+ 0x1598, 0x159c, 0x15a0, 0x15a4, 0x15a7, 0x15ab, 0x15af, 0x15b3, 0x15b7, 0x15ba, 0x15be, 0x15c2, 0x15c6, 0x15c9, 0x15cd, 0x15d1,+ 0x15d5, 0x15d8, 0x15dc, 0x15e0, 0x15e4, 0x15e8, 0x15eb, 0x15ef, 0x15f3, 0x15f7, 0x15fa, 0x15fe, 0x1602, 0x1606, 0x1609, 0x160d,+ 0x1611, 0x1614, 0x1618, 0x161c, 0x1620, 0x1623, 0x1627, 0x162b, 0x162f, 0x1632, 0x1636, 0x163a, 0x163e, 0x1641, 0x1645, 0x1649,+ 0x164c, 0x1650, 0x1654, 0x1658, 0x165b, 0x165f, 0x1663, 0x1666, 0x166a, 0x166e, 0x1671, 0x1675, 0x1679, 0x167d, 0x1680, 0x1684,+ 0x1688, 0x168b, 0x168f, 0x1693, 0x1696, 0x169a, 0x169e, 0x16a1, 0x16a5, 0x16a9, 0x16ac, 0x16b0, 0x16b4, 0x16b7, 0x16bb, 0x16bf,+ 0x16c2, 0x16c6, 0x16ca, 0x16cd, 0x16d1, 0x16d5, 0x16d8, 0x16dc, 0x16e0, 0x16e3, 0x16e7, 0x16eb, 0x16ee, 0x16f2, 0x16f6, 0x16f9,+ 0x16fd, 0x1700, 0x1704, 0x1708, 0x170b, 0x170f, 0x1713, 0x1716, 0x171a, 0x171d, 0x1721, 0x1725, 0x1728, 0x172c, 0x1730, 0x1733,+ 0x1737, 0x173a, 0x173e, 0x1742, 0x1745, 0x1749, 0x174c, 0x1750, 0x1754, 0x1757, 0x175b, 0x175e, 0x1762, 0x1766, 0x1769, 0x176d,+ 0x1770, 0x1774, 0x1778, 0x177b, 0x177f, 0x1782, 0x1786, 0x1789, 0x178d, 0x1791, 0x1794, 0x1798, 0x179b, 0x179f, 0x17a2, 0x17a6,+ 0x17aa, 0x17ad, 0x17b1, 0x17b4, 0x17b8, 0x17bb, 0x17bf, 0x17c2, 0x17c6, 0x17c9, 0x17cd, 0x17d1, 0x17d4, 0x17d8, 0x17db, 0x17df,+ 0x17e2, 0x17e6, 0x17e9, 0x17ed, 0x17f0, 0x17f4, 0x17f7, 0x17fb, 0x17fe, 0x1802, 0x1806, 0x1809, 0x180d, 0x1810, 0x1814, 0x1817,+ 0x181b, 0x181e, 0x1822, 0x1825, 0x1829, 0x182c, 0x1830, 0x1833, 0x1837, 0x183a, 0x183e, 0x1841, 0x1845, 0x1848, 0x184c, 0x184f,+ 0x1853, 0x1856, 0x185a, 0x185d, 0x1860, 0x1864, 0x1867, 0x186b, 0x186e, 0x1872, 0x1875, 0x1879, 0x187c, 0x1880, 0x1883, 0x1887,+ 0x188a, 0x188e, 0x1891, 0x1894, 0x1898, 0x189b, 0x189f, 0x18a2, 0x18a6, 0x18a9, 0x18ad, 0x18b0, 0x18b3, 0x18b7, 0x18ba, 0x18be,+ 0x18c1, 0x18c5, 0x18c8, 0x18cc, 0x18cf, 0x18d2, 0x18d6, 0x18d9, 0x18dd, 0x18e0, 0x18e3, 0x18e7, 0x18ea, 0x18ee, 0x18f1, 0x18f5,+ 0x18f8, 0x18fb, 0x18ff, 0x1902, 0x1906, 0x1909, 0x190c, 0x1910, 0x1913, 0x1917, 0x191a, 0x191d, 0x1921, 0x1924, 0x1928, 0x192b,+ 0x192e, 0x1932, 0x1935, 0x1938, 0x193c, 0x193f, 0x1943, 0x1946, 0x1949, 0x194d, 0x1950, 0x1953, 0x1957, 0x195a, 0x195d, 0x1961,+ 0x1964, 0x1968, 0x196b, 0x196e, 0x1972, 0x1975, 0x1978, 0x197c, 0x197f, 0x1982, 0x1986, 0x1989, 0x198c, 0x1990, 0x1993, 0x1996,+ 0x199a, 0x199d, 0x19a0, 0x19a4, 0x19a7, 0x19aa, 0x19ae, 0x19b1, 0x19b4, 0x19b8, 0x19bb, 0x19be, 0x19c2, 0x19c5, 0x19c8, 0x19cc,+ 0x19cf, 0x19d2, 0x19d5, 0x19d9, 0x19dc, 0x19df, 0x19e3, 0x19e6, 0x19e9, 0x19ed, 0x19f0, 0x19f3, 0x19f6, 0x19fa, 0x19fd, 0x1a00,+ 0x1a04, 0x1a07, 0x1a0a, 0x1a0d, 0x1a11, 0x1a14, 0x1a17, 0x1a1b, 0x1a1e, 0x1a21, 0x1a24, 0x1a28, 0x1a2b, 0x1a2e, 0x1a31, 0x1a35,+ 0x1a38, 0x1a3b, 0x1a3e, 0x1a42, 0x1a45, 0x1a48, 0x1a4b, 0x1a4f, 0x1a52, 0x1a55, 0x1a58, 0x1a5c, 0x1a5f, 0x1a62, 0x1a65, 0x1a69,+ 0x1a6c, 0x1a6f, 0x1a72, 0x1a76, 0x1a79, 0x1a7c, 0x1a7f, 0x1a83, 0x1a86, 0x1a89, 0x1a8c, 0x1a8f, 0x1a93, 0x1a96, 0x1a99, 0x1a9c,+ 0x1a9f, 0x1aa3, 0x1aa6, 0x1aa9, 0x1aac, 0x1ab0, 0x1ab3, 0x1ab6, 0x1ab9, 0x1abc, 0x1ac0, 0x1ac3, 0x1ac6, 0x1ac9, 0x1acc, 0x1acf,+ 0x1ad3, 0x1ad6, 0x1ad9, 0x1adc, 0x1adf, 0x1ae3, 0x1ae6, 0x1ae9, 0x1aec, 0x1aef, 0x1af2, 0x1af6, 0x1af9, 0x1afc, 0x1aff, 0x1b02,+ 0x1b05, 0x1b09, 0x1b0c, 0x1b0f, 0x1b12, 0x1b15, 0x1b18, 0x1b1c, 0x1b1f, 0x1b22, 0x1b25, 0x1b28, 0x1b2b, 0x1b2e, 0x1b32, 0x1b35,+ 0x1b38, 0x1b3b, 0x1b3e, 0x1b41, 0x1b44, 0x1b48, 0x1b4b, 0x1b4e, 0x1b51, 0x1b54, 0x1b57, 0x1b5a, 0x1b5d, 0x1b61, 0x1b64, 0x1b67,+ 0x1b6a, 0x1b6d, 0x1b70, 0x1b73, 0x1b76, 0x1b79, 0x1b7d, 0x1b80, 0x1b83, 0x1b86, 0x1b89, 0x1b8c, 0x1b8f, 0x1b92, 0x1b95, 0x1b98,+ 0x1b9c, 0x1b9f, 0x1ba2, 0x1ba5, 0x1ba8, 0x1bab, 0x1bae, 0x1bb1, 0x1bb4, 0x1bb7, 0x1bba, 0x1bbd, 0x1bc1, 0x1bc4, 0x1bc7, 0x1bca,+ 0x1bcd, 0x1bd0, 0x1bd3, 0x1bd6, 0x1bd9, 0x1bdc, 0x1bdf, 0x1be2, 0x1be5, 0x1be8, 0x1beb, 0x1bee, 0x1bf2, 0x1bf5, 0x1bf8, 0x1bfb,+ 0x1bfe, 0x1c01, 0x1c04, 0x1c07, 0x1c0a, 0x1c0d, 0x1c10, 0x1c13, 0x1c16, 0x1c19, 0x1c1c, 0x1c1f, 0x1c22, 0x1c25, 0x1c28, 0x1c2b,+ 0x1c2e, 0x1c31, 0x1c34, 0x1c37, 0x1c3a, 0x1c3d, 0x1c40, 0x1c43, 0x1c46, 0x1c49, 0x1c4c, 0x1c4f, 0x1c52, 0x1c55, 0x1c58, 0x1c5b,+ 0x1c5e, 0x1c61, 0x1c64, 0x1c67, 0x1c6a, 0x1c6d, 0x1c70, 0x1c73, 0x1c76, 0x1c79, 0x1c7c, 0x1c7f, 0x1c82, 0x1c85, 0x1c88, 0x1c8b,+ 0x1c8e, 0x1c91, 0x1c94, 0x1c97, 0x1c9a, 0x1c9d, 0x1ca0, 0x1ca3, 0x1ca6, 0x1ca9, 0x1cac, 0x1caf, 0x1cb2, 0x1cb5, 0x1cb8, 0x1cbb,+ 0x1cbe, 0x1cc1, 0x1cc3, 0x1cc6, 0x1cc9, 0x1ccc, 0x1ccf, 0x1cd2, 0x1cd5, 0x1cd8, 0x1cdb, 0x1cde, 0x1ce1, 0x1ce4, 0x1ce7, 0x1cea,+ 0x1ced, 0x1cf0, 0x1cf3, 0x1cf5, 0x1cf8, 0x1cfb, 0x1cfe, 0x1d01, 0x1d04, 0x1d07, 0x1d0a, 0x1d0d, 0x1d10, 0x1d13, 0x1d16, 0x1d18,+ 0x1d1b, 0x1d1e, 0x1d21, 0x1d24, 0x1d27, 0x1d2a, 0x1d2d, 0x1d30, 0x1d33, 0x1d35, 0x1d38, 0x1d3b, 0x1d3e, 0x1d41, 0x1d44, 0x1d47,+ 0x1d4a, 0x1d4d, 0x1d4f, 0x1d52, 0x1d55, 0x1d58, 0x1d5b, 0x1d5e, 0x1d61, 0x1d64, 0x1d66, 0x1d69, 0x1d6c, 0x1d6f, 0x1d72, 0x1d75,+ 0x1d78, 0x1d7b, 0x1d7d, 0x1d80, 0x1d83, 0x1d86, 0x1d89, 0x1d8c, 0x1d8e, 0x1d91, 0x1d94, 0x1d97, 0x1d9a, 0x1d9d, 0x1da0, 0x1da2,+ 0x1da5, 0x1da8, 0x1dab, 0x1dae, 0x1db1, 0x1db3, 0x1db6, 0x1db9, 0x1dbc, 0x1dbf, 0x1dc2, 0x1dc4, 0x1dc7, 0x1dca, 0x1dcd, 0x1dd0,+ 0x1dd3, 0x1dd5, 0x1dd8, 0x1ddb, 0x1dde, 0x1de1, 0x1de3, 0x1de6, 0x1de9, 0x1dec, 0x1def, 0x1df1, 0x1df4, 0x1df7, 0x1dfa, 0x1dfd,+ 0x1dff, 0x1e02, 0x1e05, 0x1e08, 0x1e0b, 0x1e0d, 0x1e10, 0x1e13, 0x1e16, 0x1e19, 0x1e1b, 0x1e1e, 0x1e21, 0x1e24, 0x1e26, 0x1e29,+ 0x1e2c, 0x1e2f, 0x1e32, 0x1e34, 0x1e37, 0x1e3a, 0x1e3d, 0x1e3f, 0x1e42, 0x1e45, 0x1e48, 0x1e4a, 0x1e4d, 0x1e50, 0x1e53, 0x1e55,+ 0x1e58, 0x1e5b, 0x1e5e, 0x1e60, 0x1e63, 0x1e66, 0x1e69, 0x1e6b, 0x1e6e, 0x1e71, 0x1e74, 0x1e76, 0x1e79, 0x1e7c, 0x1e7f, 0x1e81,+ 0x1e84, 0x1e87, 0x1e8a, 0x1e8c, 0x1e8f, 0x1e92, 0x1e94, 0x1e97, 0x1e9a, 0x1e9d, 0x1e9f, 0x1ea2, 0x1ea5, 0x1ea8, 0x1eaa, 0x1ead,+ 0x1eb0, 0x1eb2, 0x1eb5, 0x1eb8, 0x1eba, 0x1ebd, 0x1ec0, 0x1ec3, 0x1ec5, 0x1ec8, 0x1ecb, 0x1ecd, 0x1ed0, 0x1ed3, 0x1ed5, 0x1ed8,+ 0x1edb, 0x1ede, 0x1ee0, 0x1ee3, 0x1ee6, 0x1ee8, 0x1eeb, 0x1eee, 0x1ef0, 0x1ef3, 0x1ef6, 0x1ef8, 0x1efb, 0x1efe, 0x1f00, 0x1f03,+ 0x1f06, 0x1f08, 0x1f0b, 0x1f0e, 0x1f10, 0x1f13, 0x1f16, 0x1f18, 0x1f1b, 0x1f1e, 0x1f20, 0x1f23, 0x1f26, 0x1f28, 0x1f2b, 0x1f2e,+ 0x1f30, 0x1f33, 0x1f36, 0x1f38, 0x1f3b, 0x1f3d, 0x1f40, 0x1f43, 0x1f45, 0x1f48, 0x1f4b, 0x1f4d, 0x1f50, 0x1f53, 0x1f55, 0x1f58,+ 0x1f5a, 0x1f5d, 0x1f60, 0x1f62, 0x1f65, 0x1f68, 0x1f6a, 0x1f6d, 0x1f6f, 0x1f72, 0x1f75, 0x1f77, 0x1f7a, 0x1f7c, 0x1f7f, 0x1f82,+ 0x1f84, 0x1f87, 0x1f8a, 0x1f8c, 0x1f8f, 0x1f91, 0x1f94, 0x1f97, 0x1f99, 0x1f9c, 0x1f9e, 0x1fa1, 0x1fa4, 0x1fa6, 0x1fa9, 0x1fab,+ 0x1fae, 0x1fb0, 0x1fb3, 0x1fb6, 0x1fb8, 0x1fbb, 0x1fbd, 0x1fc0, 0x1fc3, 0x1fc5, 0x1fc8, 0x1fca, 0x1fcd, 0x1fcf, 0x1fd2, 0x1fd5,+ 0x1fd7, 0x1fda, 0x1fdc, 0x1fdf, 0x1fe1, 0x1fe4, 0x1fe6, 0x1fe9, 0x1fec, 0x1fee, 0x1ff1, 0x1ff3, 0x1ff6, 0x1ff8, 0x1ffb, 0x1ffd,+ 0x2000,+};diff --git a/games/numpico/src/femto8/p8_audio.h b/games/numpico/src/femto8/p8_audio.hnew file mode 100644index 00000000..fe5c690f--- /dev/null+++ b/games/numpico/src/femto8/p8_audio.h@@ -0,0 +1,22 @@+/*+ * p8_audio.h+ *+ * Created on: Dec 13, 2023+ * Author: bbaker+ *+ * Changed for NumPico: the calculator has no speaker, so sound and music do nothing and nothing+ * is ever playing.+ */++#include <stdint.h>++#ifndef P8_AUDIO_H+#define P8_AUDIO_H++static inline void audio_sound(int32_t index, int32_t channel, uint32_t start, uint32_t end) {}+static inline void audio_music(int32_t index, int32_t fade_ms, int32_t mask) {}+static inline void audio_stop(void) {}+/* stat(16..26) and stat(46..57): no sound, no music */+static inline int32_t audio_stat(int32_t index) { return index == 57 ? 0 : -1; }++#endifdiff --git a/games/numpico/src/femto8/p8_emu.h b/games/numpico/src/femto8/p8_emu.hnew file mode 100644index 00000000..d9f4286d--- /dev/null+++ b/games/numpico/src/femto8/p8_emu.h@@ -0,0 +1,216 @@+/*+ * p8_emu.h+ *+ * Created on: Dec 13, 2023+ * Author: bbaker+ */++#ifndef P8_EMU_H+#define P8_EMU_H++#if defined(_WIN32)+#include <direct.h> // _mkdir+#else+#include <sys/stat.h> // mkdir+#endif+/* Changed for NumPico: the calculator's platform (pico.c) instead of SDL and FreeRTOS, and PICO-8's+ * memory as far as 0x7fff (the upper 32 KB is left out: see P8_RAM_SIZE). */+#include <limits.h>+#include <setjmp.h>+#include <stdbool.h>+#include <stdint.h>+#include <string.h>++#define PROGNAME "femto8"++#ifndef MAX+#define MAX(a, b) ((a) > (b) ? a : b)+#define MIN(a, b) ((a) < (b) ? a : b)+#endif+#define IS_EVEN(n) (((n) ^ 1) == ((n) + 1))+#define NIBBLE_SWAP(n) (((n) << 4) | ((n) >> 4))++#ifndef PATH_MAX+#define PATH_MAX 256+#endif++#define P8_WIDTH 128+#define P8_HEIGHT 128+#define MEMORY_SPRITES 0+#define MEMORY_SPRITES_SIZE 0x1000+#define MEMORY_SPRITES_MAP 0x1000+#define MEMORY_SPRITES_MAP_SIZE 0x1000+#define MEMORY_MAP 0x2000+#define MEMORY_MAP_SIZE 0x1000+#define MEMORY_SPRITEFLAGS 0x3000+#define MEMORY_SPRITEFLAGS_SIZE 0x100+#define MEMORY_MUSIC 0x3100+#define MEMORY_MUSIC_SIZE 0x100+#define MEMORY_SFX 0x3200+#define MEMORY_SFX_SIZE 0x1100+#define MEMORY_WORKRAM 0x4300+#define MEMORY_WORKRAM_SIZE 0x1b00+#define MEMORY_FONT 0x5600+#define MEMORY_FONT_SIZE 0x2000+#define MEMORY_CARTDATA 0x5e00+#define MEMORY_CARTDATA_SIZE 0x100+#define MEMORY_DRAWSTATE 0x5f00+#define MEMORY_DRAWSTATE_SIZE 0x40+#define MEMORY_HARDWARESTATE 0x5f40+#define MEMORY_HARDWARESTATE_SIZE 0x40+#define MEMORY_GPIO 0x5f80+#define MEMORY_GPIO_SIZE 0x80+#define MEMORY_SCREEN 0x6000+#define MEMORY_SCREEN_SIZE 0x2000++#define MEMORY_SIZE (1024 * 64)+#define CART_MEMORY_SIZE 0x4300++#define MEMORY_PALETTES 0x5f00+#define MEMORY_CLIPRECT 0x5f20+#define MEMORY_LEFT_MARGIN 0x5f24+#define MEMORY_PENCOLOR 0x5f25+#define MEMORY_CURSOR 0x5f26+#define MEMORY_CAMERA 0x5f28+#define MEMORY_SCREEN_TRANSFORM 0x5f2c+#define MEMORY_DEVKIT_MODE 0x5f2d+#define MEMORY_AUDIO_PAUSE 0x5f2f+#define MEMORY_SUPPRESS_PAUSE 0x5f30+#define MEMORY_FILLP 0x5f31+#define MEMORY_FILLP_ATTR 0x5f33+#define MEMORY_COLOR_FILLP 0x5f34+#define MEMORY_LINE_VALID 0x5f35+#define MEMORY_MISCFLAGS 0x5f36+#define MEMORY_TLINE_MASK_X 0x5f38+#define MEMORY_TLINE_MASK_Y 0x5f39+#define MEMORY_TLINE_OFFSET_X 0x5f3a+#define MEMORY_TLINE_OFFSET_Y 0x5f3b+#define MEMORY_LINE_X 0x5f3c+#define MEMORY_LINE_Y 0x5f3e+#define MEMORY_RNG_STATE 0x5f44+#define MEMORY_BUTTON_STATE 0x5f4c+#define MEMORY_SPRITE_PHYS 0x5f54+#define MEMORY_SCREEN_PHYS 0x5f55+#define MEMORY_MAP_START 0x5f56+#define MEMORY_MAP_WIDTH 0x5f57+#define MEMORY_TEXT_ATTRS 0x5f58+#define MEMORY_SGET_DEFAULT 0x5f59+#define MEMORY_MGET_DEFAULT 0x5f5a+#define MEMORY_PGET_DEFAULT 0x5f5b+#define MEMORY_TEXT_CHAR_SIZE 0x5f59+#define MEMORY_TEXT_CHAR_SIZE2 0x5f5a+#define MEMORY_TEXT_OFFSET 0x5f5b+#define MEMORY_AUTO_REPEAT_DELAY 0x5f5c+#define MEMORY_AUTO_REPEAT_INTERVAL 0x5f5d+#define MEMORY_RW_MASK 0x5f5e+#define MEMORY_HIGH_COLOUR_MODE 0x5f5f+#define MEMORY_PALETTE_SECONDARY 0x5f60++#define TICKS_PER_SECOND 128+#define SCREEN_SIZE 128 * 128 * 4+#define GLYPH_WIDTH 4+#define GLYPH_HEIGHT 6+#define SPRITE_WIDTH 8+#define SPRITE_HEIGHT 8+#define BUTTON_COUNT 7+#define BUTTON_REPEAT_COUNT 6+#define BUTTON_INTERNAL_COUNT 13+#define PLAYER_COUNT 2++#define STAT_MEM_USAGE 0+#define STAT_CPU_USAGE 1+#define STAT_SYSTEM_CPU_USAGE 2+#define STAT_CURRENT_DISPLAY 3+#define STAT_CLIPBOARD 4+#define STAT_VERSION 5+#define STAT_PARAM 6+#define STAT_FRAMERATE 7+#define STAT_TARGET_FRAMERATE 8+#define STAT_NUM_DISPLAYS 11+#define STAT_PAUSE_MENU_X1 12+#define STAT_PAUSE_MENU_Y1 13+#define STAT_PAUSE_MENU_X2 14+#define STAT_PAUSE_MENU_Y2 15+#define STAT_RAW_KEYBOARD 28+#define STAT_KEY_PRESSED 30+#define STAT_KEY_NAME 31+#define STAT_MOUSE_X 32+#define STAT_MOUSE_Y 33+#define STAT_MOUSE_BUTTONS 34+#define STAT_MOUSE_WHEEL 36+#define STAT_MOUSE_XREL 38+#define STAT_MOUSE_YREL 39+#define STAT_YEAR_UTC 80+#define STAT_MONTH_UTC 81+#define STAT_DAY_UTC 82+#define STAT_HOUR_UTC 83+#define STAT_MINUTE_UTC 84+#define STAT_SECOND_UTC 85+#define STAT_YEAR 90+#define STAT_MONTH 91+#define STAT_DAY 92+#define STAT_HOUR 93+#define STAT_MINUTE 94+#define STAT_SECOND 95+#define STAT_RAW_GC 99+#define STAT_BREADCRUMB 100+#define STAT_BBS_CART_ID 101+#define STAT_LOAD_RESULT 107+#define STAT_PCM_BUFFER_SIZE 108+#define STAT_PCM_APP_BUFFER 109+#define STAT_CURRENT_PATH 124++#define DEFAULT_AUTO_REPEAT_DELAY 15+#define DEFAULT_AUTO_REPEAT_INTERVAL 4++#define OVERLAY_TRANSPARENT_COLOR 0++/* the memory the calculator keeps: 0x0000 to 0x7fff (reads past it give 0, writes are dropped) */+#define P8_RAM_SIZE 0x8000++enum+{+ PALTYPE_DRAW,+ PALTYPE_SCREEN,+ PALTYPE_SECONDARY+};++enum+{+ DRAWTYPE_DEFAULT,+ DRAWTYPE_GRAPHIC,+ DRAWTYPE_SPRITE+};++enum {+ COMPAT_OK = 0,+ COMPAT_SOME,+ COMPAT_NONE+};++extern unsigned m_fps;+extern unsigned m_frames;++extern uint8_t *m_memory;+extern const uint8_t *m_cart_memory;++extern char m_param_string[256];++void __attribute__ ((noreturn)) p8_abort(void);+void __attribute__ ((noreturn)) p8_restart(void);+void p8_check_for_next_frame(void);+unsigned p8_elapsed_time(void);+void p8_flip(void);+void p8_render(void);+void p8_reset(void);+void p8_seed_rng_state(uint32_t seed);+bool p8_open_cartdata(const char *id);+void p8_delayed_flush_cartdata(void);+void p8_pump_events(void);+void p8_show_pause_menu(void);+/* load(): another of the carts, by name; returns only when there's none */+bool p8_load_cart(const char *name, const char *param);+/* reload() from another cart: its ROM, or NULL */+const uint8_t *p8_cart_rom(const char *name);++#endifdiff --git a/games/numpico/src/femto8/p8_input.h b/games/numpico/src/femto8/p8_input.hnew file mode 100644index 00000000..a8b7afe3--- /dev/null+++ b/games/numpico/src/femto8/p8_input.h@@ -0,0 +1,37 @@+/**+ * Copyright (C) 2026 Chris January, Ben Baker, and contributors+ *+ * Changed for NumPico: only PICO-8's buttons (the calculator's keys are read in pico.c).+ */++#ifndef P8_INPUT_H+#define P8_INPUT_H++#include "p8_emu.h"++enum+{+ BUTTON_LEFT = 0,+ BUTTON_RIGHT = 1,+ BUTTON_UP = 2,+ BUTTON_DOWN = 3,+ BUTTON_ACTION1 = 4,+ BUTTON_ACTION2 = 5,+ BUTTON_PAUSE = 6,+};++enum+{+ BUTTON_MASK_LEFT = (1 << BUTTON_LEFT),+ BUTTON_MASK_RIGHT = (1 << BUTTON_RIGHT),+ BUTTON_MASK_UP = (1 << BUTTON_UP),+ BUTTON_MASK_DOWN = (1 << BUTTON_DOWN),+ BUTTON_MASK_ACTION1 = (1 << BUTTON_ACTION1),+ BUTTON_MASK_ACTION2 = (1 << BUTTON_ACTION2),+ BUTTON_MASK_PAUSE = (1 << BUTTON_PAUSE),+};++extern uint16_t m_buttons[PLAYER_COUNT];+extern uint16_t m_buttonsp[PLAYER_COUNT];++#endifdiff --git a/games/numpico/src/femto8/p8_lua.c b/games/numpico/src/femto8/p8_lua.cnew file mode 100644index 00000000..a135ce18--- /dev/null+++ b/games/numpico/src/femto8/p8_lua.c@@ -0,0 +1,2177 @@++/*+ * p8_lua.c+ *+ * Created on: Dec 13, 2023+ * Author: bbaker+ */++/*+ * Changed for NumPico: no files, no keyboard, mouse or clipboard, no sound; PICO-8's memory is+ * 32 KB (addresses past 0x7fff read 0 and take no writes); reload() and load() take the other+ * carts NumPico has; the Lua state's memory and the pause menu are the calculator's (pico.c).+ */++#include <assert.h>+#include <math.h>+#include <stdbool.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#define PICO_FONT_HERE+#include "pico_font.h"+#include "p8_audio.h"+#include "p8_emu.h"+#include "p8_input.h"+#include "p8_lua.h"+#include "p8_lua_helper.h"+#include "p8_print_helper.h"+#include "p8_pause_menu.h"+#include "lua.h"+#include "lualib.h"+#include "lauxlib.h"+#include "../pico.h"++lua_State *L = NULL;+static int m_status = 0;++++char m_str_buffer[256] = {0};++static int m_tline_precision = 13;+++int lua_load_api();+int lua_shutdown_api();+int lua_init_script(const char *file_name, const char *script, size_t script_len);+int lua_call_function(const char *name, int ret);+int lua_update();+int lua_draw();+int lua_init();++void lua_register_functions(lua_State *L);++static unsigned addr_remap(unsigned address)+{+ if (address < 0x2000)+ address = p8_sprite_base() | (address & 0x1fff);+ else if (address >= 0x6000 && address < 0x8000)+ address = p8_screen_base() | (address & 0x1fff);+ return address;+}++/* a byte of PICO-8's memory: 0 past what the calculator keeps */+static inline uint8_t mem_get(unsigned address)+{+ return address < P8_RAM_SIZE ? m_memory[address] : 0;+}++static inline void mem_set(unsigned address, uint8_t v)+{+ if (address < P8_RAM_SIZE)+ m_memory[address] = v;+}++// ****************************************************************+// *** Graphics ***+// ****************************************************************++// camera([x,] [y])+int camera(lua_State *L)+{+ int prev_cx, prev_cy;+ camera_get(&prev_cx, &prev_cy);++ int cx = lua_gettop(L) >= 1 ? lua_tointeger(L, 1) : 0;+ int cy = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : 0;++ camera_set(cx, cy);++ lua_pushinteger(L, prev_cx);+ lua_pushinteger(L, prev_cy);+ return 2;+}++// circ(x, y, [r,] [col])+int circ(lua_State *L)+{+ int x = lua_tointeger(L, 1);+ int y = lua_tointeger(L, 2);+ int r = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : 4;+ int col = lua_gettop(L) >= 4 ? lua_tointeger(L, 4) : pencolor_get();+ int fillp = lua_gettop(L) >= 4 ? (fix32_bits(lua_tonumber(L, 4)) & 0xffff) : 0;++ if (lua_gettop(L) >= 3 && (m_memory[MEMORY_MISCFLAGS] & 0x2)) {+ double r_real = fix32_to_double(lua_tonumber(L, 3));+ if (r_real - r >= 0.5)+ r++;+ }++ if (lua_gettop(L) >= 4)+ pencolor_set(col);++ draw_circ(x, y, r, col, fillp);++ return 0;+}++// circfill(x, y, [r,] [col])+int circfill(lua_State *L)+{+ int x = lua_tointeger(L, 1);+ int y = lua_tointeger(L, 2);+ int r = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : 4;+ int col = lua_gettop(L) >= 4 ? lua_tointeger(L, 4) : pencolor_get();+ int fillp = lua_gettop(L) >= 4 ? (fix32_bits(lua_tonumber(L, 4)) & 0xffff) : 0;++ if (lua_gettop(L) >= 3 && (m_memory[MEMORY_MISCFLAGS] & 0x2)) {+ double r_real = fix32_to_double(lua_tonumber(L, 3));+ if (r_real - r >= 0.5)+ r++;+ }++ if (lua_gettop(L) >= 4)+ pencolor_set(col);++ draw_circfill(x, y, r, col, fillp);++ return 0;+}++// clip(x, y, w, h)+int clip(lua_State *L)+{+ int prev_x0, prev_y0, prev_x1, prev_y1;+ clip_get(&prev_x0, &prev_y0, &prev_x1, &prev_y1);++ if (lua_gettop(L) < 4)+ clip_set(0, 0, P8_WIDTH, P8_HEIGHT);+ else+ {+ int x0 = lua_tointeger(L, 1);+ int y0 = lua_tointeger(L, 2);+ int w = lua_tointeger(L, 3);+ int h = lua_tointeger(L, 4);+ bool clip_previous = lua_gettop(L) >= 5 ? lua_toboolean(L, 5) : false;++ int clamp_x0 = 0, clamp_y0 = 0, clamp_x1 = P8_WIDTH, clamp_y1 = P8_HEIGHT;+ if (clip_previous) { clamp_x0 = prev_x0; clamp_y0 = prev_y0; clamp_x1 = prev_x1; clamp_y1 = prev_y1; }++ int x1 = x0 + w;+ int y1 = y0 + h;+ x0 = MAX(x0, clamp_x0);+ y0 = MAX(y0, clamp_y0);+ x1 = MIN(x1, clamp_x1);+ y1 = MIN(y1, clamp_y1);++ clip_set(x0, y0, x1-x0, y1-y0);+ }++ lua_pushinteger(L, prev_x0);+ lua_pushinteger(L, prev_y0);+ lua_pushinteger(L, prev_x1 - prev_x0);+ lua_pushinteger(L, prev_y1 - prev_y0);+ return 4;+}++// cls([color])+int cls(lua_State *L)+{+ int color = lua_gettop(L) == 1 ? lua_tointeger(L, -1) : 0;++ clear_screen(color);++ return 0;+}++// color(col)+int color(lua_State *L)+{+ int prev = pencolor_get();+ int col = lua_gettop(L) == 1 ? lua_tointeger(L, 1) : 6;++ pencolor_set(col);++ lua_pushinteger(L, prev);+ return 1;+}++// cursor([x,] [y,] [col])+int cursor(lua_State *L)+{+ int prev_x, prev_y;+ cursor_get(&prev_x, &prev_y);++ int x = lua_gettop(L) >= 1 ? lua_tointeger(L, 1) : 0;+ int y = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : 0;+ int color = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : -1;++ cursor_set(x, y, (color == -1) ? -1 : color);+ left_margin_set(x);++ lua_pushinteger(L, prev_x);+ lua_pushinteger(L, prev_y);+ return 2;+}++// fget(n, [f])+int fget(lua_State *L)+{+ int n = lua_tointeger(L, 1);+ uint8_t flags = m_memory[MEMORY_SPRITEFLAGS + n];++ if (lua_gettop(L) == 2)+ {+ int f = lua_tointeger(L, 2);+ lua_pushboolean(L, (flags & (1 << f)) != 0);+ }+ else+ {+ lua_pushinteger(L, flags);+ }++ return 1;+}++// fillp([pat])+int fillp(lua_State *L)+{+ if (lua_gettop(L) == 0) {+ m_memory[MEMORY_FILLP] = 0;+ m_memory[MEMORY_FILLP + 1] = 0;+ m_memory[MEMORY_FILLP_ATTR] = 0;+ } else {+ uint32_t n = fix32_bits(lua_tonumber(L, 1));+ m_memory[MEMORY_FILLP] = (n >> 16) & 0xff;+ m_memory[MEMORY_FILLP + 1] = (n >> 24) & 0xff;+ m_memory[MEMORY_FILLP_ATTR] = ((n & 0x8000) ? 1 : 0) | ((n & 0x4000) ? 2 : 0) | ((n & 0x2000) ? 4: 0);++ }+ return 0;+}++// flip()+int flip(lua_State *L)+{+ p8_flip();++ return 0;+}++int holdframe(lua_State *L)+{+ (void)L;+ return 0;+}++int _update_buttons(lua_State *L)+{+ (void)L;+ pico_update_buttons();+ return 0;+}++// fset(n, [f,] v)+int fset(lua_State *L)+{+ int n = lua_tointeger(L, 1);+ if (n < 0 || n > 255)+ return luaL_argerror(L, 1, "sprite index must be 0-255");++ if (lua_gettop(L) == 3)+ {+ int f = lua_tointeger(L, 2);+ bool v = lua_toboolean(L, 3);+ if (f < 0 || f > 7)+ return luaL_argerror(L, 2, "flag index must be 0-7");++ if (v)+ m_memory[MEMORY_SPRITEFLAGS + n] |= (1 << f);+ else+ m_memory[MEMORY_SPRITEFLAGS + n] &= ~(1 << f);+ }+ else+ {+ int f = lua_tointeger(L, 2);+ if (f < 0 || f > 255)+ return luaL_argerror(L, 2, "value must be 0-255");+ m_memory[MEMORY_SPRITEFLAGS + n] = f;+ }++ return 0;+}++// line([x0,] [y0,] x1, y1, [col])+int line(lua_State *L)+{+ int x0, y0, x1, y1, col, fillp, valid;++ if (lua_gettop(L) == 0) {+ m_memory[MEMORY_LINE_VALID] = 1;+ } else {+ if (lua_gettop(L) >= 4) {+ valid = 1;+ x0 = lua_tointeger(L, 1);+ y0 = lua_tointeger(L, 2);+ x1 = lua_tointeger(L, 3);+ y1 = lua_tointeger(L, 4);+ col = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : pencolor_get();+ fillp = lua_gettop(L) >= 5 ? (fix32_bits(lua_tonumber(L, 5)) & 0xffff) : 0;+ if (lua_gettop(L) >= 5)+ pencolor_set(col);+ } else {+ valid = !m_memory[MEMORY_LINE_VALID];+ x0 = m_memory[MEMORY_LINE_X] | (m_memory[MEMORY_LINE_X + 1] << 8);+ y0 = m_memory[MEMORY_LINE_Y] | (m_memory[MEMORY_LINE_Y + 1] << 8);+ x1 = lua_tointeger(L, 1);+ y1 = lua_tointeger(L, 2);+ col = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : pencolor_get();+ fillp = lua_gettop(L) >= 3 ? (fix32_bits(lua_tonumber(L, 3)) & 0xffff) : 0;+ if (lua_gettop(L) >= 3)+ pencolor_set(col);+ }++ if (valid)+ draw_line(x0, y0, x1, y1, col, fillp);++ m_memory[MEMORY_LINE_X] = x1 & 0xff;+ m_memory[MEMORY_LINE_X + 1] = (x1 >> 8) & 0xff;+ m_memory[MEMORY_LINE_Y] = y1 & 0xff;+ m_memory[MEMORY_LINE_Y + 1] = (y1 >> 8) & 0xff;+ m_memory[MEMORY_LINE_VALID] = 0;+ }++ return 0;+}++// oval(x0, y0, x1, y1, [col])+int oval(lua_State *L)+{+ int x0 = lua_tointeger(L, 1);+ int y0 = lua_tointeger(L, 2);+ int x1 = lua_tointeger(L, 3);+ int y1 = lua_tointeger(L, 4);+ int col = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : pencolor_get();+ int fillp = lua_gettop(L) >= 5 ? (fix32_bits(lua_tonumber(L, 5)) & 0xffff) : 0;++ if (lua_gettop(L) >= 5)+ pencolor_set(col);++ draw_oval(x0, y0, x1, y1, col, fillp);++ return 0;+}++// ovalfill(x0, y0, x1, y1, [col])+int ovalfill(lua_State *L)+{+ int x0 = lua_tointeger(L, 1);+ int y0 = lua_tointeger(L, 2);+ int x1 = lua_tointeger(L, 3);+ int y1 = lua_tointeger(L, 4);+ int col = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : pencolor_get();+ int fillp = lua_gettop(L) >= 5 ? (fix32_bits(lua_tonumber(L, 5)) & 0xffff) : 0;++ if (lua_gettop(L) >= 5)+ pencolor_set(col);++ draw_ovalfill(x0, y0, x1, y1, col, fillp);++ return 0;+}++// pal(c0, c1, [p])+// pal(tbl, [p])+int pal(lua_State *L)+{+ if (lua_gettop(L) == 0)+ {+ reset_color();+ }+ else if (lua_istable(L, 1))+ {+ int p = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : PALTYPE_DRAW;+ lua_pushnil(L);+ while (lua_next(L, 1))+ {+ int c0 = lua_tointeger(L, -2);+ int c1 = lua_tointeger(L, -1);+ uint8_t new_val;+ if (p == PALTYPE_DRAW) {+ uint8_t old_val = color_get(p, c0);+ new_val = (c1 & 0xf) | (old_val & 0xf0);+ } else {+ new_val = c1 & 0xff;+ }+ color_set(p, c0, new_val);+ lua_pop(L, 1);+ }+ lua_pop(L, 1);+ }+ else if (lua_gettop(L) == 1)+ {+ int p = lua_tointeger(L, 1);+ if (p == PALTYPE_DRAW) {+ for (int i=0;i<16;++i)+ color_set(PALTYPE_DRAW, i, i == 0 ? i | 0x10 : i);+ } else if (p == PALTYPE_SCREEN) {+ for (int i=0;i<16;++i)+ color_set(PALTYPE_SCREEN, i, i);+ } else if (p == PALTYPE_SECONDARY) {+ color_set(PALTYPE_SECONDARY, 0, 0x00);+ color_set(PALTYPE_SECONDARY, 1, 0x01);+ color_set(PALTYPE_SECONDARY, 2, 0x12);+ color_set(PALTYPE_SECONDARY, 3, 0x13);+ color_set(PALTYPE_SECONDARY, 4, 0x24);+ color_set(PALTYPE_SECONDARY, 5, 0x15);+ color_set(PALTYPE_SECONDARY, 6, 0xd6);+ color_set(PALTYPE_SECONDARY, 7, 0x67);+ color_set(PALTYPE_SECONDARY, 8, 0x48);+ color_set(PALTYPE_SECONDARY, 9, 0x49);+ color_set(PALTYPE_SECONDARY, 10, 0x9a);+ color_set(PALTYPE_SECONDARY, 11, 0x3b);+ color_set(PALTYPE_SECONDARY, 12, 0xdc);+ color_set(PALTYPE_SECONDARY, 13, 0x5d);+ color_set(PALTYPE_SECONDARY, 14, 0x8e);+ color_set(PALTYPE_SECONDARY, 15, 0xef);+ }+ }+ else+ {+ int c0 = lua_tointeger(L, 1);+ int c1 = lua_tointeger(L, 2);+ int p = lua_gettop(L) == 3 ? lua_tointeger(L, 3) : PALTYPE_DRAW;++ uint8_t old_val = color_get(p, c0);+ uint8_t new_val;+ if (p == PALTYPE_DRAW) {+ new_val = (c1 & 0xf) | (old_val & 0xf0);+ } else {+ new_val = c1 & 0xff;+ }+ color_set(p, c0, new_val);++ // Return the old mapped color for this slot+ lua_pushinteger(L, old_val & 0xf);+ return 1;+ }++ return 0;+}++// palt([col,] [t])+int palt(lua_State *L)+{+ if (lua_gettop(L) == 0)+ {+ for (int col=0;col<16;++col) {+ uint8_t c = color_get(PALTYPE_DRAW, col);+ color_set(PALTYPE_DRAW, col, col == 0 ? (c | 0x10) : (c & 0xf));+ }+ }+ else if (lua_gettop(L) == 1)+ {+ int b = lua_tounsigned(L, 1);+ for (int col=0;col<16;++col) {+ int t = (b >> (15-col)) & 1;+ uint8_t c = color_get(PALTYPE_DRAW, col);++ color_set(PALTYPE_DRAW, col, t ? (c | 0x10) : (c & 0xF));+ }+ }+ else+ {+ int col = lua_tointeger(L, 1);+ int t = lua_toboolean(L, 2);+ uint8_t c = color_get(PALTYPE_DRAW, col);+ bool prev_transparent = (c & 0x10) != 0;++ color_set(PALTYPE_DRAW, col, t ? (c | 0x10) : (c & 0xF));++ lua_pushboolean(L, prev_transparent);+ return 1;+ }++ return 0;+}++// pget(x, y)+int pget(lua_State *L)+{+ int x = lua_tointeger(L, 1);+ int y = lua_tointeger(L, 2);++ int x0, y0, x1, y1;+ clip_get(&x0, &y0, &x1, &y1);++ if (x >= x0 && y >= y0 && x < x1 && y < y1) {+ lua_pushinteger(L, gfx_get(x, y, MEMORY_SCREEN, MEMORY_SCREEN_SIZE));+ } else {+ int default_val = (m_memory[MEMORY_MISCFLAGS] & 0x10) ? m_memory[MEMORY_PGET_DEFAULT] : 0;+ lua_pushinteger(L, default_val);+ }++ return 1;+}++// print(str, [x,] [y,] [col])+int print(lua_State *L)+{+ size_t len = 0;+ const char *str = lua_gettop(L) >= 1 ? lua_tolstring(L, 1, &len) : NULL;+ if (!str) { str = ""; len = 0; }+ int right, bottom;++ if (lua_gettop(L) <= 2)+ {+ int x, y;+ cursor_get(&x, &y);+ int col = lua_gettop(L) == 2 ? lua_tointeger(L, 2) : pencolor_get();+ if (lua_gettop(L) == 2)+ pencolor_set(col);+ draw_text(str, len, x, y, col, left_margin_get(), false, &x, &y, &right, &bottom);+ cursor_set(x, y, -1);+ }+ else+ {+ int x = lua_tointeger(L, 2);+ int y = lua_tointeger(L, 3);+ int col = lua_gettop(L) >= 4 ? lua_tointeger(L, 4) : pencolor_get();+ if (lua_gettop(L) >= 4)+ pencolor_set(col);+ left_margin_set(x);+ draw_text(str, len, x, y, col, x, true, &x, &y, &right, &bottom);+ cursor_set(x, y, -1);+ }++ lua_pushinteger(L, right);+ lua_pushinteger(L, bottom);+ return 2;+}++// pset(x, y, [c])+int pset(lua_State *L)+{+ int x = lua_tointeger(L, 1);+ int y = lua_tointeger(L, 2);+ int c = lua_gettop(L) == 3 ? lua_tointeger(L, 3) : pencolor_get();+ int fillp = lua_gettop(L) >= 3 ? (fix32_bits(lua_tonumber(L, 3)) & 0xffff) : 0;+ if (lua_gettop(L) == 3)+ pencolor_set(c);+ pixel_set(x, y, c, fillp, DRAWTYPE_GRAPHIC);++ return 0;+}++// rect(x0, y0, x1, y1, [col])+int rect(lua_State *L)+{+ int x0 = lua_tointeger(L, 1);+ int y0 = lua_tointeger(L, 2);+ int x1 = lua_tointeger(L, 3);+ int y1 = lua_tointeger(L, 4);+ int col = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : pencolor_get();+ int fillp = lua_gettop(L) >= 5 ? (fix32_bits(lua_tonumber(L, 5)) & 0xffff) : 0;++ int left = MIN(x0, x1);+ int top = MIN(y0, y1);+ int right = MAX(x0, x1);+ int bottom = MAX(y0, y1);++ if (lua_gettop(L) >= 5)+ pencolor_set(col);++ draw_rect(left, top, right, bottom, col, fillp);++ return 0;+}++// rectfill(x0, y0, x1, y1, [col])+int rectfill(lua_State *L)+{+ int x0 = lua_tointeger(L, 1);+ int y0 = lua_tointeger(L, 2);+ int x1 = lua_tointeger(L, 3);+ int y1 = lua_tointeger(L, 4);+ int col = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : pencolor_get();+ int fillp = lua_gettop(L) >= 5 ? (fix32_bits(lua_tonumber(L, 5)) & 0xffff) : 0;++ int left = MIN(x0, x1);+ int top = MIN(y0, y1);+ int right = MAX(x0, x1);+ int bottom = MAX(y0, y1);++ if (lua_gettop(L) >= 5)+ pencolor_set(col);++ draw_rectfill(left, top, right, bottom, col, fillp);++ return 0;+}++// rrect(x, y, w, h, r, [col])+int rrect(lua_State *L)+{+ int left = lua_tointeger(L, 1);+ int top = lua_tointeger(L, 2);+ int w = lua_tointeger(L, 3);+ int h = lua_tointeger(L, 4);+ int r = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : 0;+ int col = lua_gettop(L) >= 6 ? lua_tointeger(L, 6) : pencolor_get();+ int fillp = lua_gettop(L) >= 6 ? (fix32_bits(lua_tonumber(L, 6)) & 0xffff) : 0;++ if (lua_gettop(L) >= 6)+ pencolor_set(col);++ int right = left + w-1;+ int bottom = top + h-1;+ r = MAX(0, MIN(r, MIN(w, h) / 2));++ if (is_bbox_offscreen(left, top, right, bottom)) return 0;++ draw_hline(left+r, top, right-r, col, fillp);+ draw_hline(left+r, bottom, right-r, col, fillp);+ draw_vline(left, top+r, bottom-r, col, fillp);+ draw_vline(right, top+r, bottom-r, col, fillp);+ draw_circ_mask(left+r, top+r, r, col, fillp, 1 << 3 | 1 << 7);+ draw_circ_mask(right-r, top+r, r, col, fillp, 1 << 2 | 1 << 6);+ draw_circ_mask(left+r, bottom-r, r, col, fillp, 1 << 1 | 1 << 5);+ draw_circ_mask(right-r, bottom-r, r, col, fillp, 1 << 0 | 1 << 4);++ return 0;+}++// rrectfill(x, y, w, h, r, [col])+int rrectfill(lua_State *L)+{+ int left = lua_tointeger(L, 1);+ int top = lua_tointeger(L, 2);+ int w = lua_tointeger(L, 3);+ int h = lua_tointeger(L, 4);+ int r = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : 0;+ int col = lua_gettop(L) >= 6 ? lua_tointeger(L, 6) : pencolor_get();+ int fillp = lua_gettop(L) >= 6 ? (fix32_bits(lua_tonumber(L, 6)) & 0xffff) : 0;+ bool invert = fillp_invert_enabled(col);++ if (lua_gettop(L) >= 6)+ pencolor_set(col);++ int right = left + w;+ int bottom = top + h;+ r = MAX(0, MIN(r, MIN(w, h) / 2));++ if (!invert && is_bbox_offscreen(left, top, right, bottom)) return 0;++ if (invert) {+ int cx, cy;+ camera_get(&cx, &cy);+ int clip_x0, clip_y0, clip_x1, clip_y1;+ clip_get(&clip_x0, &clip_y0, &clip_x1, &clip_y1);++ for (int y = clip_y0+cx; y < clip_y1+cy; y++) {+ for (int x = clip_x0+cx; x < clip_x1+cy; x++) {+ if (!point_in_round_rect(x, y, left, top, right, bottom, r))+ pixel_set(x, y, col, fillp, DRAWTYPE_GRAPHIC);+ }+ }+ return 0;+ }++ draw_rectfill(left, top+r, right, bottom-r, col, fillp);+ draw_rectfill(left+r, top, right-r, top+r, col, fillp);+ draw_rectfill(left+r, bottom-r, right-r, bottom, col, fillp);+ draw_circfill_mask(left+r, top+r, r, col, fillp, 1 << 3 | 1 << 7);+ draw_circfill_mask(right-r, top+r, r, col, fillp, 1 << 2 | 1 << 6);+ draw_circfill_mask(left+r, bottom-r, r, col, fillp, 1 << 1 | 1 << 5);+ draw_circfill_mask(right-r, bottom-r, r, col, fillp, 1 << 0 | 1 << 4);++ return 0;+}++// sget(x, y)+int sget(lua_State *L)+{+ int x = lua_tointeger(L, 1);+ int y = lua_tointeger(L, 2);++ if (x >= 0 && y >= 0 && x < P8_WIDTH && y < P8_HEIGHT) {+ lua_pushinteger(L, gfx_get(x, y, MEMORY_SPRITES, MEMORY_SPRITES_SIZE));+ } else {+ int default_val = (m_memory[MEMORY_MISCFLAGS] & 0x10) ? m_memory[MEMORY_SGET_DEFAULT] : 0;+ lua_pushinteger(L, default_val);+ }++ return 1;+}++// spr(n, x, y, [w,] [h,] [flip_x,] [flip_y])+int spr(lua_State *L)+{+ int n = lua_tointeger(L, 1);+ int x = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : 0;+ int y = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : 0;+ bool flip_x = false, flip_y = false;++ if (lua_gettop(L) > 3)+ {+ assert(lua_gettop(L) >= 5);++ lua_Number w_raw = lua_tonumber(L, 4);+ lua_Number h_raw = lua_tonumber(L, 5);++ if (lua_gettop(L) >= 6)+ flip_x = lua_toboolean(L, 6);++ if (lua_gettop(L) >= 7)+ flip_y = lua_toboolean(L, 7);++ // fix32 stores integers with no fractional bits (lower 16 bits == 0)+ if ((w_raw & 0xFFFF) == 0 && (h_raw & 0xFFFF) == 0)+ {+ // Integer w/h: draw a w x h grid of sprites (standard path)+ int w = fix32_to_int(w_raw);+ int h = fix32_to_int(h_raw);+ draw_sprites(n, x, y, w, h, flip_x, flip_y);+ }+ else+ {+ // Fractional w/h: compute pixel dimensions and draw at 1:1 scale+ int sw = (int)(fix32_to_double(w_raw) * SPRITE_WIDTH + 0.5);+ int sh = (int)(fix32_to_double(h_raw) * SPRITE_HEIGHT + 0.5);+ int ssx = (n & 0xF) * SPRITE_WIDTH;+ int ssy = (n >> 4) * SPRITE_HEIGHT;+ draw_scaled_sprite(ssx, ssy, sw, sh, x, y, 1.0f, 1.0f, flip_x, flip_y);+ }+ }+ else+ {+ draw_sprites(n, x, y, 1, 1, flip_x, flip_y);+ }++ return 0;+}++// sset(x, y, [c])+int sset(lua_State *L)+{+ int x = lua_tointeger(L, 1);+ int y = lua_tointeger(L, 2);+ int c = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : pencolor_get();++ if (lua_gettop(L) >= 3)+ pencolor_set(c);+ if (x >= 0 && y >= 0 && x < P8_WIDTH && y < P8_HEIGHT)+ gfx_set(x, y, MEMORY_SPRITES, MEMORY_SPRITES_SIZE, c);++ return 0;+}++// sspr(sx, sy, sw, sh, dx, dy, [dw,] [dh,] [flip_x,] [flip_y])+int sspr(lua_State *L)+{+ int sx = lua_tointeger(L, 1);+ int sy = lua_tointeger(L, 2);+ int sw = lua_tointeger(L, 3);+ int sh = lua_tointeger(L, 4);+ int dx = lua_tointeger(L, 5);+ int dy = lua_tointeger(L, 6);+ int dw = lua_to_or_default(L, integer, 7, sw);+ int dh = lua_to_or_default(L, integer, 8, sh);+ bool flip_x = lua_to_or_default(L, boolean, 9, false);+ bool flip_y = lua_to_or_default(L, boolean, 10, false);+ if (dw < 0) {+ flip_x = !flip_x;+ dw = -dw;+ if (flip_x) dx -= dw; else dx += dw;+ }+ if (dh < 0) {+ flip_y = !flip_y;+ dh = -dh;+ if (flip_y) dy -= dh; else dy += dh;+ }+ float scale_x = (float)dw / sw;+ float scale_y = (float)dh / sh;++ draw_scaled_sprite(sx, sy, sw, sh, dx, dy, scale_x, scale_y, flip_x, flip_y);++ return 0;+}++// tline( x0, y0, x1, y1, mx, my, [mdx,] [mdy])+// tline( precision )+int tline(lua_State *L)+{+ if (lua_gettop(L) == 1) {+ m_tline_precision = lua_tointeger(L, 1);+ return 0;+ }++ int x0 = lua_tointeger(L, 1);+ int y0 = lua_tointeger(L, 2);+ int x1 = lua_tointeger(L, 3);+ int y1 = lua_tointeger(L, 4);+ lua_Number mx = lua_tonumber(L, 5);+ lua_Number my = lua_tonumber(L, 6);+ lua_Number mdx = lua_to_or_default(L, number, 7, fix32_div(fix32_from_int(1), fix32_from_int(8)));+ lua_Number mdy = lua_to_or_default(L, number, 8, fix32_from_int(0));+ int layer = lua_to_or_default(L, integer, 9, 0);++ int cx, cy;+ camera_get(&cx, &cy);+ int clip_x0, clip_y0, clip_x1, clip_y1;+ clip_get(&clip_x0, &clip_y0, &clip_x1, &clip_y1);++ uint8_t map_start = m_memory[MEMORY_MAP_START];+ bool map_invalid = (map_start >= 0x10 && map_start < 0x20) ||+ (map_start >= 0x30 && map_start < 0x3f);+ uint8_t map_start_upper = map_start;+ uint8_t map_start_lower = map_start;+ if (!map_invalid) {+ if (map_start < 0x10 || map_start >= 0x40)+ map_start_upper = 0x20;+ else+ map_start_upper = map_start;+ map_start_lower = (map_start_upper < 0x80) ? 0x10 : map_start_upper;+ }+ int map_width = m_memory[MEMORY_MAP_WIDTH];+ if (map_width == 0) map_width = 256;++ int sprite_base = p8_sprite_base();+ int screen_base = p8_screen_base();++ int offset_x = m_memory[MEMORY_TLINE_OFFSET_X] * 8;+ int offset_y = m_memory[MEMORY_TLINE_OFFSET_Y] * 8;+ int precision = m_tline_precision;++ // Clamp precision to reasonable bounds to prevent integer overflow+ if (precision < 0) precision = 0;+ if (precision > 24) precision = 24;++ uint32_t mask_x_bits = ((uint32_t)m_memory[MEMORY_TLINE_MASK_X] << (precision + 3)) - 1;+ uint32_t mask_y_bits = ((uint32_t)m_memory[MEMORY_TLINE_MASK_Y] << (precision + 3)) - 1;++ uint32_t mx_bits = fix32_bits(mx);+ uint32_t my_bits = fix32_bits(my);+ uint32_t mdx_bits = fix32_bits(mdx);+ uint32_t mdy_bits = fix32_bits(mdy);++ int dx = abs(x1 - x0);+ int sx = x0 < x1 ? 1 : -1;+ int dy = -abs(y1 - y0);+ int sy = y0 < y1 ? 1 : -1;+ int err = dx + dy;++ uint8_t *draw_pal = &m_memory[MEMORY_PALETTES + PALTYPE_DRAW * 16];+ uint8_t *sprite_flags_base = &m_memory[MEMORY_SPRITEFLAGS];+ bool sprite_0_opaque = (m_memory[MEMORY_MISCFLAGS] & 0x8) != 0;+ uint8_t rw_mask = m_memory[MEMORY_RW_MASK];++ while (true)+ {+ uint32_t tmx = mx_bits & mask_x_bits;+ uint32_t tmy = my_bits & mask_y_bits;++ int tx_raw = ((int32_t)tmx) >> precision;+ int ty_raw = ((int32_t)tmy) >> precision;+ int tx = tx_raw + offset_x;+ int ty = ty_raw + offset_y;++ int celx = tx >> 3;+ int cely = ty >> 3;+ int index = 0;+ // Bounds check uses pre-offset coordinates (PICO-8 behaviour: offset doesn't+ // make a negative texture coordinate valid for map lookup).+ if (!map_invalid && (tx_raw >> 3) >= 0 && (ty_raw >> 3) >= 0) {+ uint8_t ms = (cely >= 32 && map_start_upper < 0x80) ? map_start_lower : map_start_upper;+ int adj_cely = (cely >= 32 && map_start_upper < 0x80) ? cely - 32 : cely;+ int address = (ms << 8) + celx + adj_cely * map_width;+ if (address >= 0x1000 && address < P8_RAM_SIZE &&+ !(address >= 0x3000 && address < 0x8000))+ index = m_memory[address];+ }+ if ((index != 0 || sprite_0_opaque) && (layer == 0 || ((layer & sprite_flags_base[index]) == layer))) {+ int spx = (index & 0xF) * 8 + (tx & 7);+ int spy = (index >> 4) * 8 + (ty & 7);++ int spr_offset = sprite_base + (spx >> 1) + spy * 64;+ uint8_t col = IS_EVEN(spx) ? m_memory[spr_offset] & 0xF : m_memory[spr_offset] >> 4;++ uint8_t mapped = draw_pal[col & 0xf];+ int px = x0 - cx;+ int py = y0 - cy;+ if ((mapped & 0xf0) == 0) {+ if (px >= clip_x0 && px < clip_x1 && py >= clip_y0 && py < clip_y1) {+ int scr_offset = screen_base + (px >> 1) + py * 64;+ if (rw_mask != 0xff) {+ uint8_t write_mask = rw_mask & 0xf;+ uint8_t read_mask = (rw_mask >> 4) & 0xf;+ uint8_t dst = IS_EVEN(px) ? m_memory[scr_offset] & 0xf : m_memory[scr_offset] >> 4;+ uint8_t src = mapped & 0xf;+ uint8_t result = (dst & ~write_mask) | (src & write_mask & read_mask);+ m_memory[scr_offset] = IS_EVEN(px)+ ? (m_memory[scr_offset] & 0xF0) | result+ : (result << 4) | (m_memory[scr_offset] & 0xF);+ } else {+ m_memory[scr_offset] = IS_EVEN(px)+ ? (m_memory[scr_offset] & 0xF0) | (mapped & 0xF)+ : (mapped << 4) | (m_memory[scr_offset] & 0xF);+ }+ }+ }+ }++ if (x0 == x1 && y0 == y1)+ break;++ int e2 = 2 * err;++ if (e2 >= dy)+ {+ err += dy;+ x0 += sx;+ }++ if (e2 <= dx)+ {+ err += dx;+ y0 += sy;+ }++ mx_bits += mdx_bits;+ my_bits += mdy_bits;+ }++ return 0;+}++// ****************************************************************+// *** Tables ***+// ****************************************************************++// add(tbl, v)+// all(tbl)+// count(tbl)+// del(tbl, v)+// foreach(tbl, func)+// pairs(tbl)++// ****************************************************************+// *** Input ***+// ****************************************************************++// btn([i,] [p])+int btn(lua_State *L)+{+ // button+ if (lua_gettop(L) >= 1)+ {+ int i = lua_tointeger(L, 1);+ int p = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : 0;++ if (i < BUTTON_COUNT && p < PLAYER_COUNT)+ lua_pushboolean(L, is_button_set(p, i, false));+ else+ lua_pushboolean(L, false);+ }+ // mask+ else+ {+ lua_pushinteger(L, (m_buttons[0] & 0xff) | ((m_buttons[1] & 0xff) << 8));+ }++ return 1;+}++// btnp([i,] [p])+int btnp(lua_State *L)+{+ // button+ if (lua_gettop(L) >= 1)+ {+ int i = lua_tointeger(L, 1);+ int p = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : 0;++ if (i < BUTTON_COUNT && p < PLAYER_COUNT)+ lua_pushboolean(L, is_button_set(p, i, true));+ else+ lua_pushboolean(L, false);+ }+ // mask+ else+ {+ lua_pushinteger(L, (m_buttonsp[0] & 0xff) | ((m_buttons[1] & 0xff) << 8));+ }++ return 1;+}++// ****************************************************************+// *** Sound ***+// ****************************************************************++// music(n, [fadems,] [channelmask])+int music(lua_State *L)+{+#ifdef ENABLE_AUDIO+ int prev = audio_stat(54); // stat(54) = current music pattern, -1 if none++ int n = lua_to_or_default(L, integer, 1, 0);+ int fadems = lua_to_or_default(L, integer, 2, 0);+ int channelmask = lua_to_or_default(L, integer, 3, 0);++ audio_music(n, fadems, channelmask);++ lua_pushinteger(L, prev);+ return 1;+#else+ lua_pushinteger(L, -1);+ return 1;+#endif+}++// sfx(n, [channel,] [offset,] [length])+int sfx(lua_State *L)+{+#ifdef ENABLE_AUDIO+ int n = lua_to_or_default(L, integer, 1, 0);+ int channel = lua_to_or_default(L, integer, 2, -1);+ int offset = lua_to_or_default(L, integer, 3, 0);+ int length = lua_to_or_default(L, integer, 4, 32 - offset);++ audio_sound(n, channel, offset, length);+#endif++ return 0;+}++// ****************************************************************+// *** Map ***+// ****************************************************************++static void map_get_visible_cells(int sx, int sy, int celw, int celh,+ int *start_x, int *start_y, int *end_x, int *end_y)+{+ int cam_x, cam_y;+ camera_get(&cam_x, &cam_y);++ int clip_x0, clip_y0, clip_x1, clip_y1;+ clip_get(&clip_x0, &clip_y0, &clip_x1, &clip_y1);++ int screen_x0 = cam_x + clip_x0;+ int screen_y0 = cam_y + clip_y0;+ int screen_x1 = cam_x + clip_x1;+ int screen_y1 = cam_y + clip_y1;++ int visible_x0 = (screen_x0 - sx) / SPRITE_WIDTH;+ int visible_y0 = (screen_y0 - sy) / SPRITE_HEIGHT;+ int visible_x1 = (screen_x1 - sx + SPRITE_WIDTH - 1) / SPRITE_WIDTH;+ int visible_y1 = (screen_y1 - sy + SPRITE_HEIGHT - 1) / SPRITE_HEIGHT;++ *start_x = MAX(0, visible_x0);+ *start_y = MAX(0, visible_y0);+ *end_x = MIN(celw, visible_x1);+ *end_y = MIN(celh, visible_y1);+}++// map(celx, cely, sx, sy, celw, celh, [layer])+int map(lua_State *L)+{+ int default_celw = m_memory[MEMORY_MAP_WIDTH];+ if (default_celw == 0)+ default_celw = 128;+ int map_start = m_memory[MEMORY_MAP_START];+ int max_map_cells = (map_start >= 0x80) ? (0x10000 - (map_start << 8)) : 0x2000;+ int default_celh = (default_celw > 0) ? (max_map_cells / default_celw) : 64;++ int celx = lua_gettop(L) >= 1 ? lua_tointeger(L, 1) : 0;+ int cely = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : 0;+ int sx = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : 0;+ int sy = lua_gettop(L) >= 4 ? lua_tointeger(L, 4) : 0;+ int celw = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : default_celw;+ int celh = lua_gettop(L) >= 6 ? lua_tointeger(L, 6) : default_celh;+ int layer = lua_gettop(L) >= 7 ? lua_tointeger(L, 7) : 0;++ int start_x, start_y, end_x, end_y;+ map_get_visible_cells(sx, sy, celw, celh, &start_x, &start_y, &end_x, &end_y);++ for (int y = start_y; y < end_y; y++)+ {+ for (int x = start_x; x < end_x; x++)+ {+ uint8_t index = map_get(celx + x, cely + y);+ uint8_t sprite_flags = m_memory[MEMORY_SPRITEFLAGS + index];+ bool sprite_0_opaque = (m_memory[MEMORY_MISCFLAGS] & 0x8) != 0;+ bool should_draw = (index != 0 || sprite_0_opaque) && (layer == 0 || ((layer & sprite_flags) == layer));++ if (should_draw)+ {+ int left = sx + x * SPRITE_WIDTH;+ int top = sy + y * SPRITE_HEIGHT;+ draw_sprite(index, left, top, false, false);+ }+ }+ }++ return 0;+}++// mget(celx, cely)+int mget(lua_State *L)+{+ int celx = lua_tointeger(L, 1);+ int cely = lua_tointeger(L, 2);++ int address = map_cell_addr(celx, cely);+ if (address == 0) {+ int default_val = (m_memory[MEMORY_MISCFLAGS] & 0x10) ? m_memory[MEMORY_MGET_DEFAULT] : 0;+ lua_pushinteger(L, default_val);+ } else {+ lua_pushinteger(L, m_memory[address]);+ }++ return 1;+}++// mset(celx, cely, snum)+int mset(lua_State *L)+{+ int celx = lua_tointeger(L, 1);+ int cely = lua_tointeger(L, 2);+ int snum = lua_tointeger(L, 3);++ map_set(celx, cely, snum);++ return 0;+}++// ****************************************************************+// *** Memory ***+// ****************************************************************++// cstore(destaddr, sourceaddr, len, [filename]): the carts are in the calculator's flash, which+// apps don't write, so nothing is stored+int cstore(lua_State *L)+{+ lua_pushinteger(L, 0);+ return 1;+}++// memcpy(destaddr, sourceaddr, len)+int _memcpy(lua_State *L)+{+ unsigned destaddr = lua_tounsigned(L, 1);+ unsigned orig_destaddr = destaddr;+ unsigned sourceaddr = lua_tounsigned(L, 2);+ unsigned len = lua_tounsigned(L, 3);++ if (len < 1 || destaddr == sourceaddr)+ {+ lua_pushinteger(L, orig_destaddr);+ return 1;+ }++ if (sourceaddr < 0 || (sourceaddr + len) > (1 << 16))+ {+ lua_pushinteger(L, orig_destaddr);+ return 1;+ }++ if (destaddr < 0 || (destaddr + len) > (1 << 16))+ {+ lua_pushinteger(L, orig_destaddr);+ return 1;+ }++ unsigned total = len;+ while (len > 0) {+ unsigned chunk = MIN(MIN(len, 0x2000 - (sourceaddr & 0x1fff)), 0x2000 - (destaddr & 0x1fff));+ unsigned destaddr1 = addr_remap(destaddr);+ unsigned sourceaddr1 = addr_remap(sourceaddr);+ if (destaddr1 + chunk <= P8_RAM_SIZE && sourceaddr1 + chunk <= P8_RAM_SIZE)+ memmove(m_memory + destaddr1, m_memory + sourceaddr1, chunk);+ else if (destaddr1 + chunk <= P8_RAM_SIZE)+ memset(m_memory + destaddr1, 0, chunk);+ destaddr += chunk;+ sourceaddr += chunk;+ len -= chunk;+ }+ if (orig_destaddr < MEMORY_CARTDATA + MEMORY_CARTDATA_SIZE && orig_destaddr + total > MEMORY_CARTDATA)+ p8_delayed_flush_cartdata();++ lua_pushinteger(L, orig_destaddr);+ return 1;+}++// memset(destaddr, val, len)+int _memset(lua_State *L)+{+ unsigned destaddr = lua_tounsigned(L, 1);+ int val = lua_tointeger(L, 2);+ unsigned len = lua_tounsigned(L, 3);++ if (destaddr + len > 0x10000)+ len = 0x10000 - destaddr;+ if (destaddr < MEMORY_CARTDATA + MEMORY_CARTDATA_SIZE && destaddr + len > MEMORY_CARTDATA)+ p8_delayed_flush_cartdata();+ while (len > 0) {+ unsigned chunk = MIN(len, 0x2000 - (destaddr & 0x1fff));+ unsigned destaddr1 = addr_remap(destaddr);+ if (destaddr1 + chunk <= P8_RAM_SIZE)+ memset(m_memory + destaddr1, val, chunk);+ destaddr += chunk;+ len -= chunk;+ }++ return 0;+}++// peek(addr, [n])+int peek(lua_State *L)+{+ unsigned addr = lua_tounsigned(L, 1);+ unsigned n = lua_gettop(L) >= 2 ? lua_tounsigned(L, 2) : 1;++ addr = addr_remap(addr);++ luaL_checkstack(L, n, "too many values");++ for (unsigned i=0;i<n;++i)+ lua_pushinteger(L, mem_get(addr+i));++ return n;+}++// peek2(addr, [n])+int peek2(lua_State *L)+{+ unsigned addr = lua_tounsigned(L, 1);+ unsigned n = lua_gettop(L) >= 2 ? lua_tounsigned(L, 2) : 1;++ addr = addr_remap(addr);++ luaL_checkstack(L, n, "too many values");++ for (unsigned i=0;i<n;++i)+ lua_pushinteger(L, (mem_get(addr + i*2 + 1) << 8) | mem_get(addr + i*2));++ return n;+}++// peek4(addr, [n])+int peek4(lua_State *L)+{+ unsigned addr = lua_tounsigned(L, 1);+ unsigned n = lua_gettop(L) >= 2 ? lua_tounsigned(L, 2) : 1;++ addr = addr_remap(addr);++ luaL_checkstack(L, n, "too many values");++ for (unsigned i=0;i<n;++i)+ lua_pushnumber(L, fix32_from_bits(((uint32_t)mem_get(addr + i*4 + 3) << 24) | (mem_get(addr + i*4 + 2) << 16) | (mem_get(addr + i*4 + 1) << 8) | mem_get(addr + i*4)));++ return n;+}++// poke(addr, val1, ...)+int poke(lua_State *L)+{+ unsigned addr = lua_tounsigned(L, 1);++ addr = addr_remap(addr);++ for (int i=2;i<=MAX(lua_gettop(L), 2);++i) {+ unsigned val = i <= lua_gettop(L) ? lua_tounsigned(L, i) : 0;++ mem_set(addr + i-2, val);+ }++ if (addr < MEMORY_CARTDATA + MEMORY_CARTDATA_SIZE && addr + 4 * (unsigned)lua_gettop(L) > MEMORY_CARTDATA)+ p8_delayed_flush_cartdata();++ lua_pushinteger(L, 0);+ return 1;+}++// poke2(addr, val1, ...)+int poke2(lua_State *L)+{+ unsigned addr = lua_tounsigned(L, 1);++ addr = addr_remap(addr);++ for (int i=2;i<=MAX(lua_gettop(L), 2);++i) {+ unsigned val = i <= lua_gettop(L) ? lua_tounsigned(L, i) : 0;+ unsigned offset = (unsigned)(i - 2) * 2;+ mem_set(addr + offset, val);+ mem_set(addr + offset + 1, val >> 8);+ }++ if (addr < MEMORY_CARTDATA + MEMORY_CARTDATA_SIZE && addr + 4 * (unsigned)lua_gettop(L) > MEMORY_CARTDATA)+ p8_delayed_flush_cartdata();++ lua_pushinteger(L, 0);+ return 1;+}++// poke4(addr, val1, ...)+int poke4(lua_State *L)+{+ unsigned addr = lua_tounsigned(L, 1);++ addr = addr_remap(addr);++ for (int i=2;i<=MAX(lua_gettop(L), 2);++i) {+ uint32_t val = i <= lua_gettop(L) ? (uint32_t)lua_tonumber(L, i) : 0;+ unsigned offset = (unsigned)(i - 2) * 4;+ mem_set(addr + offset, val);+ mem_set(addr + offset + 1, val >> 8);+ mem_set(addr + offset + 2, val >> 16);+ mem_set(addr + offset + 3, val >> 24);+ }++ if (addr < MEMORY_CARTDATA + MEMORY_CARTDATA_SIZE && addr + 4 * (unsigned)lua_gettop(L) > MEMORY_CARTDATA)+ p8_delayed_flush_cartdata();++ lua_pushinteger(L, 0);+ return 1;+}++// reload(destaddr, sourceaddr, len, [filename]): from this cart's ROM, or another of NumPico's carts+int reload(lua_State *L)+{+ int nargs = lua_gettop(L);+ unsigned destaddr = nargs >= 1 ? lua_tounsigned(L, 1) : 0;+ unsigned srcaddr = nargs >= 2 ? lua_tounsigned(L, 2) : 0;+ unsigned len = nargs >= 3 ? lua_tounsigned(L, 3) : 0x4300;+ destaddr = addr_remap(destaddr);+ const char *file_name = nargs >= 4 ? lua_tostring(L, 4) : NULL;+ const uint8_t *src_mem = file_name ? p8_cart_rom(file_name) : m_cart_memory;+ if (!src_mem) {+ lua_pushinteger(L, 0);+ return 1;+ }+ if (destaddr + len <= P8_RAM_SIZE && srcaddr + len <= CART_MEMORY_SIZE)+ memcpy(m_memory + destaddr, src_mem + srcaddr, len);+ if (destaddr < MEMORY_CARTDATA + MEMORY_CARTDATA_SIZE && destaddr + len > MEMORY_CARTDATA)+ p8_delayed_flush_cartdata();+ lua_pushinteger(L, len);+ return 1;+}++// ****************************************************************+// *** Math ***+// ****************************************************************++// rnd(max)+int rnd(lua_State *L)+{+ int is_table = 0;++ if (lua_gettop(L) >= 1)+ {+ if (lua_istable(L, 1))+ {+ is_table = 1;+ }+ }++ uint32_t hi = m_memory[MEMORY_RNG_STATE] | (m_memory[MEMORY_RNG_STATE + 1] << 8) |+ (m_memory[MEMORY_RNG_STATE + 2] << 16) | (m_memory[MEMORY_RNG_STATE + 3] << 24);+ uint32_t lo = m_memory[MEMORY_RNG_STATE + 4] | (m_memory[MEMORY_RNG_STATE + 5] << 8) |+ (m_memory[MEMORY_RNG_STATE + 6] << 16) | (m_memory[MEMORY_RNG_STATE + 7] << 24);++ hi = (hi << 16) | (hi >> 16);+ hi += lo;+ lo += hi;++ m_memory[MEMORY_RNG_STATE] = hi & 0xFF;+ m_memory[MEMORY_RNG_STATE + 1] = (hi >> 8) & 0xFF;+ m_memory[MEMORY_RNG_STATE + 2] = (hi >> 16) & 0xFF;+ m_memory[MEMORY_RNG_STATE + 3] = (hi >> 24) & 0xFF;+ m_memory[MEMORY_RNG_STATE + 4] = lo & 0xFF;+ m_memory[MEMORY_RNG_STATE + 5] = (lo >> 8) & 0xFF;+ m_memory[MEMORY_RNG_STATE + 6] = (lo >> 16) & 0xFF;+ m_memory[MEMORY_RNG_STATE + 7] = (lo >> 24) & 0xFF;++ if (is_table)+ {+ size_t len = lua_rawlen(L, 1);+ if (len > 0)+ {+ int index = ((hi >> 16) % len) + 1;+ lua_rawgeti(L, 1, index);+ }+ else+ {+ lua_pushnil(L);+ }+ }+ else+ {+ uint32_t max_fixed = (lua_gettop(L) >= 1) ? fix32_bits(lua_tonumber(L, 1)) : 0x10000;+ uint32_t result_fixed = (max_fixed == 0) ? 0 : (hi % max_fixed);+ lua_pushnumber(L, fix32_from_bits(result_fixed));+ }++ return 1;+}++// srand(val)+int _srand(lua_State *L)+{+ // Capture the current RNG state as the "previous seed" (lo word is the seed)+ uint32_t prev_lo = m_memory[MEMORY_RNG_STATE+4] | (m_memory[MEMORY_RNG_STATE+5] << 8) |+ (m_memory[MEMORY_RNG_STATE+6] << 16) | (m_memory[MEMORY_RNG_STATE+7] << 24);++ // Use the full 32-bit raw fix32 representation so that srand(0x5b04.17cb)+ // seeds with 0x5b0417cb, not just the integer part 0x5b04.+ uint32_t n = (uint32_t)fix32_bits(lua_tonumber(L, 1));++ p8_seed_rng_state(n);++ lua_pushnumber(L, fix32_from_bits(prev_lo));+ return 1;+}++// ****************************************************************+// *** Cartridge data ***+// ****************************************************************++// cartdata(id)+int cartdata(lua_State *L)+{+ const char *id = lua_tostring(L, 1);+ bool success = p8_open_cartdata(id);+ lua_pushboolean(L, success);+ return 1;+}++// dget(index)+int dget(lua_State *L)+{+ unsigned index = lua_tounsigned(L, 1) & 63;++ lua_pushnumber(L, fix32_from_bits((uint32_t)(m_memory[MEMORY_CARTDATA + index*4 + 3] << 24) | (m_memory[MEMORY_CARTDATA + index*4 + 2] << 16) | (m_memory[MEMORY_CARTDATA + index*4 + 1] << 8) | m_memory[MEMORY_CARTDATA + index*4]));++ return 1;+}++// dset(index, value)+int dset(lua_State *L)+{+ unsigned index = lua_tounsigned(L, 1) & 63;+ lua_Number val_num = lua_tonumber(L, 2);+ uint32_t value = fix32_bits(val_num);++ m_memory[MEMORY_CARTDATA + index*4] = value;+ m_memory[MEMORY_CARTDATA + index*4 + 1] = value >> 8;+ m_memory[MEMORY_CARTDATA + index*4 + 2] = value >> 16;+ m_memory[MEMORY_CARTDATA + index*4 + 3] = value >> 24;++ p8_delayed_flush_cartdata();++ lua_pushnumber(L, val_num);+ return 1;+}++// ****************************************************************+// *** Coroutines ***+// ****************************************************************++// cocreate(func)+// coresume(cor)+// costatus(cor)+// yield()++// ****************************************************************+// *** Values and objects ***+// ****************************************************************++// setmetatable(tbl, metatbl)+// getmetatable(tbl)+// type(v)+// sub(str, from, [to])+int sub(lua_State *L)+{+ const char *str = lua_tostring(L, 1);+ int start = lua_tointeger(L, 2);+ int end = lua_to_or_default(L, integer, 3, -1);+ int str_len = strlen(str);++ if (start < 1) start = 1;+ if (start > str_len + 1) start = str_len + 1;++ if (end == -1)+ {+ int len = str_len - start + 1;+ if (len < 0) len = 0;+ lua_pushlstring(L, str + start - 1, len);+ return 1;+ }++ if (end < 0) end = str_len + end + 1;+ if (end < 1) end = 1;+ if (end > str_len) end = str_len;++ int len = end - start + 1;+ if (len < 0) len = 0;+ lua_pushlstring(L, str + start - 1, len);++ return 1;+}++// ****************************************************************+// *** Time ***+// ****************************************************************++// time()+int _time(lua_State *L)+{+ unsigned fps = m_fps ? m_fps : 30;+ lua_pushnumber(L, fix32_from_bits((int32_t)(((uint64_t)m_frames << 16) / fps)));++ return 1;+}++// ****************************************************************+// *** System ***+// ****************************************************************++// menuitem(index, [label, callback])+int menuitem(lua_State *L)+{+ int index = luaL_checkinteger(L, 1);++ if (index < 1 || index > MAX_CUSTOM_MENUITEMS)+ return 0;++ /* menuitem(i) with no label removes the item */+ if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {+ p8_menuitem_clear(index);+ return 0;+ }++ const char *label = lua_tostring(L, 2); /* may be nil/non-string */++ if (lua_gettop(L) >= 3 && lua_isfunction(L, 3)) {+ // Full set: update label and callback+ lua_pushvalue(L, 3);+ int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);+ p8_menuitem_set(index, label ? label : "", callback_ref);+ } else {+ // Label-only update: preserve existing callback+ p8_menuitem_set_label(index, label ? label : "");+ }+ return 0;+}++// extcmd(cmd): the pause menu, a reset, or leaving the cart; the others are the desktop's+int extcmd(lua_State *L)+{+ const char *cmd = luaL_checkstring(L, 1);++ if (strcmp(cmd, "pause") == 0) {+ p8_show_pause_menu();+ } else if (strcmp(cmd, "reset") == 0) {+ p8_restart();+ } else if (strcmp(cmd, "shutdown") == 0) {+ pico_quit_cart();+ } else if (strcmp(cmd, "breadcrumb") == 0) {+ pico_breadcrumb();+ }++ return 0;+}++int reset(lua_State *L)+{+ p8_reset();++ return 0;+}++int run(lua_State *L)+{+ const char *param = (lua_gettop(L) >= 1) ? lua_tostring(L, 1) : "";+ strncpy(m_param_string, param ? param : "", sizeof(m_param_string) - 1);++ p8_restart();+}++// load(filename [,breadcrumb] [,param]): another of NumPico's carts, by its name+int _load(lua_State *L)+{+ const char *filename = luaL_checkstring(L, 1);+ const char *param = lua_gettop(L) >= 3 ? lua_tostring(L, 3) : NULL;+ p8_load_cart(filename, param); // (doesn't return when it's there)+ lua_pushboolean(L, 0);+ return 1;+}++// ****************************************************************+// *** Debugging ***+// ****************************************************************++// assert(cond, [message])+// printh(str, [filename], [overwrite]): the calculator has no console+int printh(lua_State *L)+{+ lua_pushboolean(L, 1);+ return 1;+}++// stat(n)+int lua_stat(lua_State *L)+{+ int n = lua_tointeger(L, 1);++ switch (n)+ {+ case STAT_MEM_USAGE:+ case STAT_RAW_GC: {+ int b = lua_gc(L, LUA_GCCOUNT, 0) * 1024 + lua_gc(L, LUA_GCCOUNTB, 0);+ lua_pushnumber(L, fix32_from_bits((int32_t)(((int64_t)b << 16) / 1024)));+ break;+ }+ case STAT_CPU_USAGE:+ case STAT_SYSTEM_CPU_USAGE: {+ unsigned elapsed_time = p8_elapsed_time();+ const unsigned target_frame_time = 1000 / m_fps;+ lua_pushnumber(L, fix32_from_bits((int32_t)(((int64_t)elapsed_time << 16) / (target_frame_time ? target_frame_time : 1))));+ break;+ }+ case STAT_CURRENT_DISPLAY:+ lua_pushinteger(L, 0);+ break;+ case STAT_CLIPBOARD:+ lua_pushstring(L, "");+ break;+ case STAT_VERSION:+ lua_pushnumber(L, fix32_from_bits(0x6e14)); // (0.43)+ break;+ case STAT_PARAM:+ lua_pushstring(L, m_param_string);+ break;+ case STAT_FRAMERATE:+ lua_pushinteger(L, m_fps);+ break;+ case STAT_TARGET_FRAMERATE:+ lua_pushinteger(L, m_fps);+ break;+ case STAT_NUM_DISPLAYS:+ lua_pushinteger(L, 1);+ break;+ case STAT_PAUSE_MENU_X1:+ lua_pushinteger(L, 0);+ break;+ case STAT_PAUSE_MENU_Y1:+ lua_pushinteger(L, 0);+ break;+ case STAT_PAUSE_MENU_X2:+ lua_pushinteger(L, P8_WIDTH);+ break;+ case STAT_PAUSE_MENU_Y2:+ lua_pushinteger(L, P8_HEIGHT);+ break;+ case STAT_RAW_KEYBOARD:+ case STAT_KEY_PRESSED:+ lua_pushboolean(L, 0);+ break;+ case STAT_KEY_NAME:+ lua_pushstring(L, "");+ break;+ case STAT_YEAR:+ case STAT_YEAR_UTC:+ lua_pushinteger(L, 2026);+ break;+ case STAT_MONTH:+ case STAT_MONTH_UTC:+ case STAT_DAY:+ case STAT_DAY_UTC:+ lua_pushinteger(L, 1);+ break;+ case STAT_BREADCRUMB:+ case STAT_BBS_CART_ID:+ lua_pushstring(L, "");+ break;+ case STAT_CURRENT_PATH:+ lua_pushstring(L, "/");+ break;+ default:+ if (n == 57) {+ lua_pushboolean(L, audio_stat(n) != 0);+ } else if ((n >= 46 && n <= 57) || (n >= 16 && n <= 26)) {+ lua_pushinteger(L, audio_stat(n));+ } else {+ lua_pushinteger(L, 0);+ }+ break;+ }++ return 1;+}++// stop([message,] [x,] [y,] [col])+int _stop(lua_State *L)+{+ int nargs = lua_gettop(L);+ if (nargs >= 1 && !lua_isnil(L, 1)) {+ size_t len;+ const char *str = lua_tolstring(L, 1, &len);++ if (str) {+ if (nargs >= 3) {+ int x = lua_tointeger(L, 2);+ int y = lua_tointeger(L, 3);+ int col = nargs >= 4 ? lua_tointeger(L, 4) : pencolor_get();+ draw_text(str, len, x, y, col, x, true, &x, &y, NULL, NULL);+ cursor_set(x, y, -1);+ } else {+ int x, y;+ cursor_get(&x, &y);+ int col = nargs >= 2 ? lua_tointeger(L, 2) : pencolor_get();+ draw_text(str, len, x, y, col, left_margin_get(), false, &x, &y, NULL, NULL);+ cursor_set(x, y, -1);+ }+ p8_render();+ }+ }+ pico_stop_cart();+}++// trace([coroutine,] [message,] [skip])+// Returns a description of the current call stack as a string.+// Mirrors debug.traceback() with PICO-8's default skip of 1.+int _trace(lua_State *L)+{+ int arg = 0;+ lua_State *L1 = L;++ if (lua_isthread(L, 1)) {+ L1 = lua_tothread(L, 1);+ arg = 1;+ }++ const char *msg = lua_isnoneornil(L, arg + 1) ? NULL : lua_tostring(L, arg + 1);+ int level = lua_isnoneornil(L, arg + 2) ? 1 : lua_tointeger(L, arg + 2);++ luaL_traceback(L, L1, msg, level);+ return 1;+}++// ****************************************************************+// *** Misc ***+// ****************************************************************++// ****************************************************************+// ****************************************************************++int warning(lua_State *L)+{+ return 0;+}++int set_fps(lua_State *L)+{+ int fps = lua_tointeger(L, 1);+ m_fps = fps == 60 ? 60 : 30;++ return 0;+}++void lua_register_functions(lua_State *L)+{+ // ****************************************************************+ // *** Graphics ***+ // ****************************************************************+ lua_register(L, "camera", camera);+ lua_register(L, "circ", circ);+ lua_register(L, "circfill", circfill);+ lua_register(L, "clip", clip);+ lua_register(L, "cls", cls);+ lua_register(L, "color", color);+ lua_register(L, "cursor", cursor);+ lua_register(L, "fget", fget);+ lua_register(L, "fillp", fillp);+ lua_register(L, "flip", flip);+ lua_register(L, "holdframe", holdframe);+ lua_register(L, "fset", fset);+ lua_register(L, "line", line);+ lua_register(L, "oval", oval);+ lua_register(L, "ovalfill", ovalfill);+ lua_register(L, "pal", pal);+ lua_register(L, "palt", palt);+ lua_register(L, "pget", pget);+ lua_register(L, "print", print);+ lua_register(L, "pset", pset);+ lua_register(L, "rect", rect);+ lua_register(L, "rectfill", rectfill);+ lua_register(L, "rrect", rrect);+ lua_register(L, "rrectfill", rrectfill);+ lua_register(L, "sget", sget);+ lua_register(L, "spr", spr);+ lua_register(L, "sset", sset);+ lua_register(L, "sspr", sspr);+ lua_register(L, "tline", tline);+ // ****************************************************************+ // *** Tables ***+ // ****************************************************************+ //lua_register(L, "add", add);+ //lua_register(L, "all", all);+ //lua_register(L, "count", count);+ //lua_register(L, "del", del);+ //lua_register(L, "foreach", foreach);+ // lua_register(L, "pairs", pairs);+ // ****************************************************************+ // *** Input ***+ // ****************************************************************+ lua_register(L, "btn", btn);+ lua_register(L, "btnp", btnp);+ lua_register(L, "_update_buttons", _update_buttons);+ // ****************************************************************+ // *** Sound ***+ // ****************************************************************+ lua_register(L, "music", music);+ lua_register(L, "sfx", sfx);+ // ****************************************************************+ // *** Map ***+ // ****************************************************************+ lua_register(L, "map", map);+ lua_register(L, "mget", mget);+ lua_register(L, "mset", mset);+ // ****************************************************************+ // *** Memory ***+ // ****************************************************************+ lua_register(L, "cstore", cstore);+ lua_register(L, "memcpy", _memcpy);+ lua_register(L, "memset", _memset);+ lua_register(L, "peek", peek);+ lua_register(L, "peek2", peek2);+ lua_register(L, "peek4", peek4);+ lua_register(L, "poke", poke);+ lua_register(L, "poke2", poke2);+ lua_register(L, "poke4", poke4);+ lua_register(L, "reload", reload);+ // ****************************************************************+ // *** Math ***+ // ****************************************************************+ // lua_register(L, "abs", _abs); // in lpico8lib.c+ // lua_register(L, "atan2", _atan2); // in lpico8lib.c+ // lua_register(L, "band", band); // in lpico8lib.c+ // lua_register(L, "bnot", bnot); // in lpico8lib.c+ // lua_register(L, "bor", bor); // in lpico8lib.c+ // lua_register(L, "bxor", bxor); // in lpico8lib.c+ // lua_register(L, "ceil", _ceil); // in lpico8lib.c+ // lua_register(L, "cos", _cos); // in lpico8lib.c+ // lua_register(L, "flr", flr); // in lpico8lib.c+ // lua_register(L, "lshr", lshr); // in lpico8lib.c+ // lua_register(L, "max", max); // in lpico8lib.c+ // lua_register(L, "mid", mid); // in lpico8lib.c+ // lua_register(L, "min", min); // in lpico8lib.c+ lua_register(L, "rnd", rnd);+ // lua_register(L, "rotl", rotl); // in lpico8lib.c+ // lua_register(L, "rotr", rotr); // in lpico8lib.c+ // lua_register(L, "sgn", sgn); // in lpico8lib.c+ // lua_register(L, "shl", shl); // in lpico8lib.c+ // lua_register(L, "shr", shr); // in lpico8lib.c+ // lua_register(L, "sin", _sin); // in lpico8lib.c+ // lua_register(L, "sqrt", _sqrt); // in lpico8lib.c+ lua_register(L, "srand", _srand);+ // ****************************************************************+ // *** Cartridge data ***+ // ****************************************************************+ lua_register(L, "cartdata", cartdata);+ lua_register(L, "dget", dget);+ lua_register(L, "dset", dset);+ // ****************************************************************+ // *** Coroutines ***+ // ****************************************************************+ // lua_register(L, "cocreate", cocreate);+ // lua_register(L, "coresume", coresume);+ // lua_register(L, "costatus", costatus);+ // lua_register(L, "yield", yield);+ // ****************************************************************+ // *** Values and objects ***+ // ****************************************************************+ // lua_register(L, "chr", chr); // in lpico8lib.c+ // lua_register(L, "ord", ord); // in lpico8lib.c+ // lua_register(L, "setmetatable", setmetatable);+ // lua_register(L, "getmetatable", getmetatable);+ // lua_register(L, "type", type);+ lua_register(L, "sub", sub);+ // lua_register(L, "tonum", tonum);+ // lua_register(L, "tostr", tostr); // in lpico8lib.c+ // ****************************************************************+ // *** Time ***+ // ****************************************************************+ lua_register(L, "t", _time);+ lua_register(L, "time", _time);+ // ****************************************************************+ // *** System ***+ // ****************************************************************+ lua_register(L, "menuitem", menuitem);+ lua_register(L, "extcmd", extcmd);+ lua_register(L, "load", _load);+ lua_register(L, "reset", reset);+ lua_register(L, "run", run);+ lua_register(L, "_set_fps", set_fps);+ // ****************************************************************+ // *** Debugging ***+ // ****************************************************************+ // lua_register(L, "assert", assert);+ lua_register(L, "printh", printh);+ lua_register(L, "stat", lua_stat);+ lua_register(L, "stop", _stop);+ lua_register(L, "trace", _trace);+ // ****************************************************************+ // *** Misc ***+ // ****************************************************************++ // ****************************************************************+ // *** P8SCII glyphs ***+ // ****************************************************************+ lua_pushinteger(L, 0); lua_setglobal(L, "\x8b"); // 139 ⬅️ left+ lua_pushinteger(L, 1); lua_setglobal(L, "\x91"); // 145 ➡️ right+ lua_pushinteger(L, 2); lua_setglobal(L, "\x94"); // 148 ⬆️ up+ lua_pushinteger(L, 3); lua_setglobal(L, "\x83"); // 131 ⬇️ down+ lua_pushinteger(L, 4); lua_setglobal(L, "\x8e"); // 142 🅾️ O/Z+ lua_pushinteger(L, 5); lua_setglobal(L, "\x97"); // 151 ❎ X++ lua_pushnumber(L, fix32_from_bits(0x00008000)); lua_setglobal(L, "\x80"); // 128 █+ lua_pushnumber(L, fix32_from_bits(0x5a5a8000)); lua_setglobal(L, "\x81"); // 129 ▒+ lua_pushnumber(L, fix32_from_bits(0x511f8000)); lua_setglobal(L, "\x82"); // 130 🐱+ lua_pushnumber(L, fix32_from_bits(0x7d7d8000)); lua_setglobal(L, "\x84"); // 132 ░+ lua_pushnumber(L, fix32_from_bits(0xb81d8000)); lua_setglobal(L, "\x85"); // 133 ✽+ lua_pushnumber(L, fix32_from_bits(0xf99f8000)); lua_setglobal(L, "\x86"); // 134 ●+ lua_pushnumber(L, fix32_from_bits(0x51bf8000)); lua_setglobal(L, "\x87"); // 135 ♥+ lua_pushnumber(L, fix32_from_bits(0xb5bf8000)); lua_setglobal(L, "\x88"); // 136 ☉+ lua_pushnumber(L, fix32_from_bits(0x999f8000)); lua_setglobal(L, "\x89"); // 137 웃+ lua_pushnumber(L, fix32_from_bits(0xb11f8000)); lua_setglobal(L, "\x8a"); // 138 ⌂+ lua_pushnumber(L, fix32_from_bits(0xa0e08000)); lua_setglobal(L, "\x8c"); // 140 😐+ lua_pushnumber(L, fix32_from_bits(0x9b3f8000)); lua_setglobal(L, "\x8d"); // 141 ♪+ lua_pushnumber(L, fix32_from_bits(0xb1bf8000)); lua_setglobal(L, "\x8f"); // 143 ◆+ lua_pushnumber(L, fix32_from_bits(0xf5ff8000)); lua_setglobal(L, "\x90"); // 144 …+ lua_pushnumber(L, fix32_from_bits(0xb15f8000)); lua_setglobal(L, "\x92"); // 146 ★+ lua_pushnumber(L, fix32_from_bits(0x1b1f8000)); lua_setglobal(L, "\x93"); // 147 ⧗+ lua_pushnumber(L, fix32_from_bits(0xf5bf8000)); lua_setglobal(L, "\x95"); // 149 ˇ+ lua_pushnumber(L, fix32_from_bits(0x7adf8000)); lua_setglobal(L, "\x96"); // 150 ∧+ lua_pushnumber(L, fix32_from_bits(0x0f0f8000)); lua_setglobal(L, "\x98"); // 152 ▤+ lua_pushnumber(L, fix32_from_bits(0x55558000)); lua_setglobal(L, "\x99"); // 153 ▥+}++static void lua_event_pump_hook(lua_State *L, lua_Debug *ar)+{+ (void)ar;+ pico_hook(L);+}++int lua_load_api()+{+ if (!L)+ {+ L = lua_newstate(pico_lua_alloc, NULL);+ if (!L)+ return -1;+ lua_atpanic(L, pico_panic);+ }++ luaL_openlibs(L);++ lua_register_functions(L);++ lua_setpico8memory(L, m_memory);++ // Every ~3000 instructions: Home, and a cart that never ends a frame+ lua_sethook(L, lua_event_pump_hook, LUA_MASKCOUNT, 3000);++ return 0;+}++int lua_shutdown_api()+{+ if (L) {+ p8_menuitem_reset_all();+ lua_close(L);+ L = NULL;+ }+ return 0;+}++const void *lua_get_init()+{+ const void *ret = NULL;+ if (L) {+ lua_getglobal(L, "_init");+ if (lua_isfunction(L, -1))+ ret = lua_topointer(L, -1);+ lua_pop(L, 1);+ }+ return ret;+}++const void *lua_get_update()+{+ const void *ret = NULL;+ if (L) {+ lua_getglobal(L, "_update");+ if (lua_isfunction(L, -1))+ ret = lua_topointer(L, -1);+ lua_pop(L, 1);+ }+ return ret;+}++const void *lua_get_update60()+{+ const void *ret = NULL;+ if (L) {+ lua_getglobal(L, "_update60");+ if (lua_isfunction(L, -1))+ ret = lua_topointer(L, -1);+ lua_pop(L, 1);+ }+ return ret;+}++const void *lua_get_draw()+{+ const void *ret = NULL;+ if (L) {+ lua_getglobal(L, "_draw");+ if (lua_isfunction(L, -1))+ ret = lua_topointer(L, -1);+ lua_pop(L, 1);+ }+ return ret;+}++int lua_init_script(const char *file_name, const char *script, size_t script_len)+{+ (void)file_name;+ lua_settop(L, 0);++ m_status = luaL_loadbuffer(L, script, script_len, "=cart");++ if (m_status)+ return m_status;++ m_status = lua_pcall(L, 0, 0, 0);+ return m_status;+}++int lua_call_function(const char *name, int ret)+{+ lua_settop(L, 0);+ lua_getglobal(L, name);+ m_status = lua_pcall(L, 0, ret, 0);+ return m_status;+}++int lua_update()+{+ const void *update_ptr = lua_get_update();+ const void *update60_ptr = lua_get_update60();+ lua_settop(L, 0);+ m_status = 0;+ if (update60_ptr) {+ m_fps = 60;+ return lua_call_function("_update60", 0);+ } else if (update_ptr) {+ m_fps = 30;+ return lua_call_function("_update", 0);+ }+ return 0;+}++int lua_draw()+{+ const void *draw_ptr = lua_get_draw();+ lua_settop(L, 0);+ m_status = 0;+ if (draw_ptr)+ return lua_call_function("_draw", 0);+ return 0;+}++bool lua_has_main_loop_callbacks()+{+ const void *update_ptr = lua_get_update();+ const void *update60_ptr = lua_get_update60();+ const void *draw_ptr = lua_get_draw();+ return (update_ptr != NULL || update60_ptr != NULL || draw_ptr != NULL);+}++int lua_init()+{+ const void *init_ptr = lua_get_init();+ m_status = 0;+ if (init_ptr)+ return lua_call_function("_init", 0);+ return 0;+}++void lua_get_error(const char **err_type, char *err, int err_size, const char **filename, int *lineno)+{+ assert(err_type != NULL);+ assert(err != NULL);+ if (filename) *filename = NULL;++ if (!L) {+ strncpy(err, "no lua state", err_size - 1);+ return;+ }++ switch (m_status ){+ case LUA_ERRSYNTAX:+ *err_type = "syntax error";+ break;+ case LUA_ERRMEM:+ *err_type = "out of memory";+ break;+ case LUA_ERRRUN:+ *err_type = "runtime error";+ break;+ case LUA_ERRERR:+ *err_type = "error in error handler";+ break;+ default:+ *err_type = "unknown error";+ break;+ }+ if (lua_gettop(L) > 0 && lua_isstring(L, -1)) {+ const char *err_msg = lua_tostring(L, -1);+ if (err_msg) {+ const char *colon = strrchr(err_msg, ':');+ if (colon)+ err_msg = colon + 2;+ const char *near_kw = strstr(err_msg, " near ");+ if (near_kw)+ *(char *)near_kw = '\0';+ if (strstr(err_msg, "syntax error") == NULL) {+ strncpy(err, err_msg, err_size - 1);+ err[err_size - 1] = '\0';+ }+ }++ if (lineno) {+ const char *message = lua_tostring(L, -1);+ // Extract line number from error string like "...:1292:"+ const char *colon = message;+ *lineno = 0;+ if (*colon == ':') {+ *lineno = atoi(colon + 1);+ } else {+ while (*colon) {+ if (*colon != ']' && *(colon+1) == ':') {+ *lineno = atoi(colon + 2);+ if (*lineno > 0) break;+ }+ colon++;+ }+ }+ }+ }+}diff --git a/games/numpico/src/femto8/p8_lua.h b/games/numpico/src/femto8/p8_lua.hnew file mode 100644index 00000000..c662dc91--- /dev/null+++ b/games/numpico/src/femto8/p8_lua.h@@ -0,0 +1,28 @@+/*+ * p8_lua.h+ *+ * Created on: Dec 13, 2023+ * Author: bbaker+ */++#ifndef P8_LUA_H+#define P8_LUA_H++#include <stdint.h>+#include <stdbool.h>+#include <stddef.h>++int lua_load_api();+int lua_shutdown_api();++int lua_init_script(const char *file_name, const char *script, size_t script_len);+int lua_call_function(const char *name, int ret);+int lua_update();+int lua_draw();+int lua_init();+bool lua_has_main_loop_callbacks();+void lua_get_error(const char **err_type, char *err, int err_size, const char **filename, int *lineno);++extern char m_str_buffer[256];++#endifdiff --git a/games/numpico/src/femto8/p8_lua_helper.h b/games/numpico/src/femto8/p8_lua_helper.hnew file mode 100644index 00000000..8e17629e--- /dev/null+++ b/games/numpico/src/femto8/p8_lua_helper.h@@ -0,0 +1,773 @@+/*+ * p8_lua_helper.h+ *+ * Created on: Dec 26, 2023+ * Author: bbaker+ *+ * Changed for NumPico: no UTF-8 symbol table (P8SCII only), and the sprite sheet, screen and map+ * stay in the calculator's 32 KB of PICO-8 memory (an address past it falls back to the default).+ */++#ifndef P8_LUA_HELPER_H+#define P8_LUA_HELPER_H++#include <stdbool.h>+#include <stdint.h>+#include <stdlib.h>+#include <stdio.h>+#include <math.h>+#include "p8_emu.h"+#include "p8_input.h"+#include "pico_font.h"++static inline void clear_screen(int color);+static inline void draw_circ(int x, int y, int r, int col, int fillp);+static inline void draw_circ_mask(int x, int y, int r, int col, int fillp, int mask);+static inline void draw_circfill(int x, int y, int r, int col, int fillp);+static inline void draw_circfill_mask(int x, int y, int r, int col, int fillp, int mask);+static inline void draw_oval(int x0, int y0, int x1, int y1, int col, int fillp);+static inline void draw_ovalfill(int x0, int y0, int x1, int y1, int col, int fillp);+static inline void draw_sprite(int n, int left, int top, bool flip_x, bool flip_y);+static inline void draw_scaled_sprite(int sx, int sy, int sw, int sh, int dx, int dy, float scale_x, float scale_y, bool flip_x, bool flip_y);+static inline void draw_sprites(int n, int x, int y, int w, int h, bool flip_x, bool flip_y);+static inline void draw_hline(int x0, int x1, int y, int col, int fillp);+static inline void draw_vline(int x, int y0, int y1, int col, int fillp);+static inline void draw_line(int x0, int y0, int x1, int y1, int col, int fillp);+static inline void draw_char(int n, int left, int top, int col);+static inline void draw_rect(int x0, int y0, int x1, int y1, int col, int fillp);+static inline void draw_rectfill(int x0, int y0, int x1, int y1, int col, int fillp);+static inline uint8_t gfx_addr_get(int x, int y, uint8_t *memory, int location, int size);+static inline uint8_t gfx_get(int x, int y, int location, int size);+static inline void gfx_set(int x, int y, int location, int size, int col);+static inline void camera_get(int *x, int *y);+static inline void camera_set(int x, int y);+static inline uint8_t pencolor_get(void);+static inline void pencolor_set(uint8_t col);+static inline uint8_t color_get(int type, int index);+static inline void color_set(int type, int index, int col);+static inline void clip_get(int *x0, int *y0, int *x1, int *y1);+static inline void clip_set(int x, int y, int w, int h);+static inline void cursor_get(int *x, int *y);+static inline void cursor_set(int x, int y, int col);+static inline void pixel_set(int x, int y, int c, int fillp, int draw_type);+static inline void draw_simple_text(const char *str, int x, int y, int col);+static inline bool is_button_set(int index, int button, bool prev_buttons);+static inline int map_cell_addr(int celx, int cely);+static inline void map_set(int celx, int cely, int snum);+static inline uint8_t map_get(int celx, int cely);+static inline void reset_color(void);+static inline int scroll(int y, int line_height);+static inline int scroll_newline(int y);+static inline void left_margin_set(int x);+static inline int left_margin_get(void);++static inline void clear_screen(int color)+{+ color = color_get(PALTYPE_DRAW, color);++ for (int y = 0; y < P8_HEIGHT; y++)+ for (int x = 0; x < P8_WIDTH; x++)+ gfx_set(x, y, MEMORY_SCREEN, MEMORY_SCREEN_SIZE, color);++ clip_set(0, 0, P8_WIDTH, P8_HEIGHT);+ cursor_set(0, 0, -1);+}++static inline int dash_direction_x(int facing)+{+ return 0;+}++static inline int dash_direction_y(int facing)+{+ return 0;+}++// Returns true if the world-space bounding box [wx0,wy0]..[wx1,wy1] is entirely+// outside the effective clip region (clip rect intersected with screen bounds).+static inline bool is_bbox_offscreen(int wx0, int wy0, int wx1, int wy1)+{+ int cx, cy;+ camera_get(&cx, &cy);+ int ccx0, ccy0, ccx1, ccy1;+ clip_get(&ccx0, &ccy0, &ccx1, &ccy1);+ if (ccx0 < 0) ccx0 = 0;+ if (ccy0 < 0) ccy0 = 0;+ if (ccx1 > P8_WIDTH) ccx1 = P8_WIDTH;+ if (ccy1 > P8_HEIGHT) ccy1 = P8_HEIGHT;+ int sx0 = wx0 - cx, sy0 = wy0 - cy;+ int sx1 = wx1 - cx, sy1 = wy1 - cy;+ return sx1 < ccx0 || sx0 >= ccx1 || sy1 < ccy0 || sy0 >= ccy1;+}++static inline void draw_oval_segment(int xc, int yc, int x, int y, int r, int xr, int yr, int col, int fillp, int mask)+{+ if (mask & 1)+ pixel_set(xc + x * xr / r, yc + y * yr / r, col, fillp, DRAWTYPE_GRAPHIC);+ if (mask & 2)+ pixel_set(xc - x * xr / r, yc + y * yr / r, col, fillp, DRAWTYPE_GRAPHIC);+ if (mask & 4)+ pixel_set(xc + x * xr / r, yc - y * yr / r, col, fillp, DRAWTYPE_GRAPHIC);+ if (mask & 8)+ pixel_set(xc - x * xr / r, yc - y * yr / r, col, fillp, DRAWTYPE_GRAPHIC);+ if (mask & 16)+ pixel_set(xc + y * xr / r, yc + x * yr / r, col, fillp, DRAWTYPE_GRAPHIC);+ if (mask & 32)+ pixel_set(xc - y * xr / r, yc + x * yr / r, col, fillp, DRAWTYPE_GRAPHIC);+ if (mask & 64)+ pixel_set(xc + y * xr / r, yc - x * yr / r, col, fillp, DRAWTYPE_GRAPHIC);+ if (mask & 128)+ pixel_set(xc - y * xr / r, yc - x * yr / r, col, fillp, DRAWTYPE_GRAPHIC);+}++static inline void draw_oval_mask(int xc, int yc, int xr, int yr, int col, int fillp, int mask)+{+ int r = MAX(xr, yr);+ if (r <= 0)+ return;+ if (is_bbox_offscreen(xc - xr, yc - yr, xc + xr, yc + yr)) return;+ int x = 0, y = abs(r);+ int d = 3 - 2 * abs(r);++ draw_oval_segment(xc, yc, x, y, r, xr, yr, col, fillp, mask);++ while (y >= x)+ {+ x++;++ if (d > 0)+ {+ y--;+ d = d + 4 * (x - y) + 10;+ }+ else+ d = d + 4 * x + 6;++ draw_oval_segment(xc, yc, x, y, r, xr, yr, col, fillp, mask);+ }+}++static inline void draw_circ_mask(int xc, int yc, int r, int col, int fillp, int mask)+{+ draw_oval_mask(xc, yc, r, r, col, fillp, mask);+}++static inline void draw_circ(int xc, int yc, int r, int col, int fillp)+{+ draw_circ_mask(xc, yc, r, col, fillp, 0xff);+}++static inline void draw_line(int x0, int y0, int x1, int y1, int col, int fillp)+{+ if (is_bbox_offscreen(MIN(x0, x1), MIN(y0, y1), MAX(x0, x1), MAX(y0, y1))) return;+ int dx = abs(x1 - x0);+ int sx = x0 < x1 ? 1 : -1;+ int dy = -abs(y1 - y0);+ int sy = y0 < y1 ? 1 : -1;+ int err = dx + dy;++ while (true)+ {+ pixel_set(x0, y0, col, fillp, DRAWTYPE_GRAPHIC);++ if (x0 == x1 && y0 == y1)+ break;++ int e2 = 2 * err;++ if (e2 >= dy)+ {+ err += dy;++ x0 += sx;+ }++ if (e2 <= dx)+ {+ err += dx;+ y0 += sy;+ }+ }+}++static inline void draw_hline(int x0, int y, int x1, int col, int fillp)+{+ for (int x=x0;x<=x1;x++)+ pixel_set(x, y, col, fillp, DRAWTYPE_GRAPHIC);+}++static inline void draw_vline(int x, int y0, int y1, int col, int fillp)+{+ for (int y=y0;y<=y1;y++)+ pixel_set(x, y, col, fillp, DRAWTYPE_GRAPHIC);+}++static inline void draw_ovalfill_segment(int xc, int yc, int x, int y, int r, int xr, int yr, int col, int fillp, int mask)+{+ if (mask & 1)+ draw_hline(xc, yc + y * yr / r, xc + x * xr / r, col, fillp);+ if (mask & 2)+ draw_hline(xc - x * xr / r, yc + y * yr / r, xc, col, fillp);+ if (mask & 4)+ draw_hline(xc, yc - y * yr / r, xc + x * xr / r, col, fillp);+ if (mask & 8)+ draw_hline(xc - x * xr / r, yc - y * yr / r, xc, col, fillp);+ if (mask & 16)+ draw_hline(xc, yc + x * yr / r, xc + y * xr / r, col, fillp);+ if (mask & 32)+ draw_hline(xc - y * xr / r, yc + x * yr / r, xc, col, fillp);+ if (mask & 64)+ draw_hline(xc, yc - x * yr / r, xc + y * xr / r, col, fillp);+ if (mask & 128)+ draw_hline(xc - y * xr / r, yc - x * yr / r, xc, col, fillp);+}++static inline bool fillp_invert_enabled(int color)+{+ return (m_memory[MEMORY_COLOR_FILLP] & 0x2) == 0x2 && (color & 0x1800) == 0x1800;+}++static inline bool point_in_oval(int x, int y, int xc, int yc, int xr, int yr)+{+ if (xr < 0 || yr < 0)+ return false;+ else if (xr == 0 || yr == 0)+ return x - xc == 0 && y - yc == 0;++ int dx = x - xc;+ int dy = y - yc;+ int64_t lhs = (int64_t)dx * dx * yr * yr + (int64_t)dy * dy * xr * xr;+ int64_t rhs = (int64_t)xr * xr * yr * yr;+ return lhs <= rhs;+}++static inline void draw_ovalfill_mask(int xc, int yc, int xr, int yr, int col, int fillp, int mask)+{+ int r = MAX(xr, yr);+ if (r == 0 && !fillp_invert_enabled(col)) {+ pixel_set(xc, yc, col, fillp, DRAWTYPE_GRAPHIC);+ return;+ } else if (r < 0) {+ return;+ }+ if (!fillp_invert_enabled(col) && is_bbox_offscreen(xc - xr, yc - yr, xc + xr, yc + yr)) return;++ if (fillp_invert_enabled(col)) {+ int cx, cy;+ camera_get(&cx, &cy);+ int clip_x0, clip_y0, clip_x1, clip_y1;+ clip_get(&clip_x0, &clip_y0, &clip_x1, &clip_y1);++ for (int y = clip_y0+cx; y < clip_y1+cy; y++) {+ for (int x = clip_x0+cx; x < clip_x1+cy; x++) {+ if (!point_in_oval(x, y, xc, yc, xr, yr))+ pixel_set(x, y, col, fillp, DRAWTYPE_GRAPHIC);+ }+ }+ return;+ }++ int x = 0, y = abs(r);+ int d = 3 - 2 * abs(r);++ draw_ovalfill_segment(xc, yc, x, y, r, xr, yr, col, fillp, mask);++ while (y >= x)+ {+ x++;++ if (d > 0)+ {+ y--;+ d = d + 4 * (x - y) + 10;+ }+ else+ d = d + 4 * x + 6;++ draw_ovalfill_segment(xc, yc, x, y, r, xr, yr, col, fillp, mask);+ }+}++static inline void draw_circfill_mask(int xc, int yc, int r, int col, int fillp, int mask)+{+ draw_ovalfill_mask(xc, yc, r, r, col, fillp, mask);+}++static inline void draw_circfill(int xc, int yc, int r, int col, int fillp)+{+ draw_circfill_mask(xc, yc, r, col, fillp, 0xff);+}++static inline void draw_rect(int x0, int y0, int x1, int y1, int col, int fillp)+{+ if (is_bbox_offscreen(x0, y0, x1, y1)) return;+ draw_hline(x0, y0, x1, col, fillp);+ draw_hline(x0, y1, x1, col, fillp);+ draw_vline(x0, y0, y1, col, fillp);+ draw_vline(x1, y0, y1, col, fillp);+}++static inline bool point_in_rect(int x, int y, int x0, int y0, int x1, int y1)+{+ return x >= x0 && x <= x1 && y >= y0 && y <= y1;+}++static inline void draw_rectfill(int x0, int y0, int x1, int y1, int col, int fillp)+{+ bool invert = fillp_invert_enabled(col);+ if (invert) {+ int cx, cy;+ camera_get(&cx, &cy);+ int clip_x0, clip_y0, clip_x1, clip_y1;+ clip_get(&clip_x0, &clip_y0, &clip_x1, &clip_y1);++ for (int y = clip_y0+cx; y < clip_y1+cy; y++) {+ for (int x = clip_x0+cx; x < clip_x1+cy; x++) {+ if (!point_in_rect(x, y, x0, y0, x1, y1))+ pixel_set(x, y, col, fillp, DRAWTYPE_GRAPHIC);+ }+ }+ return;+ }++ for (int x=x0;x<=x1;x++)+ for(int y=y0;y<=y1;y++)+ pixel_set(x, y, col, fillp, DRAWTYPE_GRAPHIC);+}++static inline bool point_in_round_rect(int x, int y, int left, int top, int right, int bottom, int r)+{+ if (x < left || x > right || y < top || y > bottom)+ return false;++ if (r <= 0)+ return true;++ if (x >= left + r && x <= right - r)+ return true;+ if (y >= top + r && y <= bottom - r)+ return true;++ int cx = (x < left + r) ? (left + r) : (right - r);+ int cy = (y < top + r) ? (top + r) : (bottom - r);+ return point_in_oval(x, y, cx, cy, r, r);+}++static inline void draw_oval(int x0, int y0, int x1, int y1, int col, int fillp)+{+ int x = (x0 + x1) / 2;+ int y = (y0 + y1) / 2;+ int xr = (x1 - x0) / 2;+ int yr = (y1 - y0) / 2;+ draw_oval_mask(x, y, xr, yr, col, fillp, 0xff);+}++static inline void draw_ovalfill(int x0, int y0, int x1, int y1, int col, int fillp)+{+ int x = (x0 + x1) / 2;+ int y = (y0 + y1) / 2;+ int xr = (x1 - x0) / 2;+ int yr = (y1 - y0) / 2;+ draw_ovalfill_mask(x, y, xr, yr, col, fillp, 0xff);+}++static inline void pixel_set(int x, int y, int c, int fillp, int draw_type)+{+ int cx, cy;+ camera_get(&cx, &cy);+ x -= cx;+ y -= cy;+ int x0, y0, x1, y1;+ clip_get(&x0, &y0, &x1, &y1);++ if (x >= x0 && x < x1 && y >= y0 && y < y1)+ {+ bool fillp_sprites, fillp_graphics_secondary, transparency;+ if (c & 0x1000) {+ transparency = (c & 0x100) != 0;+ fillp_sprites = (c & 0x200) != 0;+ fillp_graphics_secondary = (c & 0x400) != 0;+ } else {+ fillp = m_memory[MEMORY_FILLP] | (m_memory[MEMORY_FILLP + 1] << 8);+ transparency = (m_memory[MEMORY_FILLP_ATTR] & 1) != 0;+ fillp_sprites = (m_memory[MEMORY_FILLP_ATTR] & 2) != 0;+ fillp_graphics_secondary = (m_memory[MEMORY_FILLP_ATTR] & 4) != 0;+ }+ unsigned bit = ((3-y) & 0x3) * 4 + ((3-x) & 0x3);+ bool on = (fillp & (1 << bit)) != 0;+ bool use_fillp = (draw_type == DRAWTYPE_GRAPHIC) || (draw_type == DRAWTYPE_SPRITE && fillp_sprites);+ bool use_secondary_palette = (draw_type == DRAWTYPE_SPRITE && fillp_sprites) || (draw_type == DRAWTYPE_GRAPHIC && fillp_graphics_secondary);+ if (!use_fillp || (use_fillp && !transparency) || !on) {+ uint8_t col;+ if (c == -1)+ c = pencolor_get();+ if (use_secondary_palette) {+ uint8_t col_draw = color_get(PALTYPE_DRAW, (uint8_t)c);+ uint8_t col_secondary = color_get(PALTYPE_SECONDARY, col_draw);+ if (on)+ col = (col_secondary >> 4) & 0xf;+ else+ col = col_secondary & 0xf;+ } else {+ if (use_fillp) {+ if (on)+ c = (c >> 4) & 0xf;+ else+ c = c & 0xf;+ }+ col = color_get(PALTYPE_DRAW, c);+ }+ gfx_set(x, y, MEMORY_SCREEN, MEMORY_SCREEN_SIZE, col);+ }+ }+}++static inline void draw_scaled_sprite(int sx, int sy, int sw, int sh, int dx, int dy, float scale_x, float scale_y, bool flip_x, bool flip_y)+{+ int dw = roundf(sw * scale_x);+ int dh = roundf(sh * scale_y);++ if (dw <= 0 || dh <= 0)+ return;++ for (int y = 0; y < dh; y++)+ {+ for (int x = 0; x < dw; x++)+ {+ int src_x = sx + (flip_x ? (sw - 1 - (x * sw) / dw) : (x * sw) / dw);+ int src_y = sy + (flip_y ? (sh - 1 - (y * sh) / dh) : (y * sh) / dh);+ uint8_t index = gfx_get(src_x, src_y, MEMORY_SPRITES, MEMORY_SPRITES_SIZE);+ uint8_t color = color_get(PALTYPE_DRAW, (int)index);++ if ((color & 0xf0) == 0)+ pixel_set(dx + x, dy + y, index, 0, DRAWTYPE_SPRITE);+ }+ }+}++static inline void draw_sprite(int n, int left, int top, bool flip_x, bool flip_y)+{+ int sx = (n & 0xF) * SPRITE_WIDTH;+ int sy = (n >> 4) * SPRITE_HEIGHT;++ for (int y = 0; y < SPRITE_HEIGHT; y++)+ {+ for (int x = 0; x < SPRITE_WIDTH; x++)+ {+ int fx = flip_x ? (SPRITE_WIDTH - x - 1) : x;+ int fy = flip_y ? (SPRITE_HEIGHT - y - 1) : y;+ uint8_t index = gfx_get(sx + x, sy + y, MEMORY_SPRITES, MEMORY_SPRITES_SIZE);+ uint8_t color = color_get(PALTYPE_DRAW, index);++ if ((color & 0xf0) == 0)+ pixel_set(left + fx, top + fy, index, 0, DRAWTYPE_SPRITE);+ }+ }+}++static inline void draw_sprites(int n, int x, int y, int w, int h, bool flip_x, bool flip_y)+{+ for (int sy = 0; sy < h; sy++)+ {+ for (int sx = 0; sx < w; sx++)+ {+ int index = (n == -1 ? 0 : n) + sx + sy * 16;+ int left = x + (flip_x ? (w - 1 - sx) : sx) * 8;+ int top = y + (flip_y ? (h - 1 - sy) : sy) * 8;+ draw_sprite(index, left, top, flip_x, flip_y);+ }+ }+}++static inline void draw_char(int n, int left, int top, int col)+{+ int sx = n % 16 * 8;+ int sy = n / 16 * 8;++ for (int y = 0; y < 8; y++)+ {+ for (int x = 0; x < 8; x++)+ {+ uint8_t index = gfx_addr_get(sx + x, sy + y, (uint8_t *)font_map, 0, sizeof(font_map));+ if (index == 7)+ pixel_set(left + x, top + y, col, 0, DRAWTYPE_DEFAULT);+ }+ }+}++// Simple text drawing - draws a single line with no P8SCII support+static inline void draw_simple_text(const char *str, int x, int y, int col)+{+ int cursor_x = x;+ for (const char *c = str; *c != '\0'; c++) {+ draw_char((uint8_t)*c, cursor_x, y, col);+ if ((uint8_t)*c >= 0x80)+ cursor_x += GLYPH_WIDTH * 2;+ else+ cursor_x += GLYPH_WIDTH;+ }+}++/* where the sprite sheet and the screen are (0x5f54, 0x5f55): 0x0000 or 0x6000; the upper memory+ * (0x80 and on) isn't there, so they stay where they were by default */+static inline int p8_sprite_base(void)+{+ return m_memory[MEMORY_SPRITE_PHYS] == 0x60 ? 0x6000 : 0x0000;+}++static inline int p8_screen_base(void)+{+ return m_memory[MEMORY_SCREEN_PHYS] == 0x00 ? 0x0000 : 0x6000;+}++static inline int gfx_addr_remap(int location)+{+ if (location == MEMORY_SPRITES)+ return p8_sprite_base();+ else if (location == MEMORY_SCREEN)+ return p8_screen_base();+ else+ return location;+}++static inline uint8_t gfx_addr_get(int x, int y, uint8_t *memory, int location, int size)+{+ if (x < 0 || y < 0 || x >= P8_WIDTH || y >= P8_HEIGHT)+ return 0;+ int offset = location + (x >> 1) + y * 64;++ return IS_EVEN(x) ? memory[offset] & 0xF : memory[offset] >> 4;+}++static inline uint8_t gfx_get(int x, int y, int location, int size)+{+ if (x < 0 || y < 0 || x >= P8_WIDTH || y >= P8_HEIGHT)+ return 0;+ location = gfx_addr_remap(location);+ return gfx_addr_get(x, y, m_memory, location, size);+}++static inline void gfx_set(int x, int y, int location, int size, int col)+{+ if (x < 0 || y < 0 || x >= P8_WIDTH || y >= P8_HEIGHT)+ return;++ int offset = gfx_addr_remap(location) + (x >> 1) + y * 64;+ uint8_t rw_mask = m_memory[MEMORY_RW_MASK];+ if (location == MEMORY_SCREEN && rw_mask != 0xff) {+ uint8_t write_mask = rw_mask & 0xf;+ uint8_t read_mask = (rw_mask >> 4) & 0xf;+ uint8_t dst = IS_EVEN(x) ? m_memory[offset] & 0xf : m_memory[offset] >> 4;+ uint8_t src = col & 0xf;+ uint8_t result = (dst & ~write_mask) | (src & write_mask & read_mask);+ m_memory[offset] = IS_EVEN(x) ? (m_memory[offset] & 0xF0) | result : (result << 4) | (m_memory[offset] & 0xF);+ } else {+ m_memory[offset] = IS_EVEN(x) ? (m_memory[offset] & 0xF0) | (col & 0xF) : (col << 4) | (m_memory[offset] & 0xF);+ }+}++static inline void camera_get(int *x, int *y)+{+ int16_t cx = (m_memory[MEMORY_CAMERA + 1] << 8) | m_memory[MEMORY_CAMERA];+ int16_t cy = (m_memory[MEMORY_CAMERA + 3] << 8) | m_memory[MEMORY_CAMERA + 2];+ *x = cx;+ *y = cy;+}++static inline void camera_set(int x, int y)+{+ m_memory[MEMORY_CAMERA] = x & 0xff;+ m_memory[MEMORY_CAMERA + 1] = x >> 8;+ m_memory[MEMORY_CAMERA + 2] = y & 0xff;+ m_memory[MEMORY_CAMERA + 3] = y >> 8;+}++static inline uint8_t pencolor_get()+{+ return m_memory[MEMORY_PENCOLOR];+}++static inline void pencolor_set(uint8_t col)+{+ m_memory[MEMORY_PENCOLOR] = col;+}++static inline uint8_t color_get(int type, int index)+{+ if (type == PALTYPE_SECONDARY)+ return m_memory[MEMORY_PALETTE_SECONDARY + (index & 0xf)];+ else+ return m_memory[MEMORY_PALETTES + type * 16 + (index & 0xf)];+}++static inline void color_set(int type, int index, int col)+{+ if (type == PALTYPE_SECONDARY)+ m_memory[MEMORY_PALETTE_SECONDARY + (index & 0xf)] = col;+ else+ m_memory[MEMORY_PALETTES + type * 16 + (index & 0xf)] = col;+}++static inline void clip_set(int x, int y, int w, int h)+{+ int x1 = x + w;+ int y1 = y + h;++ // Clamp to valid screen bounds [0, P8_WIDTH] x [0, P8_HEIGHT]+ if (x < 0) x = 0;+ if (y < 0) y = 0;+ if (x > P8_WIDTH) x = P8_WIDTH;+ if (y > P8_HEIGHT) y = P8_HEIGHT;+ if (x1 < 0) x1 = 0;+ if (y1 < 0) y1 = 0;+ if (x1 > P8_WIDTH) x1 = P8_WIDTH;+ if (y1 > P8_HEIGHT) y1 = P8_HEIGHT;++ m_memory[MEMORY_CLIPRECT] = (uint8_t)x;+ m_memory[MEMORY_CLIPRECT + 1] = (uint8_t)y;+ m_memory[MEMORY_CLIPRECT + 2] = (uint8_t)x1;+ m_memory[MEMORY_CLIPRECT + 3] = (uint8_t)y1;+}++static inline void clip_get(int *x0, int *y0, int *x1, int *y1)+{+ *x0 = m_memory[MEMORY_CLIPRECT];+ *y0 = m_memory[MEMORY_CLIPRECT + 1];+ *x1 = m_memory[MEMORY_CLIPRECT + 2];+ *y1 = m_memory[MEMORY_CLIPRECT + 3];+}++static inline void cursor_set(int x, int y, int col)+{+ m_memory[MEMORY_CURSOR] = x;+ m_memory[MEMORY_CURSOR + 1] = y;++ if (col != -1)+ pencolor_set(col);+}++static inline void cursor_get(int *x, int *y)+{+ *x = (int)m_memory[MEMORY_CURSOR];+ *y = (int)m_memory[MEMORY_CURSOR + 1];+}++static inline int map_cell_addr(int celx, int cely)+{+ if (celx < 0 || cely < 0)+ return 0;++ uint8_t map_start = m_memory[MEMORY_MAP_START];+ if (map_start >= 0x80)+ map_start = 0x20;+ if ((map_start >= 0x10 && map_start < 0x20) ||+ (map_start >= 0x30 && map_start < 0x3f))+ return 0;+ if (map_start < 0x10 ||+ (map_start >= 0x40 && map_start < 0x80))+ map_start = 0x20;+ if (map_start < 0x80) {+ int start_offset = m_memory[MEMORY_MAP_START] & 0x0f;+ if (cely >= 32 && cely + start_offset >= 64)+ return 0;+ }+ if (cely >= 32 && map_start < 0x80) {+ map_start = 0x10;+ cely -= 32;+ }++ int map_width = m_memory[MEMORY_MAP_WIDTH];+ if (map_width == 0)+ map_width = 256;++ int map_base = map_start << 8;+ int offset = celx + cely * map_width;+ int address = map_base + offset;++ if (address < 0x1000 || address >= P8_RAM_SIZE ||+ (address >= 0x3000 && address < 0x8000))+ return 0;++ return address;+}++static inline uint8_t map_get(int celx, int cely)+{+ int address = map_cell_addr(celx, cely);+ if (address == 0)+ return 0;+ return m_memory[address];+}++static inline void map_set(int celx, int cely, int snum)+{+ int address = map_cell_addr(celx, cely);+ if (address == 0)+ return;+ m_memory[address] = snum;+}++static inline void reset_color()+{+ for (int i = 0; i < 16; i++)+ {+ color_set(PALTYPE_DRAW, i, i == 0 ? i | 0x10 : i);+ color_set(PALTYPE_SCREEN, i, i);+ }+ color_set(PALTYPE_SECONDARY, 0, 0x00);+ color_set(PALTYPE_SECONDARY, 1, 0x01);+ color_set(PALTYPE_SECONDARY, 2, 0x12);+ color_set(PALTYPE_SECONDARY, 3, 0x13);+ color_set(PALTYPE_SECONDARY, 4, 0x24);+ color_set(PALTYPE_SECONDARY, 5, 0x15);+ color_set(PALTYPE_SECONDARY, 6, 0xd6);+ color_set(PALTYPE_SECONDARY, 7, 0x67);+ color_set(PALTYPE_SECONDARY, 8, 0x48);+ color_set(PALTYPE_SECONDARY, 9, 0x49);+ color_set(PALTYPE_SECONDARY, 10, 0x9a);+ color_set(PALTYPE_SECONDARY, 11, 0x3b);+ color_set(PALTYPE_SECONDARY, 12, 0xdc);+ color_set(PALTYPE_SECONDARY, 13, 0x5d);+ color_set(PALTYPE_SECONDARY, 14, 0x8e);+ color_set(PALTYPE_SECONDARY, 15, 0xef);+}++static inline bool is_button_set(int index, int button, bool btnp)+{+ uint16_t mask = (btnp?m_buttonsp:m_buttons)[index];+ return mask & (1 << button);+}++static inline int scroll(int y, int line_height)+{+ int bottom = P8_HEIGHT - line_height;+ int scrolly = MAX(y - bottom, 0);+ if (scrolly == 0)+ return y;+ memmove(m_memory + p8_screen_base(), m_memory + p8_screen_base() + 64 * scrolly, 0x2000 - 64 * scrolly);+ memset(m_memory + p8_screen_base() + 0x2000 - 64 * scrolly, 0, 64 * scrolly);+ return y - scrolly;+}++static inline int scroll_newline(int y)+{+ int threshold = P8_HEIGHT - GLYPH_HEIGHT;+ if (y <= threshold)+ return y;+ int scrolly = MAX(y - threshold, GLYPH_HEIGHT);+ memmove(m_memory + p8_screen_base(), m_memory + p8_screen_base() + 64 * scrolly, 0x2000 - 64 * scrolly);+ memset(m_memory + p8_screen_base() + 0x2000 - 64 * scrolly, 0, 64 * scrolly);+ return y - scrolly;+}++static inline int left_margin_get(void)+{+ return m_memory[MEMORY_LEFT_MARGIN];+}++static inline void left_margin_set(int x)+{+ m_memory[MEMORY_LEFT_MARGIN] = x;+}++#endifdiff --git a/games/numpico/src/femto8/p8_pause_menu.h b/games/numpico/src/femto8/p8_pause_menu.hnew file mode 100644index 00000000..68cff4d3--- /dev/null+++ b/games/numpico/src/femto8/p8_pause_menu.h@@ -0,0 +1,52 @@+/**+ * Copyright (C) 2025 Chris January+ *+ * Changed for NumPico: labels of 32 bytes (PICO-8 shows 16 letters); pico.c draws the menu.+ */++#ifndef P8_PAUSE_MENU_H+#define P8_PAUSE_MENU_H++#include <stdbool.h>++#define MAX_CUSTOM_MENUITEMS 5++typedef struct {+ bool active;+ char label[32];+ int lua_callback_ref; /* LUA_NOREF if no callback */+} p8_custom_menuitem_t;++extern p8_custom_menuitem_t m_custom_menuitems[MAX_CUSTOM_MENUITEMS];++extern void p8_show_pause_menu(void);++/**+ * Register or update a custom pause menu item.+ * @param index 1-based item index (1..MAX_CUSTOM_MENUITEMS)+ * @param label Display text (copied internally)+ * @param lua_callback_ref Lua registry reference for callback, or LUA_NOREF+ */+void p8_menuitem_set(int index, const char *label, int lua_callback_ref);++/**+ * Update only the label of an existing custom pause menu item.+ * The callback is preserved; the item is made active.+ * @param index 1-based item index (1..MAX_CUSTOM_MENUITEMS)+ * @param label New display text (copied internally)+ */+void p8_menuitem_set_label(int index, const char *label);++/**+ * Remove a custom pause menu item.+ * @param index 1-based item index+ */+void p8_menuitem_clear(int index);++/**+ * Release all Lua callback refs and clear all custom menu items.+ * Must be called with a valid lua_State before closing it.+ */+void p8_menuitem_reset_all(void);++#endifdiff --git a/games/numpico/src/femto8/p8_print_helper.h b/games/numpico/src/femto8/p8_print_helper.hnew file mode 100644index 00000000..fca256c3--- /dev/null+++ b/games/numpico/src/femto8/p8_print_helper.h@@ -0,0 +1,710 @@+/*+ * p8_print_helper.h+ *+ * Print and P8SCII support+ *+ * Changed for NumPico: strings are P8SCII already (the carts' code is turned into it before it+ * reaches the calculator), and pokes from control codes stay inside the calculator's memory.+ */++#ifndef P8_PRINT_HELPER_H+#define P8_PRINT_HELPER_H++#include <stdbool.h>+#include <stdint.h>+#include <stdlib.h>+#include <string.h>+#include "p8_emu.h"+#include "pico_font.h"+#include "p8_audio.h"+#include "p8_lua_helper.h"++static inline int hexy(int c)+{+ if (c >= '0' && c <= '9')+ return c - '0';+ else if (c >= 'a' && c <= 'z')+ return c - 'a' + 10;+ else if (c >= 'A' && c <= 'Z')+ return c - 'A' + 10;+ else+ return -1;+}++typedef struct {+ bool wide;+ bool tall;+ bool stripey;+ bool invert;+ bool border;+ bool solid_bg;+ int char_w;+ int char_h;+ int char_w2;+ bool outline_enabled;+ int outline_colour;+ int outline_mask;+ bool outline_skip_interior;+ bool use_custom_font;+ int delay_frames;+} print_state_t;++static inline int get_custom_font_char_width(int char_index)+{+ int base_width = (char_index < 128) ? m_memory[MEMORY_FONT] : m_memory[MEMORY_FONT + 1];++ if (!(m_memory[MEMORY_FONT + 5] & 0x1) || char_index < 16) {+ return base_width;+ }++ int nibble_index = char_index - 16;+ int byte_offset = 8 + nibble_index / 2;+ uint8_t byte_val = m_memory[MEMORY_FONT + byte_offset];++ int nibble = (nibble_index & 1) ? (byte_val >> 4) : (byte_val & 0xF);++ int adjust = (nibble & 0x7);+ if (adjust >= 4) adjust -= 8;++ return base_width + adjust;+}++static inline bool get_custom_font_y_offset(int char_index)+{+ if (!(m_memory[MEMORY_FONT + 5] & 0x1) || char_index < 16) {+ return false;+ }++ int nibble_index = char_index - 16;+ int byte_offset = 8 + nibble_index / 2;+ uint8_t byte_val = m_memory[MEMORY_FONT + byte_offset];++ int nibble = (nibble_index & 1) ? (byte_val >> 4) : (byte_val & 0xF);+ return (nibble & 0x8) != 0;+}++static inline bool get_font_pixel(int char_index, int x, int y, bool use_custom_font)+{+ if (use_custom_font) {+ if (char_index < 16) {+ int sx = (char_index % 16) * 8;+ int sy = (char_index / 16) * 8;+ uint8_t index = gfx_addr_get(sx + x, sy + y, (uint8_t *)font_map, 0, sizeof(font_map));+ return (index == 7);+ }+ int offset = MEMORY_FONT + 128 + (char_index - 16) * 8 + y;+ if (offset < MEMORY_FONT + MEMORY_FONT_SIZE) {+ uint8_t row = m_memory[offset];+ return (row & (1 << x)) != 0;+ }+ return false;+ } else {+ int sx = (char_index % 16) * 8;+ int sy = (char_index / 16) * 8;+ uint8_t index = gfx_addr_get(sx + x, sy + y, (uint8_t *)font_map, 0, sizeof(font_map));+ return (index == 7);+ }+}++static inline void draw_char_styled(int n, int left, int top, int fg, int bg, print_state_t *state)+{+ int x_offset = 0;+ int y_offset = 0;++ if (state->use_custom_font) {+ x_offset += m_memory[MEMORY_FONT + 3];+ y_offset += m_memory[MEMORY_FONT + 4];++ if (get_custom_font_y_offset(n)) {+ y_offset -= 1;+ }+ }++ int scale_x = state->wide ? 2 : 1;+ int scale_y = state->tall ? 2 : 1;++ int char_w = state->use_custom_font ? get_custom_font_char_width(n) : (n >= 0x80 ? state->char_w2 : state->char_w);+ int render_width = char_w;+ int render_height = state->char_h;+ if (render_width > 8) render_width = 8;+ if (render_height > 8) render_height = 8;++ int outline_dx[] = {-1, 0, 1, -1, 1, -1, 0, 1};+ int outline_dy[] = {-1, -1, -1, 0, 0, 1, 1, 1};++ for (int y = 0; y < state->char_h; y++) {+ for (int x = 0; x < char_w; x++) {+ bool is_fg = (x < render_width && y < render_height) ? get_font_pixel(n, x, y, state->use_custom_font) : false;++ if (state->invert)+ is_fg = !is_fg;++ int colour = is_fg ? fg : bg;+ if (colour == -1 && !is_fg) continue;++ if (state->outline_enabled && is_fg) {+ for (int nb = 0; nb < 8; nb++) {+ if (state->outline_mask & (1 << nb)) {+ int nx = x + outline_dx[nb];+ int ny = y + outline_dy[nb];++ bool neighbour_is_fg = false;+ if (nx >= 0 && nx < 8 && ny >= 0 && ny < 8) {+ neighbour_is_fg = get_font_pixel(n, nx, ny, state->use_custom_font);+ if (state->invert)+ neighbour_is_fg = !neighbour_is_fg;+ }++ if (!neighbour_is_fg) {+ for (int dy = 0; dy < scale_y; dy++) {+ for (int dx = 0; dx < scale_x; dx++) {+ if (state->stripey && !((dx + dy) & 1))+ continue;+ int px = left + x_offset + x * scale_x + dx + outline_dx[nb];+ int py = top + y_offset + y * scale_y + dy + outline_dy[nb];+ pixel_set(px, py, state->outline_colour, 0, DRAWTYPE_DEFAULT);+ }+ }+ }+ }+ }+ }++ if (!state->outline_skip_interior || !is_fg) {+ for (int dy = 0; dy < scale_y; dy++) {+ for (int dx = 0; dx < scale_x; dx++) {+ if (state->stripey && !((dx + dy) & 1))+ continue;++ int px = left + x_offset + x * scale_x + dx;+ int py = top + y_offset + y * scale_y + dy;+ pixel_set(px, py, colour, 0, DRAWTYPE_DEFAULT);+ }+ }+ }+ }+ }+}++static inline void draw_text(const char *str, unsigned str_len, int x, int y, int col, int left_margin, bool no_scroll, int *out_left, int *out_top, int *out_right, int *out_bottom)+{+ int right = x;+ int bottom = y;+ int repeat = 1;+ int bg = 0;+ int fg = col;+ int tab_width = 16;+ int wrap_boundary = 128;+ int last_advance = GLYPH_WIDTH;+ int home_x = x;+ int home_y = y;++ uint8_t text_attrs = m_memory[MEMORY_TEXT_ATTRS];+ bool use_defaults = (text_attrs & 0x1) != 0;++ print_state_t state = {+ .wide = use_defaults && (text_attrs & 0x4),+ .tall = use_defaults && (text_attrs & 0x8),+ .stripey = use_defaults && (text_attrs & 0x40),+ .invert = use_defaults && (text_attrs & 0x20),+ .border = use_defaults ? ((text_attrs & 0x2) != 0) : true,+ .solid_bg = use_defaults && (text_attrs & 0x10),+ .char_w = GLYPH_WIDTH,+ .char_h = GLYPH_HEIGHT,+ .char_w2 = GLYPH_WIDTH * 2,+ .outline_enabled = false,+ .outline_colour = 0,+ .outline_mask = 0,+ .outline_skip_interior = false,+ .use_custom_font = use_defaults && (text_attrs & 0x80),+ .delay_frames = 0+ };++ if (state.use_custom_font) {+ int font_height = m_memory[MEMORY_FONT + 2];+ if (font_height > 0) state.char_h = font_height;+ }++ uint8_t char_size = m_memory[MEMORY_TEXT_CHAR_SIZE];+ uint8_t char_size2 = m_memory[MEMORY_TEXT_CHAR_SIZE2];+ int cw = char_size & 0xf;+ int ch = (char_size >> 4) & 0xf;+ int cw2 = char_size2 & 0xf;+ int tw = (char_size2 >> 4) & 0xf;+ if (cw > 0)+ state.char_w = cw;+ if (cw2 > 0)+ state.char_w2 = cw2;+ if (ch > 0)+ state.char_h = ch;+ if (tw > 0)+ tab_width = tw;++ bool add_newline = (m_memory[MEMORY_MISCFLAGS] & 0x4) == 0;+ bool wrap_enabled = (m_memory[MEMORY_MISCFLAGS] & 0x80) != 0;+ bool memory_no_scroll = (m_memory[MEMORY_MISCFLAGS] & 0x40) != 0;+ bool do_scroll = !memory_no_scroll && !no_scroll;++ for (unsigned i = 0; i < str_len; i++)+ {+ uint8_t character = str[i];+ int index = -1;+ int old_repeat = repeat;+ repeat = 1;++ for (int j = 0; j < old_repeat; j++)+ {+ if (character < 16)+ {+ switch (character) {+ case 0: // "\0"+ add_newline = false;+ str_len = 0;+ break;+ case 1: // "\*"+ if (i + 1 < str_len) {+ int r = hexy(str[++i]);+ if (r != -1)+ repeat = r;+ }+ break;+ case 2: // "\#"+ if (i + 1 < str_len) {+ int b = hexy(str[++i]);+ if (b != -1) {+ bg = b;+ state.solid_bg = true;+ }+ }+ break;+ case 3: // "\-"+ if (i + 1 < str_len) {+ int offset = hexy(str[++i]);+ if (offset != -1)+ x += offset - 16;+ }+ break;+ case 4: // "\|"+ if (i + 1 < str_len) {+ int offset = hexy(str[++i]);+ if (offset != -1)+ y += offset - 16;+ }+ break;+ case 5: // "\+"+ if (i + 2 < str_len) {+ int x_offset = hexy(str[++i]);+ int y_offset = hexy(str[++i]);+ if (x_offset != -1 && y_offset != -1) {+ x += x_offset - 16;+ y += y_offset - 16;+ }+ }+ break;+ case 6: // "\^"+ if (i + 1 < str_len) {+ uint8_t cmd = str[++i];+ switch (cmd) {+ case '1': case '2': case '3': case '4': case '5':+ case '6': case '7': case '8': case '9':+ {+ int frames = 1 << (cmd - '1');+ for (int f = 0; f < frames; f++) {+ p8_flip();+ }+ }+ break;+ case 'c':+ if (i + 1 < str_len) {+ int clear_col = hexy(str[++i]);+ if (clear_col != -1) {+ clear_screen(clear_col);+ x = 0;+ y = 0;+ home_x = 0;+ home_y = 0;+ left_margin = 0;+ }+ }+ break;+ case 'd': // "\^d"+ if (i + 1 < str_len) {+ int df = hexy(str[++i]);+ if (df != -1)+ state.delay_frames = df;+ }+ break;+ case 'g':+ x = home_x;+ y = home_y;+ break;+ case 'h':+ home_x = x;+ home_y = y;+ break;+ case 'j':+ if (i + 2 < str_len) {+ int jx = hexy(str[++i]);+ int jy = hexy(str[++i]);+ if (jx != -1 && jy != -1) {+ x = jx * 4;+ y = jy * 4;+ }+ }+ break;+ case 'r':+ if (i + 1 < str_len) {+ int wb = hexy(str[++i]);+ if (wb != -1) {+ wrap_boundary = wb * 4;+ wrap_enabled = true;+ }+ }+ break;+ case 's':+ if (i + 1 < str_len) {+ int tw = hexy(str[++i]);+ if (tw != -1)+ tab_width = tw;+ }+ break;+ case 'x':+ if (i + 1 < str_len) {+ int cw = hexy(str[++i]);+ if (cw != -1)+ state.char_w = cw;+ }+ break;+ case 'y':+ if (i + 1 < str_len) {+ int ch = hexy(str[++i]);+ if (ch != -1)+ state.char_h = ch;+ }+ break;+ case 'u':+ break;+ case 'w':+ state.wide = true;+ break;+ case 't':+ state.tall = true;+ break;+ case '=':+ state.stripey = true;+ break;+ case 'p':+ state.wide = true;+ state.tall = true;+ state.stripey = true;+ break;+ case 'i':+ state.invert = true;+ break;+ case 'b':+ state.border = !state.border;+ break;+ case '#':+ state.solid_bg = true;+ break;+ case '-':+ if (i + 1 < str_len) {+ uint8_t flag = str[++i];+ switch (flag) {+ case 'w': state.wide = false; break;+ case 't': state.tall = false; break;+ case '=': state.stripey = false; break;+ case 'p':+ state.wide = false;+ state.tall = false;+ state.stripey = false;+ break;+ case 'i': state.invert = false; break;+ case 'b': state.border = !state.border; break;+ case '#':+ state.solid_bg = false;+ break;+ }+ }+ break;+ case '.':+ case ',':+ if (i + 8 < str_len) {+ bool respect_padding = (cmd == ',');+ int draw_x = x + (respect_padding && state.border ? 1 : 0);+ int draw_y = y + (respect_padding && state.border ? 1 : 0);++ for (int row = 0; row < 8 && i + 1 < str_len; row++) {+ uint8_t byte = str[++i];+ for (int bit = 0; bit < 8; bit++) {+ if (byte & (1 << bit)) {+ pixel_set(draw_x + bit, draw_y + row, fg, 0, DRAWTYPE_DEFAULT);+ } else if (state.solid_bg) {+ pixel_set(draw_x + bit, draw_y + row, bg, 0, DRAWTYPE_DEFAULT);+ }+ }+ }+ x += 8;+ last_advance = 8;+ }+ break;+ case ':':+ case ';':+ if (i + 16 < str_len) {+ bool respect_padding = (cmd == ';');+ int draw_x = x + (respect_padding && state.border ? 1 : 0);+ int draw_y = y + (respect_padding && state.border ? 1 : 0);++ bool valid_hex = true;+ for (int row = 0; row < 8 && valid_hex; row++) {+ int h1 = hexy(str[i + row*2 + 1]);+ int h2 = hexy(str[i + row*2 + 2]);+ if (h1 == -1 || h2 == -1) {+ valid_hex = false;+ }+ }+ if (valid_hex) {+ for (int row = 0; row < 8; row++) {+ uint8_t byte = (hexy(str[i + row*2 + 1]) << 4) | hexy(str[i + row*2 + 2]);+ for (int bit = 0; bit < 8; bit++) {+ if (byte & (1 << bit)) {+ pixel_set(draw_x + bit, draw_y + row, fg, 0, DRAWTYPE_DEFAULT);+ } else if (state.solid_bg) {+ pixel_set(draw_x + bit, draw_y + row, bg, 0, DRAWTYPE_DEFAULT);+ }+ }+ }+ i += 16;+ x += 8;+ last_advance = 8;+ }+ }+ break;+ case '@':+ // \^@addrnnnn[data] — poke nnnn bytes to address addr+ // addr and nnnn are 4 hex chars each+ if (i + 8 < str_len) {+ int addr_h1 = hexy(str[i+1]);+ int addr_h2 = hexy(str[i+2]);+ int addr_h3 = hexy(str[i+3]);+ int addr_h4 = hexy(str[i+4]);+ int count_h1 = hexy(str[i+5]);+ int count_h2 = hexy(str[i+6]);+ int count_h3 = hexy(str[i+7]);+ int count_h4 = hexy(str[i+8]);+ if (addr_h1 != -1 && addr_h2 != -1 && addr_h3 != -1 && addr_h4 != -1 &&+ count_h1 != -1 && count_h2 != -1 && count_h3 != -1 && count_h4 != -1) {+ int addr = (addr_h1 << 12) | (addr_h2 << 8) |+ (addr_h3 << 4) | addr_h4;+ int count = (count_h1 << 12) | (count_h2 << 8) |+ (count_h3 << 4) | count_h4;+ i += 8;+ for (int k = 0; k < count && i + 1 < str_len; k++) {+ uint8_t byte = str[++i];+ if ((unsigned)(addr + k) < P8_RAM_SIZE)+ m_memory[addr + k] = byte;+ }++ add_newline = (m_memory[MEMORY_MISCFLAGS] & 0x4) == 0;+ wrap_enabled = (m_memory[MEMORY_MISCFLAGS] & 0x80) != 0;+ memory_no_scroll = (m_memory[MEMORY_MISCFLAGS] & 0x40) != 0;+ do_scroll = !memory_no_scroll && !no_scroll;+ }+ }+ break;+ case '!':+ // \^!addr[data] — poke all remaining characters to address addr+ // addr is 4 hex chars; remaining string bytes are data (not printed)+ if (i + 4 < str_len) {+ int addr_h1 = hexy(str[i+1]);+ int addr_h2 = hexy(str[i+2]);+ int addr_h3 = hexy(str[i+3]);+ int addr_h4 = hexy(str[i+4]);+ if (addr_h1 != -1 && addr_h2 != -1 && addr_h3 != -1 && addr_h4 != -1) {+ int addr = (addr_h1 << 12) | (addr_h2 << 8) |+ (addr_h3 << 4) | addr_h4;+ i += 4;+ int k = 0;+ while (i + 1 < str_len) {+ uint8_t byte = str[++i];+ if ((unsigned)(addr + k) < P8_RAM_SIZE)+ m_memory[addr + k] = byte;+ k++;+ }+ }+ }+ break;+ case 'o':+ if (i + 3 < str_len) {+ uint8_t colour_char = str[++i];+ int mask_h = hexy(str[++i]);+ int mask_l = hexy(str[++i]);++ if (mask_h != -1 && mask_l != -1) {+ state.outline_mask = (mask_h << 4) | mask_l;++ if (colour_char == '$') {+ state.outline_colour = fg;+ state.outline_skip_interior = false;+ } else if (colour_char == '!') {+ state.outline_colour = fg;+ state.outline_skip_interior = true;+ } else {+ int oc = hexy(colour_char);+ if (oc != -1)+ state.outline_colour = oc;+ state.outline_skip_interior = false;+ }++ state.outline_enabled = (state.outline_mask != 0);+ }+ }+ break;+ default:+ break;+ }+ }+ break;+ case 7: // "\a"+ if (i + 1 < str_len) {+ int h1 = hexy(str[i + 1]);+ if (h1 != -1) {+ if (i + 2 < str_len) {+ int h2 = hexy(str[i + 2]);+ if (h2 != -1) {+ int sfx_index = (h1 << 4) | h2;+#ifdef ENABLE_AUDIO+ audio_sound(sfx_index, -1, 0, 32);+#endif+ i += 2;+ }+ }+ }+ } else {+ // TODO: note data support+ }+ break;+ case 8: // "\b"+ x -= last_advance;+ break;+ case 9: // "\t"+ x = ((x / tab_width) + 1) * tab_width;+ break;+ case 0xa: // "\n"+ x = left_margin;+ y += state.char_h * (state.tall ? 2 : 1);+ if (do_scroll)+ y = scroll_newline(y);+ break;+ case 0xb: // "\v"+ if (i + 2 < str_len) {+ int offset_code = hexy(str[++i]);+ if (offset_code != -1) {+ uint8_t decoration_char = str[++i];++ int offset_x = (offset_code % 4) - 2;+ int offset_y = (offset_code / 4) - 8;++ int save_x = x;+ int save_y = y;++ int dec_x = save_x - last_advance + offset_x;+ int dec_y = save_y + offset_y;++ int dec_index = decoration_char;++ if (dec_index >= 0x20 && dec_index < 0x7F) {+ draw_char(dec_index, dec_x, dec_y, fg);+ }+ }+ }+ break;+ case 0xc: // "\f"+ if (i + 1 < str_len) {+ int fc = hexy(str[++i]);+ if (fc != -1) {+ fg = fc;+ m_memory[MEMORY_PENCOLOR] = fg;+ }+ }+ break;+ case 0xd: // "\r"+ x = left_margin;+ break;+ case 0xe: // "\014"+ state.use_custom_font = true;+ if (m_memory[MEMORY_FONT + 6] != 0) {+ tab_width = m_memory[MEMORY_FONT + 6];+ }+ if (m_memory[MEMORY_FONT + 2] != 0) {+ state.char_h = m_memory[MEMORY_FONT + 2];+ }+ break;+ case 0xf: // "\015"+ state.use_custom_font = false;+ break;+ default:+ break;+ }+ }+ else+ {+ index = character;++ if (index >= 0) {+ int base_char_width = state.use_custom_font ? get_custom_font_char_width(index) : (index >= 0x80 ? state.char_w2 : state.char_w);+ int char_width = base_char_width * (state.wide ? 2 : 1);++ bool use_styled = state.wide || state.tall || state.invert || !state.border || state.outline_enabled || state.use_custom_font || (state.char_w != GLYPH_WIDTH) || (state.char_w2 != GLYPH_WIDTH) || (state.char_h != GLYPH_HEIGHT);++ if (wrap_enabled && x + char_width > wrap_boundary) {+ x = left_margin;+ y += state.char_h * (state.tall ? 2 : 1);+ }+ if (do_scroll)+ y = scroll(y, state.char_h * (state.tall ? 2 : 1));++ int draw_bg = state.solid_bg ? bg : -1;+ if (use_styled) {+ draw_char_styled(index, x, y, fg, draw_bg, &state);+ } else if (draw_bg != -1) {+ int char_height = state.char_h * (state.tall ? 2 : 1);+ draw_rectfill(x, y, x + char_width - 1, y + char_height - 1, draw_bg, 0);+ draw_char(index, x, y, fg);+ } else {+ draw_char(index, x, y, fg);+ }++ x += char_width;+ last_advance = char_width;++ for (int f = 0; f < state.delay_frames; f++) {+ p8_flip();+ }++ if (x > right) right = x;+ int char_bottom = y + state.char_h * (state.tall ? 2 : 1);+ if (char_bottom > bottom) bottom = char_bottom;+ }+ }+ }+ }++ if (add_newline) {+ x = left_margin;+ y += state.char_h * (state.tall ? 2 : 1);+ if (do_scroll)+ y = scroll_newline(y);+ }++ if (out_left)+ *out_left = x;+ if (out_top)+ *out_top = y;+ if (out_right)+ *out_right = right;+ if (out_bottom)+ *out_bottom = bottom;+}++#endif // P8_PRINT_HELPER_Hdiff --git a/games/numpico/src/femto8/pico_font.h b/games/numpico/src/femto8/pico_font.hnew file mode 100644index 00000000..111f34bd--- /dev/null+++ b/games/numpico/src/femto8/pico_font.h@@ -0,0 +1,141 @@+#ifndef PICO_FONT_H+#define PICO_FONT_H++#include <stdint.h>++/* (NumPico: one copy, in p8_lua.c) */+extern const uint8_t font_map[8192];+#ifdef PICO_FONT_HERE+const uint8_t font_map[8192] = {+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,+ 0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,+ 0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,+ 0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,+ 0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,+ 0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x07,0x00,0x00,+ 0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x07,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x00,+ 0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,+ 0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,+ 0x70,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x07,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x00,+ 0x00,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,+ 0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,+ 0x07,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,+ 0x07,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x77,0x77,0x77,0x07,0x07,0x07,0x07,0x07,0x07,0x00,0x00,0x07,0x70,0x77,0x77,0x00,0x07,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x70,0x07,0x77,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x70,0x77,0x77,0x00,0x77,0x77,0x77,0x07,0x00,0x70,0x77,0x00,0x70,0x77,0x77,0x00,0x00,0x70,0x00,0x00,+ 0x77,0x77,0x77,0x07,0x70,0x70,0x70,0x00,0x77,0x77,0x77,0x07,0x77,0x00,0x70,0x07,0x00,0x07,0x00,0x07,0x00,0x77,0x77,0x00,0x70,0x77,0x70,0x00,0x70,0x77,0x77,0x00,0x70,0x07,0x77,0x00,0x00,0x77,0x07,0x00,0x70,0x77,0x77,0x00,0x77,0x07,0x70,0x07,0x07,0x77,0x07,0x07,0x00,0x70,0x00,0x00,0x77,0x00,0x70,0x07,0x00,0x77,0x07,0x00,+ 0x77,0x77,0x77,0x07,0x07,0x07,0x07,0x07,0x07,0x77,0x07,0x07,0x77,0x00,0x70,0x07,0x07,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x77,0x07,0x77,0x07,0x70,0x77,0x77,0x00,0x77,0x77,0x77,0x07,0x77,0x00,0x70,0x07,0x77,0x77,0x77,0x07,0x00,0x70,0x00,0x00,0x77,0x70,0x70,0x07,0x70,0x77,0x77,0x00,+ 0x77,0x77,0x77,0x07,0x70,0x70,0x70,0x00,0x07,0x77,0x07,0x07,0x77,0x07,0x77,0x07,0x00,0x07,0x00,0x07,0x70,0x77,0x07,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x07,0x00,0x70,0x07,0x77,0x00,0x00,0x77,0x07,0x00,0x70,0x70,0x70,0x00,0x77,0x07,0x70,0x07,0x07,0x00,0x00,0x07,0x70,0x77,0x00,0x00,0x77,0x00,0x70,0x07,0x00,0x77,0x07,0x00,+ 0x77,0x77,0x77,0x07,0x07,0x07,0x07,0x07,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x07,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x70,0x70,0x77,0x00,0x70,0x77,0x77,0x00,0x77,0x77,0x77,0x07,0x70,0x77,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x70,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x77,0x77,0x77,0x07,0x07,0x07,0x07,0x07,0x70,0x77,0x00,0x00,0x07,0x00,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x00,0x07,0x70,0x00,0x70,0x00,+ 0x00,0x00,0x00,0x00,0x77,0x00,0x77,0x07,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x77,0x07,0x77,0x07,0x07,0x07,0x00,0x00,0x07,0x00,0x07,0x00,0x77,0x70,0x70,0x07,0x00,0x00,0x00,0x00,0x07,0x07,0x07,0x07,0x00,0x07,0x00,0x00,0x07,0x00,0x70,0x00,0x70,0x77,0x07,0x00,0x70,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x77,0x77,0x07,0x07,+ 0x07,0x07,0x07,0x07,0x77,0x00,0x70,0x07,0x77,0x77,0x77,0x07,0x00,0x70,0x00,0x00,0x77,0x00,0x70,0x07,0x70,0x00,0x07,0x07,0x70,0x70,0x70,0x00,0x77,0x07,0x77,0x07,0x77,0x77,0x77,0x07,0x07,0x07,0x07,0x07,0x70,0x77,0x07,0x00,0x07,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x00,0x07,0x00,+ 0x00,0x00,0x00,0x00,0x77,0x00,0x77,0x07,0x70,0x77,0x77,0x00,0x00,0x77,0x07,0x00,0x77,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x07,0x00,0x07,0x77,0x70,0x70,0x07,0x00,0x00,0x00,0x00,0x07,0x07,0x07,0x07,0x07,0x77,0x70,0x00,0x07,0x07,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x07,0x70,0x00,0x07,0x07,0x00,0x07,0x70,0x00,0x07,0x00,+ 0x00,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x77,0x77,0x77,0x07,0x07,0x07,0x07,0x07,0x70,0x07,0x70,0x00,0x70,0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x70,0x70,0x07,0x00,0x70,0x07,0x70,0x00,0x70,0x70,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x70,0x77,0x07,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x70,0x00,0x70,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x07,0x00,0x00,0x77,0x77,0x00,0x70,0x00,0x00,0x00,0x77,0x77,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x77,0x00,0x70,0x70,0x77,0x07,+ 0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x70,0x70,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x77,0x77,0x00,0x70,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x77,0x77,0x77,0x00,0x00,0x00,0x07,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x70,0x77,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x07,+ 0x00,0x77,0x77,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x07,0x00,0x70,0x77,0x77,0x07,0x70,0x00,0x77,0x00,0x70,0x77,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x07,0x00,0x70,0x00,0x00,0x00,+ 0x07,0x00,0x07,0x00,0x00,0x77,0x00,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x70,0x00,0x00,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x70,0x77,0x07,0x70,0x70,0x00,0x00,+ 0x70,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x07,0x00,0x00,0x77,0x77,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x77,0x00,0x70,0x00,0x77,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x77,0x00,0x00,0x70,0x07,0x00,0x70,0x00,0x77,0x07,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x07,0x70,0x00,0x00,0x70,0x70,0x07,0x00,0x00,0x77,0x77,0x00,0x70,0x00,0x07,0x00,0x77,0x00,0x70,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x77,0x77,0x07,0x70,0x77,0x77,0x00,0x70,0x07,0x00,0x00,0x00,0x07,0x70,0x00,0x70,0x70,0x00,0x00,0x70,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x70,0x70,0x77,0x00,0x00,0x07,0x00,0x00,+ 0x70,0x77,0x77,0x00,0x77,0x07,0x70,0x00,0x70,0x70,0x00,0x07,0x70,0x70,0x77,0x00,0x70,0x00,0x70,0x07,0x00,0x00,0x00,0x00,0x00,0x77,0x00,0x00,0x07,0x70,0x77,0x07,0x00,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x70,0x77,0x00,0x07,0x00,0x77,0x77,0x00,0x00,0x07,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x07,0x07,0x07,0x00,0x77,0x07,0x00,+ 0x77,0x70,0x00,0x07,0x70,0x00,0x70,0x00,0x07,0x70,0x00,0x07,0x70,0x00,0x07,0x00,0x70,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x07,0x00,0x07,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x07,0x00,0x07,0x00,0x00,0x70,0x70,0x07,0x07,0x70,0x77,0x07,0x00,0x00,0x07,0x70,0x00,0x70,0x00,0x07,0x07,0x00,0x07,0x00,0x00,+ 0x07,0x77,0x70,0x07,0x77,0x00,0x77,0x07,0x07,0x70,0x00,0x07,0x70,0x70,0x77,0x00,0x70,0x00,0x70,0x00,0x70,0x70,0x70,0x00,0x07,0x00,0x70,0x00,0x07,0x77,0x77,0x00,0x70,0x77,0x07,0x00,0x70,0x07,0x70,0x00,0x70,0x07,0x00,0x07,0x70,0x07,0x00,0x07,0x00,0x07,0x00,0x07,0x00,0x70,0x00,0x00,0x00,0x00,0x77,0x00,0x70,0x77,0x07,0x00,+ 0x70,0x07,0x70,0x07,0x70,0x00,0x77,0x00,0x70,0x07,0x00,0x07,0x70,0x70,0x07,0x00,0x00,0x77,0x07,0x00,0x07,0x77,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x77,0x07,0x07,0x70,0x77,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x70,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x07,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x70,0x00,0x00,0x70,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x70,0x07,0x00,0x70,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x00,+ 0x70,0x00,0x00,0x00,0x70,0x00,0x70,0x00,0x00,0x70,0x07,0x00,0x70,0x07,0x77,0x00,0x00,0x70,0x07,0x00,0x77,0x07,0x70,0x00,0x00,0x07,0x70,0x07,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x70,0x00,0x00,+ 0x70,0x77,0x77,0x00,0x70,0x07,0x70,0x00,0x00,0x07,0x70,0x00,0x00,0x77,0x70,0x00,0x00,0x07,0x70,0x00,0x70,0x00,0x70,0x00,0x00,0x77,0x07,0x00,0x70,0x07,0x00,0x00,0x70,0x77,0x00,0x00,0x77,0x77,0x07,0x00,0x77,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x07,0x00,0x70,0x77,0x00,0x00,0x70,0x00,0x70,0x00,0x00,0x70,0x00,0x00,+ 0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x70,0x00,0x77,0x07,0x70,0x07,0x70,0x00,0x70,0x00,0x00,0x07,0x77,0x00,0x70,0x00,0x00,0x70,0x70,0x00,0x77,0x70,0x70,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x07,0x00,0x07,0x07,0x07,0x00,0x70,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x00,+ 0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x00,0x77,0x00,0x00,0x07,0x70,0x07,0x00,0x00,0x77,0x00,0x70,0x00,0x07,0x00,0x00,0x70,0x77,0x07,0x07,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x77,0x00,0x00,0x70,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x07,0x00,0x70,0x77,0x77,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x77,0x00,0x00,0x07,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x70,0x07,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x07,0x00,0x70,0x70,0x70,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00,+ 0x70,0x77,0x77,0x07,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x00,0x77,0x77,0x07,0x00,0x00,0x70,0x00,0x70,0x77,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x70,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x70,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,+ 0x00,0x70,0x07,0x00,0x00,0x07,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x07,0x70,0x00,0x70,0x07,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x70,0x00,0x00,0x00,0x70,0x00,0x07,0x77,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x07,0x00,+ 0x00,0x07,0x07,0x00,0x70,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x70,0x00,+ 0x70,0x00,0x07,0x00,0x70,0x00,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x00,0x00,0x70,0x07,0x70,0x00,0x00,0x70,0x77,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x07,0x70,0x77,0x07,0x00,0x00,0x07,0x00,0x00,+ 0x70,0x77,0x77,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x07,0x70,0x00,0x70,0x77,0x07,0x00,0x00,0x00,0x70,0x00,0x70,0x00,0x07,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x70,0x00,0x00,0x07,0x00,0x00,0x70,0x77,0x77,0x00,+ 0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x07,0x70,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x07,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x00,0x00,0x07,0x00,0x70,0x77,0x07,0x00,0x00,0x07,0x70,0x00,+ 0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x70,0x77,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x07,0x70,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x70,0x70,0x70,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x07,0x00,0x70,0x70,0x07,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,+ 0x00,0x07,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x00,0x00,0x70,0x00,0x00,0x07,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x70,0x70,0x00,0x00,0x00,0x07,0x00,0x70,0x77,0x07,0x00,0x70,0x77,0x77,0x07,0x70,0x07,0x00,0x00,0x00,0x77,0x77,0x00,0x00,0x07,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x77,0x07,0x00,0x70,0x77,0x07,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x00,0x07,0x07,0x00,0x70,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x70,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,+ 0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x70,0x00,0x00,0x07,0x07,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x07,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,+ 0x00,0x00,0x07,0x00,0x70,0x77,0x07,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x00,0x07,0x07,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x77,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x70,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x77,0x00,0x70,0x07,0x77,0x00,0x70,0x07,+ 0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x07,0x07,0x07,0x70,0x00,0x07,0x00,0x70,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,+ 0x70,0x77,0x77,0x00,0x70,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x77,0x00,0x70,0x77,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x70,0x77,0x00,0x00,0x70,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,+};+#endif++#endif // PICO_FONT_Hdiff --git a/games/numpico/src/heap.c b/games/numpico/src/heap.cnew file mode 100644index 00000000..8eb81ef8--- /dev/null+++ b/games/numpico/src/heap.c@@ -0,0 +1,183 @@+/* Lua's memory: all the RAM the app has after its own (plat_heap), without a header on any block.+ * Lua says how big a block is when it frees or resizes it, so a block is just its bytes, rounded up+ * to 8 (a free block's size and link; 16 on a 64-bit computer). Small blocks (up to 256 bytes,+ * most of Lua's) go back to a list of their size and come out first from there; bigger ones go back to a list kept in address order, merged with their+ * free neighbours. When a block doesn't fit anywhere, the small free blocks go back to that list+ * too, merged, and the search is made again. */+#include "heap.h"+#include <stddef.h>+#include <string.h>++#define SMALL_MAX 256+#define GRAIN ((uint32_t)sizeof(blk_t))+#define CLASSES (SMALL_MAX / GRAIN)++typedef struct blk {+ uint32_t size;+ struct blk *next;+} blk_t;++static blk_t *small[CLASSES];+static blk_t *big; /* address order */+static uint8_t *lo, *hi;+static uint32_t used, peak;++static uint32_t r8(size_t n) { return n ? (uint32_t)((n + GRAIN - 1) & ~(size_t)(GRAIN - 1)) : GRAIN; }++void heap_init(uint8_t *start, uint8_t *end) {+ lo = (uint8_t *)(((uintptr_t)start + GRAIN - 1) & ~(uintptr_t)(GRAIN - 1));+ hi = (uint8_t *)((uintptr_t)end & ~(uintptr_t)(GRAIN - 1));+ memset(small, 0, sizeof small);+ big = NULL;+ if (hi > lo + 16) {+ big = (blk_t *)lo;+ big->size = (uint32_t)(hi - lo);+ big->next = NULL;+ }+ used = peak = 0;+}++uint32_t heap_used(void) { return used; }+uint32_t heap_peak(void) { return peak; }+uint32_t heap_size(void) { return hi > lo ? (uint32_t)(hi - lo) : 0; }++/* back into the address-ordered list, merged with the blocks around it */+static void put_big(uint8_t *p, uint32_t n) {+ blk_t **at = &big;+ while (*at && (uint8_t *)*at < p) at = &(*at)->next;+ blk_t *prev = at == &big ? NULL : (blk_t *)((uint8_t *)at - offsetof(blk_t, next));+ blk_t *next = *at;+ if (prev && (uint8_t *)prev + prev->size == p) {+ prev->size += n;+ if (next && (uint8_t *)prev + prev->size == (uint8_t *)next) prev->size += next->size, prev->next = next->next;+ return;+ }+ blk_t *b = (blk_t *)p;+ b->size = n;+ b->next = next;+ if (next && p + n == (uint8_t *)next) b->size += next->size, b->next = next->next;+ *at = b;+}++/* the first free block it fits in: its end */+static void *take_big(uint32_t n) {+ for (blk_t **at = &big; *at; at = &(*at)->next) {+ blk_t *b = *at;+ if (b->size < n) continue;+ if (b->size - n < GRAIN) { /* (it can't be less but 0 or GRAIN or more) */+ *at = b->next;+ return b;+ }+ b->size -= n;+ return (uint8_t *)b + b->size;+ }+ return NULL;+}++/* a sorted list of blocks (merge sort on the list itself) */+static blk_t *sort(blk_t *l, int n) {+ if (n <= 1) {+ if (l) l->next = NULL;+ return l;+ }+ blk_t *mid = l;+ for (int i = 0; i < n / 2 - 1; i++) mid = mid->next;+ blk_t *r = mid->next;+ mid->next = NULL;+ blk_t *a = sort(l, n / 2), *b = sort(r, n - n / 2), *out = NULL, **tail = &out;+ while (a && b) {+ blk_t **m = (uint8_t *)a < (uint8_t *)b ? &a : &b;+ *tail = *m;+ tail = &(*m)->next;+ *m = (*m)->next;+ }+ *tail = a ? a : b;+ return out;+}++/* the small free blocks back into the big list */+static void reclaim(void) {+ blk_t *all = NULL;+ int n = 0;+ for (int c = 0; c < CLASSES; c++) {+ while (small[c]) {+ blk_t *b = small[c];+ small[c] = b->next;+ b->size = (uint32_t)(c + 1) * GRAIN;+ b->next = all;+ all = b;+ n++;+ }+ }+ if (!n) return;+ all = sort(all, n);+ /* (merge the two sorted lists, joining neighbours) */+ blk_t *a = big, *out = NULL, *last = NULL;+ big = NULL;+ while (a || all) {+ blk_t **m = !all || (a && (uint8_t *)a < (uint8_t *)all) ? &a : &all;+ blk_t *b = *m;+ *m = b->next;+ if (last && (uint8_t *)last + last->size == (uint8_t *)b) {+ last->size += b->size;+ } else {+ b->next = NULL;+ if (last) last->next = b;+ else out = b;+ last = b;+ }+ }+ big = out;+}++static void *alloc(uint32_t n) {+ void *p = NULL;+ if (n <= SMALL_MAX && small[n / GRAIN - 1]) {+ blk_t *b = small[n / GRAIN - 1];+ small[n / GRAIN - 1] = b->next;+ p = b;+ } else {+ p = take_big(n);+ if (!p) {+ reclaim();+ p = take_big(n);+ }+ }+ if (p) {+ used += n;+ if (used > peak) peak = used;+ }+ return p;+}++static void release(void *p, uint32_t n) {+ used -= n;+ if (n <= SMALL_MAX) {+ blk_t *b = p;+ b->next = small[n / GRAIN - 1];+ small[n / GRAIN - 1] = b;+ } else {+ put_big(p, n);+ }+}++void *heap_alloc(void *ud, void *ptr, size_t osize, size_t nsize) {+ (void)ud;+ if (!ptr) return nsize ? alloc(r8(nsize)) : NULL;+ uint32_t o = r8(osize);+ if (!nsize) {+ release(ptr, o);+ return NULL;+ }+ uint32_t n = r8(nsize);+ if (n == o) return ptr;+ if (n < o) { /* the end of it goes back */+ release((uint8_t *)ptr + n, o - n);+ return ptr;+ }+ void *q = alloc(n);+ if (!q) return NULL;+ memcpy(q, ptr, o);+ release(ptr, o);+ return q;+}diff --git a/games/numpico/src/heap.h b/games/numpico/src/heap.hnew file mode 100644index 00000000..529ee728--- /dev/null+++ b/games/numpico/src/heap.h@@ -0,0 +1,12 @@+/* Lua's memory (heap.c). */+#ifndef NP8_HEAP_H+#define NP8_HEAP_H+#include <stddef.h>+#include <stdint.h>+void heap_init(uint8_t *start, uint8_t *end);+/* lua_Alloc */+void *heap_alloc(void *ud, void *ptr, size_t osize, size_t nsize);+uint32_t heap_used(void);+uint32_t heap_peak(void);+uint32_t heap_size(void);+#endifdiff --git a/games/numpico/src/icon.png b/games/numpico/src/icon.pngnew file mode 100644index 00000000..2238e7d8Binary files /dev/null and b/games/numpico/src/icon.png differdiff --git a/games/numpico/src/main.c b/games/numpico/src/main.cnew file mode 100644index 00000000..ebcbf333--- /dev/null+++ b/games/numpico/src/main.c@@ -0,0 +1,313 @@+/* NumPico: PICO-8 carts on the calculator.+ *+ * The carts come in a table in flash, np_carts (tools/p8cart.py, or NumPlay Studio), read in place.+ * One cart starts at once; with several, a list shows them with their labels. A cart plays with the+ * keys written at the left of its picture (pico.c runs it); its errors, and a cart too big for the+ * calculator's memory, say so in plain words. Home quits from anywhere.+ *+ * The screens are drawn in strips (the launcher's gfx.c), the strip's buffer at the start of the RAM+ * Lua gets while a cart plays. Everything is written with PICO-8's own font. */+#include <string.h>+#include "gfx.h"+#include "heap.h"+#include "pico.h"+#include "plat.h"++#if PLATFORM_DEVICE+/* the carts: np_carts (weak: a NumPlay with no carts has none), up to the end of NumPico's block of+ flash (np_numpico_end: NumPlay's linker script, or carts.ld on its own) */+extern const uint8_t np_carts[] __attribute__((weak));+extern const uint8_t np_numpico_end[];+#define TABLE_LIMIT ((uintptr_t)np_numpico_end > (uintptr_t)np_carts ? (uint32_t)((uintptr_t)np_numpico_end - (uintptr_t)np_carts) : 0)+#else+extern const uint8_t *np_carts;+extern uint32_t np_carts_size;+#define TABLE_LIMIT np_carts_size+#endif++#define WHITE pico_rgb565[7]+#define GREY pico_rgb565[6]+#define DARK pico_rgb565[5]+#define BLACK 0x0000++/* ------------------------------------------------------------ settings (numpico.cfg) */+#define CFG_NAME "numpico.cfg"+static struct {+ uint8_t magic, version, sel, pad;+} cfg;++static void cfg_load(void) {+ uint32_t len = 0;+ const uint8_t *d = plat_load(CFG_NAME, &len);+ memset(&cfg, 0, sizeof cfg);+ if (d && len == sizeof cfg) memcpy(&cfg, d, sizeof cfg);+ if (cfg.magic != 'P' || cfg.version != 1) memset(&cfg, 0, sizeof cfg);+ cfg.magic = 'P', cfg.version = 1;+}+static void cfg_save(void) { plat_save(CFG_NAME, &cfg, sizeof cfg); }++/* ------------------------------------------------------------ drawing */+static void strips_init(void) {+ uint8_t *a, *b;+ plat_heap(&a, &b);+ gfx_buf = (color_t *)(((uintptr_t)a + 3) & ~(uintptr_t)3);+}++/* PICO-8's letters (lowercase shows as its capitals), `s` pixels each */+static int ptext(int x, int y, const char *t, color_t c, int s) {+ for (; *t; t++) {+ uint8_t ch = (uint8_t)*t;+ if (ch >= 'A' && ch <= 'Z') ch = (uint8_t)(ch - 'A' + 'a');+ int w = ch >= 0x80 ? 8 : 4;+ if (y + 6 * s > gfx_y0 && y < gfx_y1)+ for (int gy = 0; gy < 6; gy++)+ for (int gx = 0; gx < w; gx++)+ if (pico_glyph_px(ch, gx, gy)) gfx_fill(x + gx * s, y + gy * s, s, s, c);+ x += w * s;+ }+ return x;+}++static int ptext_w(const char *t, int s) { return pico_text_w(t) * s; }++/* a cart's label, 128 x 128 at (x, y) */+static void label(const uint8_t *l, int x, int y) {+ uint16_t pal[16];+ for (int i = 0; i < 16; i++) pal[i] = pico_rgb565[(l[i] & 15) | (l[i] & 0x80 ? 16 : 0)];+ const uint8_t *px = l + 16;+ for (int row = NP_MAX(y, gfx_y0); row < NP_MIN(y + 128, gfx_y1); row++) {+ color_t *d = gfx_buf + (row - gfx_y0) * SCREEN_W + x;+ const uint8_t *s = px + (row - y) * 64;+ for (int i = 0; i < 64; i++) d[2 * i] = pal[s[i] & 15], d[2 * i + 1] = pal[s[i] >> 4];+ }+}++/* the words of `t` on lines of at most `w` pixels, from y down; the next line's y */+static int paragraph(int x, int y, int w, const char *t, color_t c, int s) {+ char line[80];+ int max = NP_MIN(w / (4 * s), (int)sizeof line - 1);+ while (*t) {+ int n = 0, cut = 0;+ while (t[n] && t[n] != '\n' && n < max) {+ if (t[n] == ' ') cut = n;+ n++;+ }+ if (t[n] && t[n] != '\n' && t[n] != ' ' && cut) n = cut;+ memcpy(line, t, n);+ line[n] = 0;+ ptext(x, y, line, c, s);+ y += 8 * s;+ t += n;+ while (*t == ' ' || *t == '\n') t++;+ }+ return y;+}++/* a cart's name to show: its title, else its file's; and its author */+static void cart_name(int i, char *name, int n, char *author, int an) {+ carts_title(&pico_carts[i], name, n, author, an);+ if (!name[0]) carts_name(&pico_carts[i], name, n);+}++/* the key line at the bottom */+static void keys_line(const char *a, const char *b) {+ int x = ptext(14, 222, a, GREY, 2);+ if (b) ptext(x + 20, 222, b, GREY, 2);+}++/* ------------------------------------------------------------ the list of carts */+static int sel, top;+#define ROWS 8+#define ROW_H 20++static void list_scene(void *ctx) {+ (void)ctx;+ gfx_fill(0, gfx_y0, SCREEN_W, gfx_y1 - gfx_y0, BLACK);+ ptext(14, 12, "numpico", WHITE, 2);+ char n[16];+ int k = pico_ncarts, d = 0;+ char tmp[8];+ do tmp[d++] = (char)('0' + k % 10), k /= 10; while (k);+ for (int i = 0; i < d; i++) n[i] = tmp[d - 1 - i];+ strcpy(n + d, " carts");+ ptext(SCREEN_W - 14 - ptext_w(n, 2), 12, n, DARK, 2);+ for (int r = 0; r < ROWS && top + r < pico_ncarts; r++) {+ int i = top + r, y = 40 + r * ROW_H;+ if (i == sel) {+ gfx_rrect(8, y, 160, ROW_H - 2, 3, pico_rgb565[1], 256);+ gfx_rrect_outline(8, y, 160, ROW_H - 2, 3, 2, pico_rgb565[12], 256);+ }+ char name[19], author[2];+ cart_name(i, name, sizeof name, author, sizeof author);+ ptext(16, y + 4, name, i == sel ? WHITE : GREY, 2);+ }+ /* (more above or below) */+ if (top > 0) ptext(84, 30, "\x94", DARK, 1);+ if (top + ROWS < pico_ncarts) ptext(84, 40 + ROWS * ROW_H - 2, "\x83", DARK, 1);+ /* the cart: its label, title and author */+ const p8_cart_t *c = &pico_carts[sel];+ gfx_fill(178, 36, 136, 136, WHITE);+ if (c->label) label(c->label, 182, 40);+ else gfx_fill(182, 40, 128, 128, pico_rgb565[1]);+ char t[33], a[33];+ cart_name(sel, t, sizeof t, a, sizeof a);+ ptext(178, 180, t, WHITE, 1);+ ptext(178, 190, a, GREY, 1);+ keys_line("ok play", "home quit");+}++static void list_draw(void) {+ if (sel < top) top = sel;+ if (sel >= top + ROWS) top = sel - ROWS + 1;+ gfx_render(list_scene, NULL, 0, 240);+}++/* ------------------------------------------------------------ other screens */+static void blank_scene(void *ctx) {+ (void)ctx;+ gfx_fill(0, gfx_y0, SCREEN_W, gfx_y1 - gfx_y0, BLACK);+}++static void none_scene(void *ctx) {+ blank_scene(ctx);+ ptext(14, 12, "numpico", WHITE, 2);+ ptext(14, 70, "no carts yet", WHITE, 2);+ paragraph(14, 100, 292, "add your .p8 and .p8.png carts in numplay studio.", GREY, 2);+ keys_line("home quit", NULL);+}++/* the keys, at the left of the picture */+static void panel_scene(void *ctx) {+ (void)ctx;+ gfx_fill(0, gfx_y0, PIC_X, gfx_y1 - gfx_y0, BLACK);+ static const char *const hints[][2] = {+ {"arrows", "\x8b\x91\x94\x83"}, {"ok, exe", "\x8e"}, {"back, ans", "\x97"}, {"backspace", "menu"}, {"home", "quit"}};+ int y = 40;+ for (int i = 0; i < 5; i++) {+ ptext(4, y, hints[i][0], DARK, 2);+ ptext(4, y + 14, hints[i][1], WHITE, 2);+ y += 34;+ }+}++static int ended; /* how the cart ended, for end_scene */+static bool alone;++static void end_scene(void *ctx) {+ blank_scene(ctx);+ int y = 30;+ if (ended == PICO_MEMORY) {+ ptext(14, y, "out of memory", pico_rgb565[8], 2);+ char t[96] = "this cart needs more memory than the calculator has (";+ int kb = (int)(heap_size() / 1024), n = (int)strlen(t);+ char d[8];+ int k = 0;+ do d[k++] = (char)('0' + kb % 10), kb /= 10; while (kb);+ while (k) t[n++] = d[--k];+ strcpy(t + n, " kb).");+ paragraph(14, y + 34, 292, t, GREY, 2);+ } else {+ ptext(14, y, pico_error.what, pico_rgb565[8], 2);+ if (pico_error.line > 0) {+ char t[16] = "line ";+ int n = 5, v = pico_error.line;+ char d[8];+ int k = 0;+ do d[k++] = (char)('0' + v % 10), v /= 10; while (v);+ while (k) t[n++] = d[--k];+ t[n] = 0;+ ptext(14, y + 20, t, GREY, 2);+ }+ paragraph(14, y + 44, 292, pico_error.msg, WHITE, 2);+ }+ keys_line("ok run again", alone ? "home quit" : "back carts");+}++/* ------------------------------------------------------------ keys */+static uint32_t held;+static uint32_t hits(void) {+ uint32_t k = plat_keys(), hit = k & ~held;+ held = k;+ return hit;+}++/* ------------------------------------------------------------ playing */+/* a cart until it's left: 0 back to the list, 1 Home */+static int play(int i) {+ for (;;) {+ strips_init();+ gfx_render(panel_scene, NULL, 0, 240);+ int how = pico_run(i);+ while (how == PICO_LOAD) {+ i = pico_next;+ strips_init();+ gfx_render(panel_scene, NULL, 0, 240);+ how = pico_run(i);+ }+#ifdef HOST+ void host_ended(int how);+ host_ended(how);+#endif+ if (how == PICO_HOME) return 1;+ if (how == PICO_QUIT) return 0;+ /* an error, or too little memory: say so */+ strips_init();+ ended = how;+ gfx_render(end_scene, NULL, 0, 240);+ held = plat_keys();+ for (;;) {+ uint32_t k = hits();+ if (k & PK_HOME) return 1;+ if (k & PK_OK) break;+ if ((k & PK_BACK) && !alone) return 0;+ plat_sleep(20);+ }+ }+}++int numpico_main(void) {+ plat_begin();+ strips_init();+ cfg_load();+ int n = carts_read(np_carts, np_carts ? TABLE_LIMIT : 0, pico_carts, P8_MAX_CARTS);+ pico_ncarts = n > 0 ? n : 0;+ held = plat_keys();+ if (!pico_ncarts) {+ gfx_render(none_scene, NULL, 0, 240);+ while (!(hits() & PK_HOME)) plat_sleep(20);+ return plat_end();+ }+ alone = pico_ncarts == 1;+ if (alone) {+ play(0);+ return plat_end();+ }+ sel = cfg.sel < pico_ncarts ? cfg.sel : 0;+ list_draw();+ for (;;) {+ uint32_t k = hits();+ if (k & PK_HOME) break;+ int was = sel;+ if (k & PK_UP) sel = (sel + pico_ncarts - 1) % pico_ncarts;+ if (k & PK_DOWN) sel = (sel + 1) % pico_ncarts;+ if (k & PK_LEFT) sel = NP_MAX(sel - ROWS, 0);+ if (k & PK_RIGHT) sel = NP_MIN(sel + ROWS, pico_ncarts - 1);+ if (sel != was) list_draw();+ if (k & PK_OK) {+ cfg.sel = (uint8_t)sel;+ cfg_save();+ if (play(sel)) break;+ strips_init();+ list_draw();+ held = plat_keys();+ }+ plat_sleep(16);+ }+ cfg.sel = (uint8_t)sel;+ cfg_save();+ return plat_end();+}++#if PLATFORM_DEVICE+int main(void) { return numpico_main(); }+#endifdiff --git a/games/numpico/src/pico.c b/games/numpico/src/pico.cnew file mode 100644index 00000000..69b248ca--- /dev/null+++ b/games/numpico/src/pico.c@@ -0,0 +1,666 @@+/* A PICO-8 cart on the calculator: femto8's Lua and API (femto8/) with what the calculator gives it.+ *+ * - Memory: PICO-8's first 32 KB (0x0000 to 0x7fff) here; the cart's ROM is read in place in+ * flash (reload()). Lua gets all the RAM left (heap.c).+ * - Frames: _update (30 a second) or _update60 (60) at the cart's own speed, read from the clock;+ * when the calculator can't keep up, _draw is skipped now and then, as PICO-8 does when a cart+ * is too slow for it. A cart that runs its own loop with flip() is paced the same way.+ * - The picture: PICO-8's 128 x 128 pixels on 240 x 240 of the screen.+ * - Keys: arrows (and 8 4 6 2) the D-pad, OK or EXE O, Back or Ans X, Backspace the pause menu+ * (PICO-8's own: Continue, the cart's items, Reset cart, Quit), Home leaves from anywhere.+ * - cartdata(): 256 bytes for each id, in a file of the calculator's (p8_<id>.dat), written at+ * the end of the frame it changed in. */+#include "pico.h"+#include <setjmp.h>+#include <string.h>+#include "heap.h"+#include "plat.h"+#include "femto8/p8_emu.h"+#include "femto8/p8_input.h"+#include "femto8/p8_lua.h"+#include "femto8/p8_lua_helper.h"+#include "femto8/p8_pause_menu.h"+#include "femto8/lua/lauxlib.h"+#include "femto8/lua/lua.h"++extern lua_State *L; /* (femto8/p8_lua.c) */++/* ------------------------------------------------------------ the state */+static uint8_t ram[P8_RAM_SIZE] __attribute__((aligned(4)));+uint8_t *m_memory = ram;+const uint8_t *m_cart_memory;+unsigned m_fps = 30;+unsigned m_frames;+char m_param_string[256];+uint16_t m_buttons[PLAYER_COUNT];+uint16_t m_buttonsp[PLAYER_COUNT];+p8_custom_menuitem_t m_custom_menuitems[MAX_CUSTOM_MENUITEMS];++p8_cart_t pico_carts[P8_MAX_CARTS];+int pico_ncarts;+pico_error_t pico_error;+int pico_next = -1;+uint32_t pico_peak;++static int cart = -1, breadcrumb = -1;+static jmp_buf run_jmp;+static bool in_lua; /* (a Lua error can only be raised from inside it) */+static uint32_t keys_now; /* the calculator's keys this frame */+static uint32_t keys_held; /* those held when the cart started, ignored until let go */+static uint32_t t0, ticks; /* the clock: frame `ticks` is due at t0 + ticks / fps seconds */+static unsigned clock_fps;+static uint32_t frame_start;+static uint16_t down_frames[6];+static bool first_repeat[6];+static char cartdata_name[40];+static bool cartdata_dirty;++enum { END_RESTART = 16 };++#define KEYS_HOME PK_HOME+static _Noreturn void end_run(int how) { longjmp(run_jmp, how + 1); }++/* ------------------------------------------------------------ PICO-8's colours, RGB565 */+const uint16_t pico_rgb565[32] = {+ 0x0000, 0x194a, 0x792a, 0x042a, 0xaa86, 0x5aa9, 0xc618, 0xff9d, 0xf809, 0xfd00, 0xff64, 0x0726, 0x2d7f, 0x83b3, 0xfbb5, 0xfe75,+ 0x28c2, 0x10e6, 0x4106, 0x128b, 0x7165, 0x4987, 0xa44f, 0xf76f, 0xb88a, 0xfb64, 0xaf25, 0x05a9, 0x02d6, 0x722c, 0xfb6b, 0xfcf0};++static inline int color_index(uint8_t c) { return ((c >> 3) & 0x10) | (c & 0xf); }++bool pico_glyph_px(uint8_t c, int x, int y) {+ if (x < 0 || x > 7 || y < 0 || y > 7) return false;+ int sx = (c & 15) * 8 + x, sy = (c >> 4) * 8 + y;+ uint8_t b = font_map[sy * 64 + (sx >> 1)];+ return ((sx & 1) ? b >> 4 : b & 15) == 7;+}++int pico_text_w(const char *s) {+ int w = 0;+ for (; *s; s++) w += (uint8_t)*s >= 0x80 ? 8 : 4;+ return w;+}++/* ------------------------------------------------------------ the pause menu, over the picture */+#define MENU_MAX (MAX_CUSTOM_MENUITEMS + 3)+static struct {+ bool on;+ int n, sel;+ const char *title;+ const char *items[MENU_MAX];+} menu;++/* the menu's box, in PICO-8's pixels */+static void menu_box(int *x0, int *y0, int *x1, int *y1) {+ int w = 0;+ for (int i = 0; i < menu.n; i++) w = MAX(w, pico_text_w(menu.items[i]));+ if (menu.title) w = MAX(w, pico_text_w(menu.title) - 8);+ w += 18;+ int h = menu.n * 8 + 7 + (menu.title ? 10 : 0);+ *x0 = 64 - w / 2, *x1 = *x0 + w - 1;+ *y0 = 64 - h / 2, *y1 = *y0 + h - 1;+}++static void text_row(int8_t *out, const char *s, int x, int row, int col) {+ for (; *s; s++) {+ uint8_t c = (uint8_t)*s;+ int w = c >= 0x80 ? 8 : 4;+ for (int gx = 0; gx < w; gx++)+ if (x + gx >= 0 && x + gx < 128 && pico_glyph_px(c, gx, row)) out[x + gx] = (int8_t)col;+ x += w;+ }+}++/* one row of the menu: -1 where the picture shows */+static void menu_row(int y, int8_t *out) {+ int x0, y0, x1, y1;+ menu_box(&x0, &y0, &x1, &y1);+ if (y < y0 || y > y1) return;+ for (int x = x0; x <= x1; x++) out[x] = (y == y0 || y == y1 || x == x0 || x == x1) ? 7 : 0;+ int top = y0 + 4;+ if (menu.title) {+ if (y >= top && y < top + 6) text_row(out, menu.title, x0 + 5, y - top, 6);+ top += 10;+ }+ int i = (y - top) / 8, r = (y - top) % 8;+ if (y < top || i >= menu.n || r >= 6) return;+ text_row(out, menu.items[i], x0 + 12, r, 7);+ if (i == menu.sel) text_row(out, "\x17", x0 + 4, r, 7); /* (▶) */+}++/* ------------------------------------------------------------ the picture */+static uint16_t lines[2 * PIC_W] __attribute__((aligned(4)));++/* where 0x5f2c (the screen's mode) takes an output pixel from */+static void transform(uint8_t mode, int ox, int oy, int *sx, int *sy) {+ switch (mode) {+ default: *sx = ox, *sy = oy; break;+ case 1: *sx = ox >> 1, *sy = oy; break;+ case 2: *sx = ox, *sy = oy >> 1; break;+ case 3: *sx = ox >> 1, *sy = oy >> 1; break;+ case 5: *sx = ox < 64 ? ox : 127 - ox, *sy = oy; break;+ case 6: *sx = ox, *sy = oy < 64 ? oy : 127 - oy; break;+ case 7: *sx = ox < 64 ? ox : 127 - ox, *sy = oy < 64 ? oy : 127 - oy; break;+ case 129: *sx = 127 - ox, *sy = oy; break;+ case 130: *sx = ox, *sy = 127 - oy; break;+ case 131: case 134: *sx = 127 - ox, *sy = 127 - oy; break;+ case 133: *sx = 127 - oy, *sy = ox; break;+ case 135: *sx = oy, *sy = 127 - ox; break;+ }+}++/* (femto8's high colour modes, 0x5f5f) */+static uint8_t high_color(uint8_t hc, uint8_t pix, int sx, int sy) {+ if (hc == 0x10) {+ uint8_t bf = m_memory[0x5f70 + (sy >> 3)];+ return color_get((bf & (1 << (sy & 7))) ? PALTYPE_SECONDARY : PALTYPE_SCREEN, pix);+ }+ if (hc == 0x20) {+ uint8_t v = m_memory[p8_screen_base() + ((sx + 64) >> 1) + sy * 64];+ uint8_t hidden = IS_EVEN(sx + 64) ? (v & 0xF) : (v >> 4);+ return color_get(hidden ? PALTYPE_SECONDARY : PALTYPE_SCREEN, pix);+ }+ if ((hc & 0xf0) == 0x30) {+ uint8_t c = color_get(PALTYPE_SCREEN, pix);+ if ((c & 0x0f) == (hc & 0x0f)) {+ int section = sy >> 3;+ if (m_memory[0x5f70 + (sy >> 3)] & (1 << (sy & 7))) section = (section + 1) & 0x0f;+ return color_get(PALTYPE_SECONDARY, section);+ }+ return c;+ }+ return color_get(PALTYPE_SCREEN, pix);+}++/* (for tools/emu.py and tests/perf.py: pictures shown, frames run, Lua's memory at its most) */+__attribute__((used)) uint32_t perf_frames, perf_updates, perf_heap, perf_heap_size, perf_end;++void p8_render(void) {+ perf_frames++;+ const uint8_t *scr = m_memory + p8_screen_base();+ const uint8_t *pal = m_memory + MEMORY_PALETTES + PALTYPE_SCREEN * 16;+ uint8_t mode = m_memory[MEMORY_SCREEN_TRANSFORM], hc = m_memory[MEMORY_HIGH_COLOUR_MODE];+ uint16_t rgb[16];+ for (int i = 0; i < 16; i++) rgb[i] = pico_rgb565[color_index(pal[i])];+ int oy = 0;+ for (int y = 0; y < 128; y++) {+ int8_t over[128];+ if (menu.on) {+ memset(over, -1, sizeof over);+ menu_row(y, over);+ }+ uint16_t *d = lines;+ if (mode == 0 && hc == 0 && !menu.on) {+ const uint8_t *s = scr + y * 64;+ for (int x = 0; x < 64; x += 4) { /* (8 pixels: 15 on the screen) */+ uint16_t c;+ c = rgb[s[x] & 15], d[0] = d[1] = c;+ c = rgb[s[x] >> 4], d[2] = d[3] = c;+ c = rgb[s[x + 1] & 15], d[4] = d[5] = c;+ c = rgb[s[x + 1] >> 4], d[6] = d[7] = c;+ c = rgb[s[x + 2] & 15], d[8] = d[9] = c;+ c = rgb[s[x + 2] >> 4], d[10] = d[11] = c;+ c = rgb[s[x + 3] & 15], d[12] = d[13] = c;+ d[14] = rgb[s[x + 3] >> 4];+ d += 15;+ }+ } else {+ for (int x = 0; x < 128; x++) {+ uint16_t c;+ if (menu.on && over[x] >= 0) {+ c = pico_rgb565[over[x]];+ } else {+ int sx, sy;+ transform(mode, x, y, &sx, &sy);+ uint8_t v = scr[(sx >> 1) + sy * 64], pix = IS_EVEN(sx) ? v & 0xF : v >> 4;+ c = hc ? pico_rgb565[color_index(high_color(hc, pix, sx, sy))] : rgb[pix];+ if (menu.on) c = (c >> 1) & 0x7BEF; /* (the picture dimmed behind the menu) */+ }+ *d++ = c;+ if ((x & 7) != 7) *d++ = c;+ }+ }+ int h = (y & 7) == 7 ? 1 : 2;+ if (h == 2) memcpy(lines + PIC_W, lines, PIC_W * sizeof *lines);+ plat_push(PIC_X, oy, PIC_W, h, lines);+ oy += h;+ }+}++void pico_redraw(void) { p8_render(); }++/* ------------------------------------------------------------ keys and buttons */+static uint16_t buttons_of(uint32_t k) {+ uint16_t b = 0;+ if (k & PK_LEFT) b |= BUTTON_MASK_LEFT;+ if (k & PK_RIGHT) b |= BUTTON_MASK_RIGHT;+ if (k & PK_UP) b |= BUTTON_MASK_UP;+ if (k & PK_DOWN) b |= BUTTON_MASK_DOWN;+ if (k & PK_O) b |= BUTTON_MASK_ACTION1;+ if (k & PK_X) b |= BUTTON_MASK_ACTION2;+ return b;+}++static void flush_cartdata(void) {+ if (cartdata_dirty && cartdata_name[0]) plat_save(cartdata_name, m_memory + MEMORY_CARTDATA, MEMORY_CARTDATA_SIZE);+ cartdata_dirty = false;+}++static void home(void) {+ flush_cartdata();+ end_run(PICO_HOME);+}++/* the keys for this frame: btn() and btnp() (repeating after 15 frames, every 4, or 0x5f5c and+ 0x5f5d's; twice as many at 60 a second) */+static void read_keys(void) {+ uint32_t k = plat_keys();+ keys_held &= k;+ if (k & PK_HOME) home();+ uint32_t fresh = k & ~keys_now;+ keys_now = k;+ k &= ~keys_held;+ m_buttons[0] = buttons_of(k);+ m_buttonsp[0] = 0;+ m_buttons[1] = m_buttonsp[1] = 0;+ unsigned delay = m_memory[MEMORY_AUTO_REPEAT_DELAY] ? m_memory[MEMORY_AUTO_REPEAT_DELAY] : DEFAULT_AUTO_REPEAT_DELAY;+ unsigned interval = m_memory[MEMORY_AUTO_REPEAT_INTERVAL] ? m_memory[MEMORY_AUTO_REPEAT_INTERVAL] : DEFAULT_AUTO_REPEAT_INTERVAL;+ if (m_fps == 60) delay *= 2, interval *= 2;+ for (int i = 0; i < 6; i++) {+ if (!(m_buttons[0] & (1 << i))) {+ down_frames[i] = 0, first_repeat[i] = false;+ continue;+ }+ unsigned n = ++down_frames[i];+ if (n == 1) m_buttonsp[0] |= 1 << i;+ else if (delay != 255 && !first_repeat[i] && n > delay) m_buttonsp[0] |= 1 << i, first_repeat[i] = true, down_frames[i] = 1;+ else if (first_repeat[i] && n > interval) m_buttonsp[0] |= 1 << i, down_frames[i] = 1;+ }+ if (fresh & PK_MENU) {+ m_buttons[0] |= BUTTON_MASK_PAUSE, m_buttonsp[0] |= BUTTON_MASK_PAUSE;+ if (m_memory[MEMORY_SUPPRESS_PAUSE]) m_memory[MEMORY_SUPPRESS_PAUSE] = 0; /* (the cart takes the press) */+ else p8_show_pause_menu();+ }+}++void pico_update_buttons(void) { read_keys(); }++/* ------------------------------------------------------------ frames */+static void clock_reset(void) {+ t0 = plat_millis(), ticks = 0, clock_fps = m_fps ? m_fps : 30;+}++/* the time the next frame is due; a calculator far behind starts the count again (the cart slows+ down rather than skipping on for ever) */+static uint32_t due(void) {+ if (clock_fps != m_fps) clock_reset();+ return t0 + (uint32_t)((uint64_t)ticks * 1000 / clock_fps);+}++static void wait_frame(void) {+ ticks++;+ uint32_t d = due(), now = plat_millis();+ if ((int32_t)(d - now) > 0) plat_sleep(d - now);+ else if ((int32_t)(now - d) > 250) clock_reset();+ frame_start = plat_millis();+}++static void end_frame(void) {+ perf_updates++;+ if (heap_peak() > perf_heap) perf_heap = heap_peak();+ perf_heap_size = heap_size();+ flush_cartdata();+ m_frames++;+}++unsigned p8_elapsed_time(void) { return plat_millis() - frame_start; }++/* flip(): the picture shown, the next frame's keys */+void p8_flip(void) {+ p8_render();+ end_frame();+ wait_frame();+ read_keys();+}++void p8_check_for_next_frame(void) {}+void p8_pump_events(void) {}++/* every few thousand instructions: Home, even in a cart that never ends its frame */+void pico_hook(lua_State *l) {+ (void)l;+ if (plat_keys() & PK_HOME) home();+}++/* ------------------------------------------------------------ the pause menu */+static const char *const PAUSE_ITEMS[] = {"continue", "reset cart", "quit"};++static uint32_t menu_keys(uint32_t *held) {+ uint32_t k = plat_keys();+ if (k & PK_HOME) home();+ uint32_t hit = k & ~*held;+ *held = k;+ return hit;+}++/* a cart's menu item: its function gets the buttons (1 left, 2 right, 16 O, 32 X); true keeps the menu */+static bool call_item(int i, int b) {+ int ref = m_custom_menuitems[i].lua_callback_ref;+ if (ref == LUA_NOREF || ref == LUA_REFNIL || !L) return false;+ menu.on = false;+ int top = lua_gettop(L);+ lua_rawgeti(L, LUA_REGISTRYINDEX, ref);+ lua_pushinteger(L, b);+ int st = lua_pcall(L, 1, 1, 0);+ if (st) {+ lua_get_error(&(const char *){0}, pico_error.msg, sizeof pico_error.msg, NULL, &pico_error.line);+ strcpy(pico_error.what, "runtime error");+ end_run(st == LUA_ERRMEM ? PICO_MEMORY : PICO_ERROR);+ }+ bool keep = lua_toboolean(L, -1);+ lua_settop(L, top);+ return keep;+}++static bool confirm_quit(void) {+ static const char *const items[] = {"no", "yes"};+ menu.title = "quit this cart?";+ menu.n = 2, menu.sel = 0;+ memcpy(menu.items, items, sizeof items);+ uint32_t held = plat_keys();+ for (;;) {+ p8_render();+ uint32_t k = menu_keys(&held);+ if (k & (PK_UP | PK_DOWN)) menu.sel ^= 1;+ if (k & (PK_BACK | PK_X | PK_MENU)) return false;+ if (k & (PK_OK | PK_O)) return menu.sel == 1;+ plat_sleep(16);+ }+}++void p8_show_pause_menu(void) {+ int map[MENU_MAX]; /* each item: -1 continue, -2 reset, -3 quit, else the cart's item */+ int sel = 0;+ for (;;) {+ menu.title = NULL;+ menu.n = 0;+ map[menu.n] = -1, menu.items[menu.n++] = PAUSE_ITEMS[0];+ for (int i = 0; i < MAX_CUSTOM_MENUITEMS; i++)+ if (m_custom_menuitems[i].active) map[menu.n] = i, menu.items[menu.n++] = m_custom_menuitems[i].label;+ map[menu.n] = -2, menu.items[menu.n++] = PAUSE_ITEMS[1];+ map[menu.n] = -3, menu.items[menu.n++] = PAUSE_ITEMS[2];+ menu.sel = sel < menu.n ? sel : 0;+ menu.on = true;+ uint32_t held = plat_keys();+ int chosen = -100, b = 0;+ while (chosen == -100) {+ p8_render();+ uint32_t k = menu_keys(&held);+ if (k & PK_UP) menu.sel = (menu.sel + menu.n - 1) % menu.n;+ if (k & PK_DOWN) menu.sel = (menu.sel + 1) % menu.n;+ if (k & (PK_BACK | PK_X | PK_MENU)) chosen = -1;+ else if (k & (PK_OK | PK_O)) chosen = map[menu.sel], b = 16;+ else if ((k & (PK_LEFT | PK_RIGHT)) && map[menu.sel] >= 0) chosen = map[menu.sel], b = k & PK_LEFT ? 1 : 2;+ plat_sleep(16);+ }+ sel = menu.sel;+ if (chosen == -1) break;+ if (chosen == -2) {+ menu.on = false;+ end_run(END_RESTART);+ }+ if (chosen == -3) {+ if (confirm_quit()) {+ menu.on = false;+ flush_cartdata();+ end_run(PICO_QUIT);+ }+ continue;+ }+ if (!call_item(chosen, b)) break;+ }+ menu.on = false;+ p8_render();+ keys_held = plat_keys(); /* (the key that closed the menu isn't the cart's) */+ clock_reset();+}++void p8_menuitem_set(int index, const char *label, int ref) {+ p8_custom_menuitem_t *m = &m_custom_menuitems[index - 1];+ if (m->active && m->lua_callback_ref != LUA_NOREF && L) luaL_unref(L, LUA_REGISTRYINDEX, m->lua_callback_ref);+ m->active = true;+ m->lua_callback_ref = ref;+ p8_menuitem_set_label(index, label);+}++void p8_menuitem_set_label(int index, const char *label) {+ p8_custom_menuitem_t *m = &m_custom_menuitems[index - 1];+ if (!m->active) m->lua_callback_ref = LUA_NOREF;+ m->active = true;+ /* (16 letters, as PICO-8 shows) */+ int n = 0;+ for (; label[n] && n < 16 && n < (int)sizeof m->label - 1; n++) m->label[n] = label[n];+ m->label[n] = 0;+}++void p8_menuitem_clear(int index) {+ p8_custom_menuitem_t *m = &m_custom_menuitems[index - 1];+ if (m->active && m->lua_callback_ref != LUA_NOREF && L) luaL_unref(L, LUA_REGISTRYINDEX, m->lua_callback_ref);+ m->active = false;+ m->lua_callback_ref = LUA_NOREF;+}++void p8_menuitem_reset_all(void) {+ for (int i = 0; i < MAX_CUSTOM_MENUITEMS; i++) m_custom_menuitems[i].active = false, m_custom_menuitems[i].lua_callback_ref = LUA_NOREF;+}++/* ------------------------------------------------------------ the rest of femto8's platform */+#if !defined(HOST)+/* (setjmp's unwind table names the C++ unwinder's first routine; nothing here unwinds) */+void __aeabi_unwind_cpp_pr0(void) {}+#endif++void p8_seed_rng_state(uint32_t seed) {+ uint32_t hi, lo;+ if (seed == 0) {+ hi = 0x60009755;+ lo = 0xdeadbeef;+ } else {+ seed &= 0x7fffffff;+ hi = seed ^ 0xbead29ba;+ lo = seed;+ }+ for (int i = 0; i < 32; i++) {+ hi = (hi << 16) | (hi >> 16);+ hi += lo;+ lo += hi;+ }+ memcpy(m_memory + MEMORY_RNG_STATE, &hi, 4);+ memcpy(m_memory + MEMORY_RNG_STATE + 4, &lo, 4);+}++/* (femto8's p8_reset) */+void p8_reset(void) {+ uint8_t cursor_x = m_memory[MEMORY_CURSOR], cursor_y = m_memory[MEMORY_CURSOR + 1];+ memset(m_memory + MEMORY_DRAWSTATE, 0, MEMORY_DRAWSTATE_SIZE);+ memset(m_memory + MEMORY_HARDWARESTATE, 0, MEMORY_HARDWARESTATE_SIZE);+ m_memory[MEMORY_SCREEN_PHYS] = 0x60;+ m_memory[MEMORY_MAP_START] = 0x20;+ m_memory[MEMORY_MAP_WIDTH] = 128;+ m_memory[MEMORY_RW_MASK] = 0xff;+ pencolor_set(6);+ reset_color();+ clip_set(0, 0, P8_WIDTH, P8_HEIGHT);+ p8_seed_rng_state(plat_random() & 0x7fffffff);+ m_memory[MEMORY_CURSOR] = cursor_x;+ m_memory[MEMORY_CURSOR + 1] = cursor_y;+}++bool p8_open_cartdata(const char *id) {+ if (cartdata_name[0] || !id || !*id) return false;+ char *n = cartdata_name;+ strcpy(n, "p8_");+ int k = 3;+ for (; *id && k < 3 + 32; id++) {+ char c = *id;+ if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a');+ n[k++] = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' ? c : '_';+ }+ strcpy(n + k, ".dat");+ uint32_t len = 0;+ const uint8_t *d = plat_load(n, &len);+ memset(m_memory + MEMORY_CARTDATA, 0, MEMORY_CARTDATA_SIZE);+ if (d) memcpy(m_memory + MEMORY_CARTDATA, d, MIN(len, (uint32_t)MEMORY_CARTDATA_SIZE));+ return true;+}++void p8_delayed_flush_cartdata(void) { cartdata_dirty = true; }++_Noreturn void p8_abort(void) { end_run(PICO_QUIT); }+_Noreturn void p8_restart(void) { end_run(END_RESTART); }+_Noreturn void pico_quit_cart(void) {+ flush_cartdata();+ end_run(PICO_QUIT);+}++_Noreturn void pico_stop_cart(void) {+ strcpy(pico_error.what, "stopped");+ pico_error.msg[0] = 0, pico_error.line = 0;+ flush_cartdata();+ end_run(PICO_ERROR);+}++bool p8_load_cart(const char *name, const char *param) {+ int i = carts_find(pico_carts, pico_ncarts, name);+ if (i < 0) return false;+ strncpy(m_param_string, param ? param : "", sizeof m_param_string - 1);+ breadcrumb = cart;+ pico_next = i;+ flush_cartdata();+ end_run(PICO_LOAD);+}++void pico_breadcrumb(void) {+ if (breadcrumb < 0) return;+ pico_next = breadcrumb;+ m_param_string[0] = 0;+ flush_cartdata();+ end_run(PICO_LOAD);+}++const uint8_t *p8_cart_rom(const char *name) {+ int i = carts_find(pico_carts, pico_ncarts, name);+ return i < 0 ? NULL : pico_carts[i].rom;+}++#ifdef HOST_MALLOC+#include <stdlib.h>+void *pico_lua_alloc(void *ud, void *ptr, size_t osize, size_t nsize) {+ if (!nsize) return free(ptr), NULL;+ return realloc(ptr, nsize);+}+#else+void *pico_lua_alloc(void *ud, void *ptr, size_t osize, size_t nsize) { return heap_alloc(ud, ptr, osize, nsize); }+#endif++/* an error outside any pcall (Lua's panic): out of memory, nearly always */+int pico_panic(lua_State *l) {+ (void)l;+ end_run(PICO_MEMORY);+}++#if !defined(HOST)+/* (Lua's last resort, after a panic that returned: never here, but not the C library's, which needs+ the calculator to have a process to kill) */+void abort(void) { end_run(PICO_MEMORY); }+#endif++/* ------------------------------------------------------------ a cart from start to end */+static int lua_failed(int status) {+ const char *what = NULL;+ pico_error.msg[0] = 0, pico_error.line = 0;+ lua_get_error(&what, pico_error.msg, sizeof pico_error.msg, NULL, &pico_error.line);+ strncpy(pico_error.what, what ? what : "error", sizeof pico_error.what - 1);+ return status == LUA_ERRMEM ? PICO_MEMORY : PICO_ERROR;+}++static int start(void) {+ const p8_cart_t *c = &pico_carts[cart];+ m_cart_memory = c->rom;+ memcpy(ram, c->rom, CART_MEMORY_SIZE);+ memset(ram + CART_MEMORY_SIZE, 0, sizeof ram - CART_MEMORY_SIZE);+ p8_reset();+ m_memory[MEMORY_CURSOR] = m_memory[MEMORY_CURSOR + 1] = 0;+ cartdata_name[0] = 0, cartdata_dirty = false;+ p8_menuitem_reset_all();+ memset(&menu, 0, sizeof menu);+ memset(down_frames, 0, sizeof down_frames);+ memset(first_repeat, 0, sizeof first_repeat);+ m_fps = 30, m_frames = 0;+ keys_now = keys_held = plat_keys();+ m_buttons[0] = m_buttonsp[0] = 0;++ uint8_t *a, *b;+ plat_heap(&a, &b);+ heap_init(a, b);+ if (lua_load_api() != 0) return PICO_MEMORY;+ lua_gc(L, LUA_GCSETPAUSE, 150);+ in_lua = true;+ int st = lua_init_script(NULL, c->code, c->code_len);+ if (!st) st = lua_init();+ in_lua = false;+ if (st) return lua_failed(st);++ if (!lua_has_main_loop_callbacks()) {+ /* (a cart that ran its course in its own loop: its last picture, until a key) */+ p8_render();+ uint32_t held = plat_keys();+ for (;;) {+ uint32_t k = menu_keys(&held);+ if (k & (PK_OK | PK_O | PK_BACK | PK_X | PK_MENU)) return PICO_QUIT;+ plat_sleep(20);+ }+ }++ clock_reset();+ frame_start = plat_millis();+ int skipped = 0;+ for (;;) {+ read_keys();+ in_lua = true;+ st = lua_update();+ in_lua = false;+ if (st) return lua_failed(st);+ /* drawn when on time, else skipped (never more than 3 in a row) */+ uint32_t now = plat_millis(), d = due() + 1000 / clock_fps;+ if ((int32_t)(now - d) <= 0 || skipped >= 3) {+ in_lua = true;+ st = lua_draw();+ in_lua = false;+ if (st) return lua_failed(st);+ p8_render();+ skipped = 0;+ } else {+ skipped++;+ }+ end_frame();+ wait_frame();+ }+}++int pico_run(int index) {+ cart = index;+ pico_next = -1;+ for (;;) {+ int volatile how = setjmp(run_jmp);+ if (how == 0) how = start() + 1;+ in_lua = false;+ menu.on = false;+ flush_cartdata();+ pico_peak = heap_peak();+ lua_shutdown_api();+ how--;+ perf_end = (uint32_t)how + 1;+ if (how != END_RESTART) return how;+ m_param_string[0] = 0;+ }+}diff --git a/games/numpico/src/pico.h b/games/numpico/src/pico.hnew file mode 100644index 00000000..06239e32--- /dev/null+++ b/games/numpico/src/pico.h@@ -0,0 +1,57 @@+/* NumPico's PICO-8: femto8's Lua and API (femto8/) running a cart on the calculator (pico.c), and+ * what the app around it (main.c) sees of it. */+#ifndef NP8_PICO_H+#define NP8_PICO_H+#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>+#include "carts.h"++typedef struct lua_State lua_State;++/* ---- for femto8's code (femto8/p8_lua.c) */+void *pico_lua_alloc(void *ud, void *ptr, size_t osize, size_t nsize);+void pico_hook(lua_State *L); /* every few thousand Lua instructions */+int pico_panic(lua_State *L); /* an error outside a pcall */+void pico_update_buttons(void);+_Noreturn void pico_quit_cart(void); /* extcmd("shutdown") */+_Noreturn void pico_stop_cart(void); /* stop() */+void pico_breadcrumb(void); /* extcmd("breadcrumb"): back to the cart that loaded this one */++/* ---- for the app */+/* the picture: 128 x 128 drawn on 240 x 240 (every 8th row and column of PICO-8's once, the others+ twice), from x = PIC_X; the hints are at its left */+#define PIC_X 80+#define PIC_W 240++enum {+ PICO_QUIT, /* the pause menu's Quit, or the cart ended */+ PICO_HOME, /* Home: leave the app */+ PICO_ERROR, /* pico_error says what */+ PICO_MEMORY, /* the cart needs more memory than the calculator has */+ PICO_LOAD, /* load(): pico_next is the cart to run, with m_param_string */+};+typedef struct {+ char what[24]; /* "syntax error", "runtime error", "stopped" */+ char msg[120];+ int line;+} pico_error_t;+extern pico_error_t pico_error;+extern int pico_next;+extern uint32_t pico_peak; /* the most memory Lua had, in bytes, the last time a cart ran */++extern p8_cart_t pico_carts[P8_MAX_CARTS];+extern int pico_ncarts;++/* runs a cart until it ends (one of PICO_*) */+int pico_run(int index);+/* the cart's frame as it was last drawn, again (behind a screen of the app's) */+void pico_redraw(void);++/* ---- PICO-8's font, for the app's screens */+/* a P8SCII letter's pixel (x 0..7, y 0..5) */+bool pico_glyph_px(uint8_t c, int x, int y);+/* the width of a P8SCII string in PICO-8's pixels (4 a letter, 8 for those from 128) */+int pico_text_w(const char *s);+extern const uint16_t pico_rgb565[32];+#endifdiff --git a/games/numpico/src/plat.h b/games/numpico/src/plat.hnew file mode 100644index 00000000..8fded9f7--- /dev/null+++ b/games/numpico/src/plat.h@@ -0,0 +1,27 @@+/* What NumPico needs from the calculator (plat_eadk.c), or from a computer for the tests (tests/host.c). */+#ifndef NP8_PLAT_H+#define NP8_PLAT_H+#include <stdbool.h>+#include <stdint.h>++enum {+ PK_LEFT = 1 << 0, PK_RIGHT = 1 << 1, PK_UP = 1 << 2, PK_DOWN = 1 << 3,+ PK_O = 1 << 4, /* OK, EXE */+ PK_X = 1 << 5, /* Back, Ans */+ PK_MENU = 1 << 6, /* Backspace */+ PK_HOME = 1 << 7, /* Home, On/Off */+ PK_OK = 1 << 8, /* OK or EXE alone, Back alone: for the menus */+ PK_BACK = 1 << 9,+};+uint32_t plat_keys(void);+uint32_t plat_millis(void);+void plat_sleep(uint32_t ms);+void plat_push(int x, int y, int w, int h, const uint16_t *px);+bool plat_save(const char *name, const void *data, uint32_t len);+const uint8_t *plat_load(const char *name, uint32_t *len);+uint32_t plat_random(void);+/* the RAM after the app's own, for Lua */+void plat_heap(uint8_t **start, uint8_t **end);+void plat_begin(void);+int plat_end(void);+#endifdiff --git a/games/numpico/src/plat_eadk.c b/games/numpico/src/plat_eadk.cnew file mode 100644index 00000000..36e0745d--- /dev/null+++ b/games/numpico/src/plat_eadk.c@@ -0,0 +1,46 @@+/* The calculator: keys, time, the screen, files and RAM (EADK, and NumPlay's careful file helpers). */+#include <eadk.h>+#include "../../common/epsilon_app.h"+#include "../../common/epsilon_files.h"+#include "gfx.h"+#include "plat.h"++const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "NumPico";+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;++#define KEY(k) ((uint64_t)1 << (k))++uint32_t plat_keys(void) {+ uint64_t k = eadk_keyboard_scan();+ uint32_t r = 0;+ if (k & (KEY(eadk_key_left) | KEY(eadk_key_four))) r |= PK_LEFT;+ if (k & (KEY(eadk_key_right) | KEY(eadk_key_six))) r |= PK_RIGHT;+ if (k & (KEY(eadk_key_up) | KEY(eadk_key_eight))) r |= PK_UP;+ if (k & (KEY(eadk_key_down) | KEY(eadk_key_two))) r |= PK_DOWN;+ if (k & (KEY(eadk_key_ok) | KEY(eadk_key_exe))) r |= PK_O | PK_OK;+ if (k & (KEY(eadk_key_back) | KEY(eadk_key_ans))) r |= PK_X;+ if (k & KEY(eadk_key_back)) r |= PK_BACK;+ if (k & KEY(eadk_key_backspace)) r |= PK_MENU;+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= PK_HOME;+ return r;+}+uint32_t plat_millis(void) { return (uint32_t)eadk_timing_millis(); }+void plat_sleep(uint32_t ms) { eadk_timing_msleep(ms); }+void plat_push(int x, int y, int w, int h, const uint16_t *px) {+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, (const eadk_color_t *)px);+}+void np_push(int x, int y, int w, int h, const color_t *px) { plat_push(x, y, w, h, px); }+bool plat_save(const char *name, const void *data, uint32_t len) { return ef_write(name, data, len); }+const uint8_t *plat_load(const char *name, uint32_t *len) { return ef_read(name, len); }+uint32_t plat_random(void) { return eadk_random(); }+void plat_heap(uint8_t **start, uint8_t **end) {+ extern char _heap_start[], _heap_end[];+ *start = (uint8_t *)_heap_start, *end = (uint8_t *)_heap_end;+}+/* nothing takes memory with malloc (Lua has the RAM after the app's: heap.c), but newlib's printf names it */+void *_sbrk(ptrdiff_t incr) {+ (void)incr;+ return (void *)-1;+}+void plat_begin(void) { np_app_begin(); }+int plat_end(void) { return np_app_end(); }diff --git a/games/numpico/tests/host.c b/games/numpico/tests/host.cnew file mode 100644index 00000000..0f966e5e--- /dev/null+++ b/games/numpico/tests/host.c@@ -0,0 +1,153 @@+/* NumPico on a computer, for the tests: the app with its carts from a table file (tools/p8cart.py --bin),+ * the calculator's keys from a seeded random generator, its clock virtual (it moves only when the app+ * waits), its screen a buffer that can be saved as pictures, its files in memory.+ *+ * usage: host TABLE [--frames N] [--seed S] [--heap BYTES] [--keys none|random|menu] [--cart I]+ * [--shots DIR] [--every N]+ * Plays N frames of the cart (the first, or --cart I from the list), then presses Home. Prints how each+ * run of a cart ended: "end <how> <what>: <message>", and Lua's memory at its most. */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include "../src/pico.h"+#include "../src/plat.h"++const uint8_t *np_carts;+uint32_t np_carts_size;+int numpico_main(void);++static uint16_t screen[320 * 240];+static uint32_t now_ms, rng = 1, frames, limit = 600, every = 0, presses;+static int keys_mode = 1, cart_pick = -1, picked;+static const char *shots;+static uint8_t *heap;+static size_t heap_bytes = 1 << 20;+static uint32_t held_keys, hold_left;++static uint32_t rand32(void) {+ rng ^= rng << 13, rng ^= rng >> 17, rng ^= rng << 5;+ return rng;+}++static void shot(void) {+ char path[512];+ snprintf(path, sizeof path, "%s/frame_%05u.ppm", shots, frames);+ FILE *f = fopen(path, "wb");+ if (!f) return;+ fprintf(f, "P6 320 240 255\n");+ for (int i = 0; i < 320 * 240; i++) {+ uint16_t c = screen[i];+ uint8_t rgb[3] = {(uint8_t)((c >> 11) * 255 / 31), (uint8_t)(((c >> 5) & 63) * 255 / 63), (uint8_t)((c & 31) * 255 / 31)};+ fwrite(rgb, 1, 3, f);+ }+ fclose(f);+}++void plat_push(int x, int y, int w, int h, const uint16_t *px) {+ if (x < 0 || y < 0 || w < 0 || h < 0 || x + w > 320 || y + h > 240) {+ fprintf(stderr, "host: rect out of the screen %d,%d %dx%d\n", x, y, w, h);+ abort();+ }+ for (int j = 0; j < h; j++) memcpy(screen + (y + j) * 320 + x, px + j * w, w * 2);+ /* (a frame of the cart: its last row) */+ if (x == PIC_X && y + h == 240) {+ frames++;+ if (shots && every && frames % every == 0) shot();+ }+}++uint32_t plat_keys(void) {+ if (frames >= limit) return PK_HOME;+ /* the list: the cart to play */+ if (cart_pick >= 0 && !picked) {+ static int step;+ step++;+ if (step % 2) return 0;+ static int moved;+ if (moved < cart_pick) return moved++, PK_DOWN;+ picked = 1;+ return PK_OK | PK_O;+ }+ if (keys_mode == 0) return 0;+ if (!hold_left) {+ static const uint32_t pads[] = {PK_LEFT, PK_RIGHT, PK_UP, PK_DOWN, PK_O, PK_X, PK_O | PK_RIGHT, PK_X | PK_LEFT, 0, 0};+ uint32_t r = rand32();+ held_keys = pads[r % 10];+ if (keys_mode == 2 && r % 97 == 0) held_keys = PK_MENU, presses++;+ hold_left = 1 + (r >> 8) % 12;+ }+ hold_left--;+ return held_keys | (held_keys & PK_O ? PK_OK : 0) | (held_keys & PK_X ? PK_BACK : 0);+}++void np_push(int x, int y, int w, int h, const uint16_t *px) { plat_push(x, y, w, h, px); }+void *np_alloc(uint32_t size) { (void)size; return NULL; }+uint32_t plat_millis(void) { return now_ms; }+void plat_sleep(uint32_t ms) { now_ms += ms ? ms : 1; }++static struct {+ char name[64];+ uint8_t data[512];+ uint32_t len;+} files[16];+bool plat_save(const char *name, const void *data, uint32_t len) {+ for (int i = 0; i < 16; i++)+ if (!files[i].name[0] || !strcmp(files[i].name, name)) {+ if (len > sizeof files[i].data) return false;+ snprintf(files[i].name, sizeof files[i].name, "%s", name);+ memcpy(files[i].data, data, len);+ files[i].len = len;+ return true;+ }+ return false;+}+const uint8_t *plat_load(const char *name, uint32_t *len) {+ for (int i = 0; i < 16; i++)+ if (files[i].name[0] && !strcmp(files[i].name, name)) return *len = files[i].len, files[i].data;+ return NULL;+}+uint32_t plat_random(void) { return 12345; }+void plat_heap(uint8_t **start, uint8_t **end) { *start = heap, *end = heap + heap_bytes; }+void plat_begin(void) {}+int plat_end(void) { return 0; }++void host_ended(int how) {+ static const char *const names[] = {"quit", "home", "error", "memory", "load"};+ printf("end %s", names[how]);+ if (how == PICO_ERROR) printf(" %s line %d: %s", pico_error.what, pico_error.line, pico_error.msg);+ printf("\npeak %u bytes, %u frames\n", pico_peak, frames);+ fflush(stdout);+ if (how != PICO_HOME) frames = limit; /* (then Home, from the screen that says so) */+}++int main(int argc, char **argv) {+ if (argc < 2) {+ fprintf(stderr, "usage: host TABLE [--frames N] [--seed S] [--heap BYTES] [--keys none|random|menu] [--cart I] [--shots DIR] [--every N]\n");+ return 2;+ }+ for (int i = 2; i + 1 < argc; i += 2) {+ if (!strcmp(argv[i], "--frames")) limit = (uint32_t)atoi(argv[i + 1]);+ else if (!strcmp(argv[i], "--seed")) rng = (uint32_t)atoi(argv[i + 1]) * 2654435761u + 1;+ else if (!strcmp(argv[i], "--heap")) heap_bytes = (size_t)atol(argv[i + 1]);+ else if (!strcmp(argv[i], "--keys")) keys_mode = !strcmp(argv[i + 1], "none") ? 0 : !strcmp(argv[i + 1], "menu") ? 2 : 1;+ else if (!strcmp(argv[i], "--cart")) cart_pick = atoi(argv[i + 1]);+ else if (!strcmp(argv[i], "--shots")) shots = argv[i + 1];+ else if (!strcmp(argv[i], "--every")) every = (uint32_t)atoi(argv[i + 1]);+ }+ FILE *f = fopen(argv[1], "rb");+ if (!f) return perror(argv[1]), 2;+ fseek(f, 0, SEEK_END);+ long n = ftell(f);+ fseek(f, 0, SEEK_SET);+ uint8_t *t = malloc(n > 0 ? n : 1);+ if (fread(t, 1, n, f) != (size_t)n) return 2;+ fclose(f);+ np_carts = t, np_carts_size = (uint32_t)n;+ heap = malloc(heap_bytes);+ int r = numpico_main();+ if (shots) shot();+ free(heap);+ free(t);+ printf("done %u frames, %u menu presses\n", frames, presses);+ return r;+}diff --git a/games/numpico/tests/perf.py b/games/numpico/tests/perf.pynew file mode 100644index 00000000..d7aab8f8--- /dev/null+++ b/games/numpico/tests/perf.py@@ -0,0 +1,71 @@+#!/usr/bin/env python3+"""Carts on the calculator's CPU (tools/emu.py, an N0110's speed and the RAM of custom 25.2 builds, 133652+bytes): each cart alone in output/perf.nwa (make output/perf.nwa PERF_CART=...), played for a while with+keys held now and then. Prints the pictures shown and the frames run a second, Lua's memory at its most+against what it has, and how the cart ended.++usage: perf.py [--ms N] [--shots DIR] CART|DIR..."""+import argparse+import os+import struct+import subprocess+import sys++HERE = os.path.dirname(os.path.abspath(__file__))+GAME = os.path.join(HERE, "..")+sys.path.insert(0, os.path.join(GAME, "..", "..", "tools"))+import emu # noqa: E402++# OK to start (the first cart starts at once), then a few presses of every button+KEYS = "3000-3200:ok,4000-4600:right,5000-5100:ok,6000-6600:left,7000-7100:back,8000-8400:up,9000-9200:exe," \+ "10000-10800:right,11000-11100:ok,12000-12300:down,13000-13100:back"+++def carts(args):+ for a in args:+ if os.path.isdir(a):+ yield from sorted(os.path.join(a, f) for f in os.listdir(a) if f.lower().endswith((".p8", ".p8.png")))+ else:+ yield a+++def word(c, name):+ return struct.unpack("<I", bytes(c.uc.mem_read(c.symbols[name], 4)))[0] if name in c.symbols else 0+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--ms", type=int, default=15000)+ ap.add_argument("--shots", help="a picture of each cart at the end, here")+ ap.add_argument("--ram", default="133652", help="the RAM apps get (several: each in turn)")+ ap.add_argument("carts", nargs="+")+ a = ap.parse_args()+ nwlink = os.environ.get("NWLINK", "nwlink")+ for ram, cart in ((int(r), c) for c in carts(a.carts) for r in a.ram.split(",")):+ emu.configure("n0110", "epsilon", ram)+ name = os.path.basename(cart)+ r = subprocess.run(["make", "-s", "-C", GAME, "output/perf.nwa", f"PERF_CART={os.path.abspath(cart)}",+ f"NWLINK={nwlink}"], capture_output=True, text=True)+ if r.returncode:+ print(f"{name}: no build: {(r.stdout + r.stderr).strip()[-300:]}")+ continue+ c = emu.Calculator(os.path.join(GAME, "output", "perf.nwa"), None, None, nwlink)+ c.keys = emu.parse_keys(KEYS)+ try:+ c.run(a.ms)+ except RuntimeError as e:+ print(f"{name}: CRASH {e}")+ continue+ secs = max(c.now_ms, 1) / 1000+ frames, updates = word(c, "perf_frames"), word(c, "perf_updates")+ heap, size = word(c, "perf_heap"), word(c, "perf_heap_size")+ end = ["playing", "quit", "home", "error", "OUT OF MEMORY", "load"][min(word(c, "perf_end"), 5)]+ print(f"{name:28s} {frames / secs:5.1f} pictures/s {updates / secs:5.1f} frames/s Lua {heap // 1024:3d} KB "+ f"of {size // 1024} KB {end}", flush=True)+ if a.shots:+ os.makedirs(a.shots, exist_ok=True)+ c.save_png(os.path.join(a.shots, name.split(".")[0] + ".png"))+++if __name__ == "__main__":+ main()diff --git a/games/numpico/tests/test_p8cart.py b/games/numpico/tests/test_p8cart.pynew file mode 100644index 00000000..3fee661a--- /dev/null+++ b/games/numpico/tests/test_p8cart.py@@ -0,0 +1,49 @@+#!/usr/bin/env python3+"""tools/p8cart.py: the same cart as .p8 and .p8.png reads the same (femto8's carts come both ways: the+ROM byte for byte; the code too, but for a few letters, in the pairs PICO-8 saved from the same version),+and the table holds together as src/carts.h says.++usage: test_p8cart.py DIR (the .p8 and .p8.png pairs: femto8's carts/)"""+import difflib+import os+import struct+import sys++sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools"))+import p8cart # noqa: E402+++def main():+ d = sys.argv[1] if len(sys.argv) > 1 else os.path.expanduser("~/Documents/Assets/gamesrc/numpico/femto8/carts")+ pairs = codes = 0+ for f in sorted(os.listdir(d)):+ if not f.endswith(".p8.png") or not os.path.exists(os.path.join(d, f[:-4])):+ continue+ rom_png, code_png, label_png = p8cart.read_cart(os.path.join(d, f))+ rom_p8, code_p8, label_p8 = p8cart.read_cart(os.path.join(d, f[:-4]))+ assert rom_png == rom_p8, f"{f}: the ROMs differ at {next(i for i in range(len(rom_p8)) if rom_png[i] != rom_p8[i]):#x}"+ a, b = code_png.replace(b"\r", b"").strip(), code_p8.replace(b"\r", b"").strip()+ if difflib.SequenceMatcher(None, a, b, autojunk=False).ratio() > 0.995:+ codes += 1+ if label_p8:+ same = sum(1 for x, y in zip(label_png, label_p8) if x == y)+ assert same > 0.99 * len(label_p8), f"{f}: the labels differ ({same} pixels the same)"+ pairs += 1+ assert pairs >= 8 and codes >= 6, f"{pairs} carts, {codes} with the same code"+ # the table+ carts = [(b"a", bytes(range(256)) * 67, b"print(1)", None), (p8cart.cart_name("été.p8.png"), bytes(0x4300), b"x", [3] * 16384)]+ t = p8cart.table(carts)+ magic, version, count = struct.unpack_from("<III", t)+ assert (magic, version, count) == (0x3850504E, 1, 2) and len(t) % 4 == 0+ rom, code, n, label, name = struct.unpack_from("<IIII48s", t, 12)+ assert rom == 12 + 64 * 2 and code == rom + 0x4300 and n == 8 and label == 0 and name.rstrip(b"\0") == b"a"+ assert t[code:code + n] == b"print(1)"+ rom, code, n, label, name = struct.unpack_from("<IIII48s", t, 12 + 64)+ assert rom % 4 == 0 and label % 4 == 0 and label > code and name.rstrip(b"\0") == "été".encode()+ assert t[label] == 3 and t[label + 16] == 0+ print(f"test_p8cart: {pairs} carts the same as .p8 and .p8.png ({codes} with the same code), the table as "+ "src/carts.h says")+++if __name__ == "__main__":+ main()diff --git a/games/numpico/tools/p8cart.py b/games/numpico/tools/p8cart.pynew file mode 100644index 00000000..942760f8--- /dev/null+++ b/games/numpico/tools/p8cart.py@@ -0,0 +1,493 @@+#!/usr/bin/env python3+"""Makes NumPico's table of carts, np_carts, from PICO-8 carts (.p8 and .p8.png), as an object file to+link into NumPico.nwa. NumPlay Studio makes the same table in the browser (customize/app.js).++A cart becomes its 0x4300 bytes of ROM (sprites, map, flags, music, sound), its Lua code (unpacked,+in P8SCII, the bytes PICO-8 runs) and its label (16 colours, then 128 x 128 pixels of 4 bits). The+table's layout is in src/carts.h. To be the same byte for byte as the website's for the same files:+- the carts come in the order given; their parts in the order ROM, code, label, each starting+ 4-byte aligned after the one before (zeros in between), the first at 12 + 64 * count;+- the table ends with the last part, then zeros up to a multiple of 4;+- a cart's name is its file's without .p8.png or .p8 (in any case), its UTF-8 cut to the longest+ start of at most 48 bytes ending on a whole letter, zero-padded;+- the label: the 16 colours it uses most (ties: the lower colour first), in that order; a pixel of+ another colour takes the closest of those (the sum of squared differences of PICO-8's RGB; ties:+ the first). No label (a .p8 without __label__): 0.++Reading the carts: a .p8.png's pixels hold a byte each (the low 2 bits of alpha, red, green, blue);+its code is plain, or packed in PICO-8's old ":c:" format or its "pxa" one (0.2.0), unpacked with+Lexaloffle's algorithms (p8_compress.c, zlib licence; pxa_compress_snippets.c, MIT licence). A .p8 is+text: its code's UTF-8 symbols become P8SCII, its __gfx__, __gff__, __map__, __sfx__ and __music__+become memory as femto8's parser does (MIT licence).++usage:+ p8cart.py -o carts.o [CART...] an ARM object for the calculator+ p8cart.py -o carts.o --list FILE the carts named in FILE, one a line+ p8cart.py --c carts.c [CART...] the same table as C, for the tests+ p8cart.py --bin carts.bin [CART...]"""+import argparse+import os+import struct+import sys+import zlib++MAGIC, VERSION, ENTRY, NAME = 0x3850504E, 1, 64, 48+ROM = 0x4300++# P8SCII as .p8 files write it (from femto8's table)+P8SCII = {1: "\u00b9", 2: "\u00b2", 3: "\u00b3", 4: "\u2074", 5: "\u2075", 6: "\u2076", 7: "\u2077", 8: "\u2078",+ 11: "\u1d47", 12: "\u1d9c", 14: "\u1d49", 15: "\u1da0", 16: "\u25ae", 17: "\u25a0", 18: "\u25a1",+ 19: "\u2059", 20: "\u2058", 21: "\u2016", 22: "\u25c0", 23: "\u25b6", 24: "\u300c", 25: "\u300d",+ 26: "\u00a5", 27: "\u2022", 28: "\u3001", 29: "\u3002", 30: "\u309b", 31: "\u309c", 127: "\u25cb",+ 128: "\u2588", 129: "\u2592", 130: "\U0001f431", 131: "\u2b07\ufe0f", 132: "\u2591", 133: "\u273d",+ 134: "\u25cf", 135: "\u2665", 136: "\u2609", 137: "\uc6c3", 138: "\u2302", 139: "\u2b05\ufe0f",+ 140: "\U0001f610", 141: "\u266a", 142: "\U0001f17e\ufe0f", 143: "\u25c6", 144: "\u2026",+ 145: "\u27a1\ufe0f", 146: "\u2605", 147: "\u29d7", 148: "\u2b06\ufe0f", 149: "\u02c7", 150: "\u2227",+ 151: "\u274e", 152: "\u25a4", 153: "\u25a5"}+for _i, _c in enumerate("あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわをん"+ "っゃゅょアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン"+ "ッャュョ◜◝"):+ P8SCII[154 + _i] = _c+SYMBOLS = sorted(((v.encode("utf-8"), k) for k, v in P8SCII.items()), key=lambda x: -len(x[0]))++# PICO-8's 32 colours (RGB), for labels+COLORS = [(0, 0, 0), (29, 43, 83), (126, 37, 83), (0, 135, 81), (171, 82, 54), (95, 87, 79), (194, 195, 199),+ (255, 241, 232), (255, 0, 77), (255, 163, 0), (255, 236, 39), (0, 228, 54), (41, 173, 255), (131, 118, 156),+ (255, 119, 168), (255, 204, 170), (41, 24, 20), (17, 29, 53), (66, 33, 54), (18, 83, 89), (116, 47, 41),+ (73, 51, 59), (162, 136, 121), (243, 239, 125), (190, 18, 80), (255, 108, 36), (168, 231, 46), (0, 181, 67),+ (6, 90, 181), (117, 70, 101), (255, 110, 89), (255, 157, 129)]+++class CartError(Exception):+ pass+++def utf8_len(data, i):+ """the length of the UTF-8 letter at i, or 0 when it isn't one"""+ c = data[i]+ n = 2 if c & 0xE0 == 0xC0 else 3 if c & 0xF0 == 0xE0 else 4 if c & 0xF8 == 0xF0 else 0+ if not n or i + n > len(data) or any(b & 0xC0 != 0x80 for b in data[i + 1:i + n]):+ return 0+ return n+++def to_p8scii(data):+ """the code of a .p8 to P8SCII: its UTF-8 symbols to their letters; other UTF-8 letters are left out+ (PICO-8 has none), and bytes that aren't UTF-8 kept (old carts wrote P8SCII as it is)"""+ out = bytearray()+ i = 0+ while i < len(data):+ c = data[i]+ if c < 0x80:+ out.append(c)+ i += 1+ continue+ for s, k in SYMBOLS:+ if data.startswith(s, i):+ out.append(k)+ i += len(s)+ break+ else:+ n = utf8_len(data, i)+ if n:+ i += n+ else:+ out.append(c)+ i += 1+ return bytes(out)+++# ------------------------------------------------------------------ .p8+def hexbytes(line):+ h = [c for c in line if c in "0123456789abcdefABCDEF"]+ return bytes(int(h[k] + h[k + 1], 16) for k in range(0, len(h) - 1, 2))+++def parse_p8(data):+ raw = data.split(b"\n")+ lines = [r.decode("latin-1") for r in raw]+ if not lines or not lines[0].startswith("pico-8 cartridge"):+ raise CartError("not a PICO-8 cart")+ rom = bytearray(ROM)+ code, label = [], None+ section, n = None, 0+ music = 0+ for li, line in enumerate(lines[1:], 1):+ tag = line.rstrip("\r")+ if tag in ("__lua__", "__gfx__", "__gff__", "__label__", "__map__", "__sfx__", "__music__", "__gfx8__",+ "__meta__", "__change_mask__") or (tag.startswith("__") and tag.endswith("__") and len(tag) > 4+ and section != "__lua__"):+ section, n = tag, 0+ if tag == "__label__":+ label = [0] * (128 * 128)+ continue+ if section is None:+ continue+ if section == "__lua__":+ code.append(raw[li])+ elif section == "__gfx__":+ b = hexbytes(tag)+ at = n * 64+ for k, v in enumerate(b[:64]):+ if at + k < 0x2000:+ rom[at + k] = ((v << 4) | (v >> 4)) & 0xFF+ if b:+ n += 1+ elif section == "__gff__":+ b = hexbytes(tag)+ at = 0x3000 + n * 128+ for k, v in enumerate(b[:128]):+ if at + k < 0x3100:+ rom[at + k] = v+ if b:+ n += 1+ elif section == "__map__":+ b = hexbytes(tag)+ at = 0x2000 + n * 128+ for k, v in enumerate(b[:128]):+ if at + k < 0x3000:+ rom[at + k] = v+ if b:+ n += 1+ elif section == "__sfx__":+ b = hexbytes(tag)+ if len(b) >= 84 and n < 64:+ at = 0x3200 + n * 68+ rom[at:at + 68] = sfx_bytes(b)+ n += 1+ elif section == "__music__":+ b = hexbytes(tag)+ if len(b) >= 5 and n < 64:+ flags = b[0]+ at = 0x3100 + n * 4+ for k in range(4):+ rom[at + k] = (b[1 + k] & 0x7F) | (0x80 if flags & (1 << k) else 0)+ n += 1+ music = n+ elif section == "__label__" and label is not None:+ row = [c for c in tag if c in "0123456789abcdefghijklmnopqrstuv"]+ if row and n < 128:+ for x, c in enumerate(row[:128]):+ label[n * 128 + x] = "0123456789abcdefghijklmnopqrstuv".index(c)+ n += 1+ for at in range(0x3100 + music * 4, 0x3200, 4): # (missing patterns: PICO-8's empty ones)+ rom[at:at + 4] = b"\x41\x42\x43\x44"+ return bytes(rom), to_p8scii(b"\n".join(code)), label+++def sfx_bytes(b):+ """a __sfx__ line (84 bytes) as memory (68): 32 notes of 16 bits, then editor mode, speed, loop start, end"""+ out = bytearray()+ for i in range(0, 32, 2):+ a, bb, c, d, e = b[4 + i * 5 // 2:4 + i * 5 // 2 + 5]+ n1 = (a, bb >> 4, bb & 15, c >> 4) # pitch, waveform, volume, effect+ n2 = (((c << 4) | (d >> 4)) & 0xFF, d & 15, e >> 4, e & 15)+ for pitch, wave, vol, fx in (n1, n2):+ v = (0x8000 if wave > 7 else 0) | (fx << 12) | (vol << 9) | ((wave & 7) << 6) | (pitch & 63)+ out += struct.pack("<H", v)+ out += bytes(b[0:4])+ return bytes(out)+++# ------------------------------------------------------------------ .p8.png+def png_rgba(data):+ """the pixels of an 8-bit RGBA (or RGB) PNG, without interlacing: (width, height, bytes RGBA)"""+ if data[:8] != b"\x89PNG\r\n\x1a\n":+ raise CartError("not a PNG")+ at, idat, w = 8, bytearray(), None+ while at + 8 <= len(data):+ n, kind = struct.unpack(">I4s", data[at:at + 8])+ body = data[at + 8:at + 8 + n]+ if kind == b"IHDR":+ w, h, depth, ctype, _, _, interlace = struct.unpack(">IIBBBBB", body[:13])+ if depth != 8 or ctype not in (2, 6) or interlace:+ raise CartError("a PNG PICO-8 didn't make")+ elif kind == b"IDAT":+ idat += body+ elif kind == b"IEND":+ break+ at += 12 + n+ if w is None:+ raise CartError("not a PNG")+ bpp = 4 if ctype == 6 else 3+ raw = zlib.decompress(bytes(idat))+ stride = w * bpp+ out = bytearray(w * h * 4)+ prev = bytearray(stride)+ for y in range(h):+ f = raw[y * (stride + 1)]+ line = bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])+ for x in range(stride):+ a = line[x - bpp] if x >= bpp else 0+ b = prev[x]+ c = prev[x - bpp] if x >= bpp else 0+ if f == 1:+ line[x] = (line[x] + a) & 0xFF+ elif f == 2:+ line[x] = (line[x] + b) & 0xFF+ elif f == 3:+ line[x] = (line[x] + ((a + b) >> 1)) & 0xFF+ elif f == 4:+ p = a + b - c+ pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)+ line[x] = (line[x] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 0xFF+ for x in range(w):+ px = line[x * bpp:x * bpp + bpp]+ out[(y * w + x) * 4:(y * w + x) * 4 + 4] = px if bpp == 4 else px + b"\xff"+ prev = line+ return w, h, bytes(out)+++LITERALS = b"^\n 0123456789abcdefghijklmnopqrstuvwxyz!#%(){}[]<>+=/*:;.,~_"+FUTURE = (b"if(_update60)_update=function()_update60()_update60()end",+ b"if(_update60)_update=function()_update60()_update_buttons()_update60()end")+++def unpack_old(d):+ """PICO-8's first packing (":c:"): Lexaloffle's decompress_mini"""+ n = d[4] * 256 + d[5]+ out = bytearray()+ at = 8+ while len(out) < n and at < len(d):+ v = d[at]+ at += 1+ if v < len(LITERALS):+ if v == 0:+ out.append(d[at])+ at += 1+ else:+ out.append(LITERALS[v])+ else:+ off = (v - len(LITERALS)) * 16 + d[at] % 16+ ln = d[at] // 16 + 2+ at += 1+ for _ in range(ln):+ out.append(out[-off] if 0 < off <= len(out) else 0)+ out = bytes(out[:n]).split(b"\0")[0]+ for f in FUTURE:+ if out.endswith(f):+ out = out[:-len(f)]+ return out+++def unpack_pxa(d):+ """PICO-8's 0.2.0 packing ("pxa"): Lexaloffle's pxa_decompress"""+ raw_len, comp_len = d[4] * 256 + d[5], d[6] * 256 + d[7]+ st = {"pos": 8, "bit": 1}++ def bit():+ r = 1 if st["pos"] < len(d) and d[st["pos"]] & st["bit"] else 0+ st["bit"] <<= 1+ if st["bit"] == 256:+ st["bit"] = 1+ st["pos"] += 1+ return r++ def val(bits):+ v = 0+ for i in range(bits):+ if bit():+ v |= 1 << i+ return v++ def chain(link, most):+ top, v, read, vv = (1 << link) - 1, 0, 0, (1 << link) - 1+ while vv == top:+ vv = val(link)+ read += link+ v += vv+ if read >= most:+ return v+ return v++ lit = list(range(256))+ out = bytearray()+ while st["pos"] < comp_len and len(out) < raw_len:+ if bit() == 0:+ bits = (3 - chain(1, 2)) * 5+ num = val(bits)+ off = -1 if num == 0 and bits == 10 else num+ off += 1+ if off == 0:+ while len(out) < raw_len:+ c = val(8)+ if c == 0:+ break+ out.append(c)+ else:+ ln = chain(3, 100000) + 3+ for _ in range(ln):+ out.append(out[-off] if off <= len(out) else 0)+ else:+ lpos, bits = 0, 0+ safety = 0+ while bit() == 1 and safety < 16:+ safety += 1+ lpos += 1 << (4 + bits)+ bits += 1+ lpos += val(bits + 4)+ if lpos > 255:+ raise CartError("damaged code")+ c = lit[lpos]+ out.append(c)+ del lit[lpos]+ lit.insert(0, c)+ return bytes(out[:raw_len]).split(b"\0")[0]+++def parse_png(data):+ w, h, px = png_rgba(data)+ if (w, h) != (160, 205):+ raise CartError("a PNG that isn't a PICO-8 cart (160 x 205)")+ b = bytes(((px[i + 3] & 3) << 6) | ((px[i] & 3) << 4) | ((px[i + 1] & 3) << 2) | (px[i + 2] & 3)+ for i in range(0, len(px), 4))+ rom = b[:ROM]+ c = b[ROM:0x8000]+ if c[:4] == b":c:\0":+ code = unpack_old(c)+ elif c[:4] == b"\0pxa":+ code = unpack_pxa(c)+ else:+ code = c.split(b"\0")[0]+ # the label: each pixel the colour it is (the low 2 bits held data), else the closest+ exact = {(r & 0xFC, g & 0xFC, bb & 0xFC): k for k, (r, g, bb) in reversed(list(enumerate(COLORS)))}+ label = []+ for y in range(128):+ for x in range(128):+ i = ((24 + y) * 160 + 16 + x) * 4+ rgb = (px[i] & 0xFC, px[i + 1] & 0xFC, px[i + 2] & 0xFC)+ if rgb not in exact:+ exact[rgb] = min(range(32), key=lambda k: (sum((COLORS[k][j] - rgb[j]) ** 2 for j in range(3)), k))+ label.append(exact[rgb])+ return rom, code, label+++# ------------------------------------------------------------------ the table+def label_bytes(label):+ use = [0] * 32+ for c in label:+ use[c] += 1+ keep = sorted(range(32), key=lambda c: (-use[c], c))[:16]+ keep = [c for c in keep if use[c]] or [0]+ keep += [0] * (16 - len(keep))+ near = {}+ for c in range(32):+ if c in keep:+ near[c] = keep.index(c)+ else:+ near[c] = min(range(16), key=lambda k: (sum((COLORS[c][j] - COLORS[keep[k]][j]) ** 2 for j in range(3)), k))+ out = bytearray(bytes((c & 15) | (0x80 if c >= 16 else 0) for c in keep))+ for i in range(0, 128 * 128, 2):+ out.append(near[label[i]] | near[label[i + 1]] << 4)+ return bytes(out)+++def cart_name(path):+ base = os.path.basename(path)+ for ext in (".p8.png", ".p8"):+ if base.lower().endswith(ext):+ base = base[:-len(ext)]+ break+ name = base.encode("utf-8")+ k = min(len(name), NAME)+ while 0 < k < len(name) and (name[k] & 0xC0) == 0x80:+ k -= 1+ return name[:k]+++def read_cart(path):+ data = open(path, "rb").read()+ rom, code, label = parse_png(data) if data[:8] == b"\x89PNG\r\n\x1a\n" else parse_p8(data)+ return rom, code, label+++def table(carts):+ """carts: (name bytes, rom, code, label or None)"""+ out = bytearray(struct.pack("<III", MAGIC, VERSION, len(carts)))+ out += bytes(ENTRY * len(carts))+ for i, (name, rom, code, label) in enumerate(carts):+ offs = []+ for part in (rom, code, label_bytes(label) if label else None):+ if part is None:+ offs.append(0)+ continue+ out += bytes(-len(out) % 4)+ offs.append(len(out))+ out += part+ struct.pack_into("<IIII48s", out, 12 + ENTRY * i, offs[0], offs[1], len(code), offs[2], name.ljust(NAME, b"\0"))+ out += bytes(-len(out) % 4)+ return bytes(out)+++def elf_object(blob):+ """A 32-bit ARM relocatable object: .rodata.np_carts, and np_carts in its symbol table."""+ shstr = b"\0.rodata.np_carts\0.symtab\0.strtab\0.shstrtab\0"+ strtab = b"\0np_carts\0"+ STB_GLOBAL, STT_OBJECT, STT_SECTION = 1, 1, 3+ symtab = struct.pack("<IIIBBH", 0, 0, 0, 0, 0, 0)+ symtab += struct.pack("<IIIBBH", 0, 0, 0, STT_SECTION, 0, 1)+ symtab += struct.pack("<IIIBBH", 1, 0, len(blob), STB_GLOBAL << 4 | STT_OBJECT, 0, 1)+ out = bytearray(52)+ offs = []+ for part in (blob, symtab, strtab, shstr):+ out += bytes(-len(out) % 4)+ offs.append(len(out))+ out += part+ out += bytes(-len(out) % 4)+ shoff = len(out)+ SHT_PROGBITS, SHT_SYMTAB, SHT_STRTAB, SHF_ALLOC = 1, 2, 3, 2+ sections = [+ (0, 0, 0, 0, 0, 0, 0, 0, 0, 0),+ (shstr.index(b".rodata.np_carts"), SHT_PROGBITS, SHF_ALLOC, 0, offs[0], len(blob), 0, 0, 4, 0),+ (shstr.index(b".symtab"), SHT_SYMTAB, 0, 0, offs[1], len(symtab), 3, 2, 4, 16),+ (shstr.index(b".strtab"), SHT_STRTAB, 0, 0, offs[2], len(strtab), 0, 0, 1, 0),+ (shstr.index(b".shstrtab"), SHT_STRTAB, 0, 0, offs[3], len(shstr), 0, 0, 1, 0),+ ]+ for s in sections:+ out += struct.pack("<10I", *s)+ ident = b"\x7fELF\x01\x01\x01" + bytes(9)+ struct.pack_into("<16sHHIIIIIHHHHHH", out, 0, ident, 1, 40, 1, 0, 0, shoff, 0, 52, 0, 0, 40, len(sections), 4)+ return bytes(out)+++def c_source(blob):+ lines = [",".join(str(b) for b in blob[k:k + 32]) for k in range(0, len(blob), 32)]+ return ("/* Made by tools/p8cart.py: NumPico's table of carts (see that file). */\n#include <stdint.h>\n"+ f"static const uint8_t carts[{max(len(blob), 1)}] __attribute__((aligned(4))) = {{\n" ++ ",\n".join(lines) + "\n};\n"+ "const uint8_t *np_carts = carts;\n"+ f"uint32_t np_carts_size = {len(blob)};\n")+++def main():+ ap = argparse.ArgumentParser(description="NumPico's table of carts (np_carts)")+ ap.add_argument("-o", dest="obj", help="ARM object to write")+ ap.add_argument("--c", dest="csrc", help="C source to write")+ ap.add_argument("--bin", dest="bin", help="raw table to write")+ ap.add_argument("--list", help="a file naming more carts, one a line")+ ap.add_argument("carts", nargs="*")+ a = ap.parse_args()+ if not (a.obj or a.csrc or a.bin):+ ap.error("say where: -o, --c or --bin")+ if a.list:+ a.carts += [line.strip() for line in open(a.list, encoding="utf-8") if line.strip()]+ carts = []+ for p in a.carts:+ try:+ rom, code, label = read_cart(p)+ except (CartError, zlib.error, IndexError, ValueError) as e:+ sys.exit(f"p8cart: {p}: {e}")+ carts.append((cart_name(p), rom, code, label))+ blob = table(carts)+ for path, data in ((a.obj, lambda: elf_object(blob)), (a.csrc, lambda: c_source(blob).encode()),+ (a.bin, lambda: blob)):+ if not path:+ continue+ data = data()+ if not os.path.exists(path) or open(path, "rb").read() != data:+ open(path, "wb").write(data)+ print(f"CARTS {path}: {len(carts)} carts, {len(blob)} bytes")+++if __name__ == "__main__":+ main()