potatOS/copy-cat/resources-e74d4ac3.js
2023-11-12 14:57:16 +00:00

13 lines
829 KiB
JavaScript

/**
* copy-cat: Copyright SquidDev 2023
*
* - @squid-dev/cc-web-term: Copyright SquidDev (BSD-3-Clause)
* - jszip: Copyright Stuart Knightley ((MIT OR GPL-3.0-or-later))
* - preact: Copyright (MIT)
* - setimmediate: Copyright YuzuJS (MIT)
* - style-inject: Copyright EGOIST (MIT)
* - tslib: Copyright Microsoft Corp. (0BSD)
*
* @license
*/define(["exports"],function(e){"use strict";e.resources={"bios.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n-- Load in expect from the module path.\n--\n-- Ideally we\'d use require, but that is part of the shell, and so is not\n-- available to the BIOS or any APIs. All APIs load this using dofile, but that\n-- has not been defined at this point.\nlocal expect\n\ndo\n local h = fs.open("rom/modules/main/cc/expect.lua", "r")\n local f, err = loadstring(h.readAll(), "@/rom/modules/main/cc/expect.lua")\n h.close()\n\n if not f then error(err) end\n expect = f().expect\nend\n\nif _VERSION == "Lua 5.1" then\n -- If we\'re on Lua 5.1, install parts of the Lua 5.2/5.3 API so that programs can be written against it\n local nativeload = load\n\n function load(x, name, mode, env)\n expect(1, x, "function", "string")\n expect(2, name, "string", "nil")\n expect(3, mode, "string", "nil")\n expect(4, env, "table", "nil")\n\n local ok, p1, p2 = pcall(function()\n local result, err = nativeload(x, name, mode, env)\n if result and env then\n env._ENV = env\n end\n return result, err\n end)\n if ok then\n return p1, p2\n else\n error(p1, 2)\n end\n end\n\n loadstring = function(string, chunkname) return nativeload(string, chunkname) end\nend\n\n-- Inject a stub for the old bit library\n_G.bit = {\n bnot = bit32.bnot,\n band = bit32.band,\n bor = bit32.bor,\n bxor = bit32.bxor,\n brshift = bit32.arshift,\n blshift = bit32.lshift,\n blogic_rshift = bit32.rshift,\n}\n\n-- Install lua parts of the os api\nfunction os.version()\n return "CraftOS 1.8"\nend\n\nfunction os.pullEventRaw(sFilter)\n return coroutine.yield(sFilter)\nend\n\nfunction os.pullEvent(sFilter)\n local eventData = table.pack(os.pullEventRaw(sFilter))\n if eventData[1] == "terminate" then\n error("Terminated", 0)\n end\n return table.unpack(eventData, 1, eventData.n)\nend\n\n-- Install globals\nfunction sleep(nTime)\n expect(1, nTime, "number", "nil")\n local timer = os.startTimer(nTime or 0)\n repeat\n local _, param = os.pullEvent("timer")\n until param == timer\nend\n\nfunction write(sText)\n expect(1, sText, "string", "number")\n\n local w, h = term.getSize()\n local x, y = term.getCursorPos()\n\n local nLinesPrinted = 0\n local function newLine()\n if y + 1 <= h then\n term.setCursorPos(1, y + 1)\n else\n term.setCursorPos(1, h)\n term.scroll(1)\n end\n x, y = term.getCursorPos()\n nLinesPrinted = nLinesPrinted + 1\n end\n\n -- Print the line with proper word wrapping\n sText = tostring(sText)\n while #sText > 0 do\n local whitespace = string.match(sText, "^[ \\t]+")\n if whitespace then\n -- Print whitespace\n term.write(whitespace)\n x, y = term.getCursorPos()\n sText = string.sub(sText, #whitespace + 1)\n end\n\n local newline = string.match(sText, "^\\n")\n if newline then\n -- Print newlines\n newLine()\n sText = string.sub(sText, 2)\n end\n\n local text = string.match(sText, "^[^ \\t\\n]+")\n if text then\n sText = string.sub(sText, #text + 1)\n if #text > w then\n -- Print a multiline word\n while #text > 0 do\n if x > w then\n newLine()\n end\n term.write(text)\n text = string.sub(text, w - x + 2)\n x, y = term.getCursorPos()\n end\n else\n -- Print a word normally\n if x + #text - 1 > w then\n newLine()\n end\n term.write(text)\n x, y = term.getCursorPos()\n end\n end\n end\n\n return nLinesPrinted\nend\n\nfunction print(...)\n local nLinesPrinted = 0\n local nLimit = select("#", ...)\n for n = 1, nLimit do\n local s = tostring(select(n, ...))\n if n < nLimit then\n s = s .. "\\t"\n end\n nLinesPrinted = nLinesPrinted + write(s)\n end\n nLinesPrinted = nLinesPrinted + write("\\n")\n return nLinesPrinted\nend\n\nfunction printError(...)\n local oldColour\n if term.isColour() then\n oldColour = term.getTextColour()\n term.setTextColour(colors.red)\n end\n print(...)\n if term.isColour() then\n term.setTextColour(oldColour)\n end\nend\n\nfunction read(_sReplaceChar, _tHistory, _fnComplete, _sDefault)\n expect(1, _sReplaceChar, "string", "nil")\n expect(2, _tHistory, "table", "nil")\n expect(3, _fnComplete, "function", "nil")\n expect(4, _sDefault, "string", "nil")\n\n term.setCursorBlink(true)\n\n local sLine\n if type(_sDefault) == "string" then\n sLine = _sDefault\n else\n sLine = ""\n end\n local nHistoryPos\n local nPos, nScroll = #sLine, 0\n if _sReplaceChar then\n _sReplaceChar = string.sub(_sReplaceChar, 1, 1)\n end\n\n local tCompletions\n local nCompletion\n local function recomplete()\n if _fnComplete and nPos == #sLine then\n tCompletions = _fnComplete(sLine)\n if tCompletions and #tCompletions > 0 then\n nCompletion = 1\n else\n nCompletion = nil\n end\n else\n tCompletions = nil\n nCompletion = nil\n end\n end\n\n local function uncomplete()\n tCompletions = nil\n nCompletion = nil\n end\n\n local w = term.getSize()\n local sx = term.getCursorPos()\n\n local function redraw(_bClear)\n local cursor_pos = nPos - nScroll\n if sx + cursor_pos >= w then\n -- We\'ve moved beyond the RHS, ensure we\'re on the edge.\n nScroll = sx + nPos - w\n elseif cursor_pos < 0 then\n -- We\'ve moved beyond the LHS, ensure we\'re on the edge.\n nScroll = nPos\n end\n\n local _, cy = term.getCursorPos()\n term.setCursorPos(sx, cy)\n local sReplace = _bClear and " " or _sReplaceChar\n if sReplace then\n term.write(string.rep(sReplace, math.max(#sLine - nScroll, 0)))\n else\n term.write(string.sub(sLine, nScroll + 1))\n end\n\n if nCompletion then\n local sCompletion = tCompletions[nCompletion]\n local oldText, oldBg\n if not _bClear then\n oldText = term.getTextColor()\n oldBg = term.getBackgroundColor()\n term.setTextColor(colors.white)\n term.setBackgroundColor(colors.gray)\n end\n if sReplace then\n term.write(string.rep(sReplace, #sCompletion))\n else\n term.write(sCompletion)\n end\n if not _bClear then\n term.setTextColor(oldText)\n term.setBackgroundColor(oldBg)\n end\n end\n\n term.setCursorPos(sx + nPos - nScroll, cy)\n end\n\n local function clear()\n redraw(true)\n end\n\n recomplete()\n redraw()\n\n local function acceptCompletion()\n if nCompletion then\n -- Clear\n clear()\n\n -- Find the common prefix of all the other suggestions which start with the same letter as the current one\n local sCompletion = tCompletions[nCompletion]\n sLine = sLine .. sCompletion\n nPos = #sLine\n\n -- Redraw\n recomplete()\n redraw()\n end\n end\n while true do\n local sEvent, param, param1, param2 = os.pullEvent()\n if sEvent == "char" then\n -- Typed key\n clear()\n sLine = string.sub(sLine, 1, nPos) .. param .. string.sub(sLine, nPos + 1)\n nPos = nPos + 1\n recomplete()\n redraw()\n\n elseif sEvent == "paste" then\n -- Pasted text\n clear()\n sLine = string.sub(sLine, 1, nPos) .. param .. string.sub(sLine, nPos + 1)\n nPos = nPos + #param\n recomplete()\n redraw()\n\n elseif sEvent == "key" then\n if param == keys.enter or param == keys.numPadEnter then\n -- Enter/Numpad Enter\n if nCompletion then\n clear()\n uncomplete()\n redraw()\n end\n break\n\n elseif param == keys.left then\n -- Left\n if nPos > 0 then\n clear()\n nPos = nPos - 1\n recomplete()\n redraw()\n end\n\n elseif param == keys.right then\n -- Right\n if nPos < #sLine then\n -- Move right\n clear()\n nPos = nPos + 1\n recomplete()\n redraw()\n else\n -- Accept autocomplete\n acceptCompletion()\n end\n\n elseif param == keys.up or param == keys.down then\n -- Up or down\n if nCompletion then\n -- Cycle completions\n clear()\n if param == keys.up then\n nCompletion = nCompletion - 1\n if nCompletion < 1 then\n nCompletion = #tCompletions\n end\n elseif param == keys.down then\n nCompletion = nCompletion + 1\n if nCompletion > #tCompletions then\n nCompletion = 1\n end\n end\n redraw()\n\n elseif _tHistory then\n -- Cycle history\n clear()\n if param == keys.up then\n -- Up\n if nHistoryPos == nil then\n if #_tHistory > 0 then\n nHistoryPos = #_tHistory\n end\n elseif nHistoryPos > 1 then\n nHistoryPos = nHistoryPos - 1\n end\n else\n -- Down\n if nHistoryPos == #_tHistory then\n nHistoryPos = nil\n elseif nHistoryPos ~= nil then\n nHistoryPos = nHistoryPos + 1\n end\n end\n if nHistoryPos then\n sLine = _tHistory[nHistoryPos]\n nPos, nScroll = #sLine, 0\n else\n sLine = ""\n nPos, nScroll = 0, 0\n end\n uncomplete()\n redraw()\n\n end\n\n elseif param == keys.backspace then\n -- Backspace\n if nPos > 0 then\n clear()\n sLine = string.sub(sLine, 1, nPos - 1) .. string.sub(sLine, nPos + 1)\n nPos = nPos - 1\n if nScroll > 0 then nScroll = nScroll - 1 end\n recomplete()\n redraw()\n end\n\n elseif param == keys.home then\n -- Home\n if nPos > 0 then\n clear()\n nPos = 0\n recomplete()\n redraw()\n end\n\n elseif param == keys.delete then\n -- Delete\n if nPos < #sLine then\n clear()\n sLine = string.sub(sLine, 1, nPos) .. string.sub(sLine, nPos + 2)\n recomplete()\n redraw()\n end\n\n elseif param == keys["end"] then\n -- End\n if nPos < #sLine then\n clear()\n nPos = #sLine\n recomplete()\n redraw()\n end\n\n elseif param == keys.tab then\n -- Tab (accept autocomplete)\n acceptCompletion()\n\n end\n\n elseif sEvent == "mouse_click" or sEvent == "mouse_drag" and param == 1 then\n local _, cy = term.getCursorPos()\n if param1 >= sx and param1 <= w and param2 == cy then\n -- Ensure we don\'t scroll beyond the current line\n nPos = math.min(math.max(nScroll + param1 - sx, 0), #sLine)\n redraw()\n end\n\n elseif sEvent == "term_resize" then\n -- Terminal resized\n w = term.getSize()\n redraw()\n\n end\n end\n\n local _, cy = term.getCursorPos()\n term.setCursorBlink(false)\n term.setCursorPos(w + 1, cy)\n print()\n\n return sLine\nend\n\nfunction loadfile(filename, mode, env)\n -- Support the previous `loadfile(filename, env)` form instead.\n if type(mode) == "table" and env == nil then\n mode, env = nil, mode\n end\n\n expect(1, filename, "string")\n expect(2, mode, "string", "nil")\n expect(3, env, "table", "nil")\n\n local file = fs.open(filename, "r")\n if not file then return nil, "File not found" end\n\n local func, err = load(file.readAll(), "@/" .. fs.combine(filename), mode, env)\n file.close()\n return func, err\nend\n\nfunction dofile(_sFile)\n expect(1, _sFile, "string")\n\n local fnFile, e = loadfile(_sFile, nil, _G)\n if fnFile then\n return fnFile()\n else\n error(e, 2)\n end\nend\n\n-- Install the rest of the OS api\nfunction os.run(_tEnv, _sPath, ...)\n expect(1, _tEnv, "table")\n expect(2, _sPath, "string")\n\n local tEnv = _tEnv\n setmetatable(tEnv, { __index = _G })\n\n if settings.get("bios.strict_globals", false) then\n -- load will attempt to set _ENV on this environment, which\n -- throws an error with this protection enabled. Thus we set it here first.\n tEnv._ENV = tEnv\n getmetatable(tEnv).__newindex = function(_, name)\n error("Attempt to create global " .. tostring(name), 2)\n end\n end\n\n local fnFile, err = loadfile(_sPath, nil, tEnv)\n if fnFile then\n local ok, err = pcall(fnFile, ...)\n if not ok then\n if err and err ~= "" then\n printError(err)\n end\n return false\n end\n return true\n end\n if err and err ~= "" then\n printError(err)\n end\n return false\nend\n\nlocal tAPIsLoading = {}\nfunction os.loadAPI(_sPath)\n expect(1, _sPath, "string")\n local sName = fs.getName(_sPath)\n if sName:sub(-4) == ".lua" then\n sName = sName:sub(1, -5)\n end\n if tAPIsLoading[sName] == true then\n printError("API " .. sName .. " is already being loaded")\n return false\n end\n tAPIsLoading[sName] = true\n\n local tEnv = {}\n setmetatable(tEnv, { __index = _G })\n local fnAPI, err = loadfile(_sPath, nil, tEnv)\n if fnAPI then\n local ok, err = pcall(fnAPI)\n if not ok then\n tAPIsLoading[sName] = nil\n return error("Failed to load API " .. sName .. " due to " .. err, 1)\n end\n else\n tAPIsLoading[sName] = nil\n return error("Failed to load API " .. sName .. " due to " .. err, 1)\n end\n\n local tAPI = {}\n for k, v in pairs(tEnv) do\n if k ~= "_ENV" then\n tAPI[k] = v\n end\n end\n\n _G[sName] = tAPI\n tAPIsLoading[sName] = nil\n return true\nend\n\nfunction os.unloadAPI(_sName)\n expect(1, _sName, "string")\n if _sName ~= "_G" and type(_G[_sName]) == "table" then\n _G[_sName] = nil\n end\nend\n\nfunction os.sleep(nTime)\n sleep(nTime)\nend\n\nlocal nativeShutdown = os.shutdown\nfunction os.shutdown()\n nativeShutdown()\n while true do\n coroutine.yield()\n end\nend\n\nlocal nativeReboot = os.reboot\nfunction os.reboot()\n nativeReboot()\n while true do\n coroutine.yield()\n end\nend\n\nlocal bAPIError = false\n\nlocal function load_apis(dir)\n if not fs.isDir(dir) then return end\n\n for _, file in ipairs(fs.list(dir)) do\n if file:sub(1, 1) ~= "." then\n local path = fs.combine(dir, file)\n if not fs.isDir(path) then\n if not os.loadAPI(path) then\n bAPIError = true\n end\n end\n end\n end\nend\n\n-- Load APIs\nload_apis("rom/apis")\nif http then load_apis("rom/apis/http") end\nif turtle then load_apis("rom/apis/turtle") end\nif pocket then load_apis("rom/apis/pocket") end\n\nif commands and fs.isDir("rom/apis/command") then\n -- Load command APIs\n if os.loadAPI("rom/apis/command/commands.lua") then\n -- Add a special case-insensitive metatable to the commands api\n local tCaseInsensitiveMetatable = {\n __index = function(table, key)\n local value = rawget(table, key)\n if value ~= nil then\n return value\n end\n if type(key) == "string" then\n local value = rawget(table, string.lower(key))\n if value ~= nil then\n return value\n end\n end\n return nil\n end,\n }\n setmetatable(commands, tCaseInsensitiveMetatable)\n setmetatable(commands.async, tCaseInsensitiveMetatable)\n\n -- Add global "exec" function\n exec = commands.exec\n else\n bAPIError = true\n end\nend\n\nif bAPIError then\n print("Press any key to continue")\n os.pullEvent("key")\n term.clear()\n term.setCursorPos(1, 1)\nend\n\n-- Set default settings\nsettings.define("shell.allow_startup", {\n default = true,\n description = "Run startup files when the computer turns on.",\n type = "boolean",\n})\nsettings.define("shell.allow_disk_startup", {\n default = commands == nil,\n description = "Run startup files from disk drives when the computer turns on.",\n type = "boolean",\n})\n\nsettings.define("shell.autocomplete", {\n default = true,\n description = "Autocomplete program and arguments in the shell.",\n type = "boolean",\n})\nsettings.define("edit.autocomplete", {\n default = true,\n description = "Autocomplete API and function names in the editor.",\n type = "boolean",\n})\nsettings.define("lua.autocomplete", {\n default = true,\n description = "Autocomplete API and function names in the Lua REPL.",\n type = "boolean",\n})\n\nsettings.define("edit.default_extension", {\n default = "lua",\n description = [[The file extension the editor will use if none is given. Set to "" to disable.]],\n type = "string",\n})\nsettings.define("paint.default_extension", {\n default = "nfp",\n description = [[The file extension the paint program will use if none is given. Set to "" to disable.]],\n type = "string",\n})\n\nsettings.define("list.show_hidden", {\n default = false,\n description = [[Whether the list program show hidden files (those starting with ".").]],\n type = "boolean",\n})\n\nsettings.define("motd.enable", {\n default = pocket == nil,\n description = "Display a random message when the computer starts up.",\n type = "boolean",\n})\nsettings.define("motd.path", {\n default = "/rom/motd.txt:/motd.txt",\n description = [[The path to load random messages from. Should be a colon (":") separated string of file paths.]],\n type = "string",\n})\n\nsettings.define("lua.warn_against_use_of_local", {\n default = true,\n description = [[Print a message when input in the Lua REPL starts with the word \'local\'. Local variables defined in the Lua REPL are be inaccessible on the next input.]],\n type = "boolean",\n})\nsettings.define("lua.function_args", {\n default = true,\n description = "Show function arguments when printing functions.",\n type = "boolean",\n})\nsettings.define("lua.function_source", {\n default = false,\n description = "Show where a function was defined when printing functions.",\n type = "boolean",\n})\nsettings.define("bios.strict_globals", {\n default = false,\n description = "Prevents assigning variables into a program\'s environment. Make sure you use the local keyword or assign to _G explicitly.",\n type = "boolean",\n})\nsettings.define("shell.autocomplete_hidden", {\n default = false,\n description = [[Autocomplete hidden files and folders (those starting with ".").]],\n type = "boolean",\n})\n\nif term.isColour() then\n settings.define("bios.use_multishell", {\n default = true,\n description = [[Allow running multiple programs at once, through the use of the "fg" and "bg" programs.]],\n type = "boolean",\n })\nend\nif _CC_DEFAULT_SETTINGS then\n for sPair in string.gmatch(_CC_DEFAULT_SETTINGS, "[^,]+") do\n local sName, sValue = string.match(sPair, "([^=]*)=(.*)")\n if sName and sValue then\n local value\n if sValue == "true" then\n value = true\n elseif sValue == "false" then\n value = false\n elseif sValue == "nil" then\n value = nil\n elseif tonumber(sValue) then\n value = tonumber(sValue)\n else\n value = sValue\n end\n if value ~= nil then\n settings.set(sName, value)\n else\n settings.unset(sName)\n end\n end\n end\nend\n\n-- Load user settings\nif fs.exists(".settings") then\n settings.load(".settings")\nend\n\n-- Run the shell\nlocal ok, err = pcall(parallel.waitForAny,\n function()\n local sShell\n if term.isColour() and settings.get("bios.use_multishell") then\n sShell = "rom/programs/advanced/multishell.lua"\n else\n sShell = "rom/programs/shell.lua"\n end\n os.run({}, sShell)\n os.run({}, "rom/programs/shutdown.lua")\n end,\n rednet.run\n)\n\n-- If the shell errored, let the user read it.\nterm.redirect(term.native())\nif not ok then\n printError(err)\n pcall(function()\n term.setCursorBlink(false)\n print("Press any key to continue")\n os.pullEvent("key")\n end)\nend\n\n-- End\nos.shutdown()\n',"rom/apis/colors.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[- Constants and functions for colour values, suitable for working with\n[`term`] and [`redstone`].\n\nThis is useful in conjunction with [Bundled Cables][`redstone.setBundledOutput`]\nfrom mods like Project Red, and [colors on Advanced Computers and Advanced\nMonitors][`term.setTextColour`].\n\nFor the non-American English version just replace [`colors`] with [`colours`].\nThis alternative API is exactly the same, except the colours use British English\n(e.g. [`colors.gray`] is spelt [`colours.grey`]).\n\nOn basic terminals (such as the Computer and Monitor), all the colors are\nconverted to grayscale. This means you can still use all 16 colors on the\nscreen, but they will appear as the nearest tint of gray. You can check if a\nterminal supports color by using the function [`term.isColor`].\n\nGrayscale colors are calculated by taking the average of the three components,\ni.e. `(red + green + blue) / 3`.\n\n<table>\n<thead>\n <tr><th colspan="8" align="center">Default Colors</th></tr>\n <tr>\n <th rowspan="2" align="center">Color</th>\n <th colspan="3" align="center">Value</th>\n <th colspan="4" align="center">Default Palette Color</th>\n </tr>\n <tr>\n <th>Dec</th><th>Hex</th><th>Paint/Blit</th>\n <th>Preview</th><th>Hex</th><th>RGB</th><th>Grayscale</th>\n </tr>\n</thead>\n<tbody>\n <tr>\n <td><code>colors.white</code></td>\n <td align="right">1</td><td align="right">0x1</td><td align="right">0</td>\n <td style="background:#F0F0F0"></td><td>#F0F0F0</td><td>240, 240, 240</td>\n <td style="background:#F0F0F0"></td>\n </tr>\n <tr>\n <td><code>colors.orange</code></td>\n <td align="right">2</td><td align="right">0x2</td><td align="right">1</td>\n <td style="background:#F2B233"></td><td>#F2B233</td><td>242, 178, 51</td>\n <td style="background:#9D9D9D"></td>\n </tr>\n <tr>\n <td><code>colors.magenta</code></td>\n <td align="right">4</td><td align="right">0x4</td><td align="right">2</td>\n <td style="background:#E57FD8"></td><td>#E57FD8</td><td>229, 127, 216</td>\n <td style="background:#BEBEBE"></td>\n </tr>\n <tr>\n <td><code>colors.lightBlue</code></td>\n <td align="right">8</td><td align="right">0x8</td><td align="right">3</td>\n <td style="background:#99B2F2"></td><td>#99B2F2</td><td>153, 178, 242</td>\n <td style="background:#BFBFBF"></td>\n </tr>\n <tr>\n <td><code>colors.yellow</code></td>\n <td align="right">16</td><td align="right">0x10</td><td align="right">4</td>\n <td style="background:#DEDE6C"></td><td>#DEDE6C</td><td>222, 222, 108</td>\n <td style="background:#B8B8B8"></td>\n </tr>\n <tr>\n <td><code>colors.lime</code></td>\n <td align="right">32</td><td align="right">0x20</td><td align="right">5</td>\n <td style="background:#7FCC19"></td><td>#7FCC19</td><td>127, 204, 25</td>\n <td style="background:#767676"></td>\n </tr>\n <tr>\n <td><code>colors.pink</code></td>\n <td align="right">64</td><td align="right">0x40</td><td align="right">6</td>\n <td style="background:#F2B2CC"></td><td>#F2B2CC</td><td>242, 178, 204</td>\n <td style="background:#D0D0D0"></td>\n </tr>\n <tr>\n <td><code>colors.gray</code></td>\n <td align="right">128</td><td align="right">0x80</td><td align="right">7</td>\n <td style="background:#4C4C4C"></td><td>#4C4C4C</td><td>76, 76, 76</td>\n <td style="background:#4C4C4C"></td>\n </tr>\n <tr>\n <td><code>colors.lightGray</code></td>\n <td align="right">256</td><td align="right">0x100</td><td align="right">8</td>\n <td style="background:#999999"></td><td>#999999</td><td>153, 153, 153</td>\n <td style="background:#999999"></td>\n </tr>\n <tr>\n <td><code>colors.cyan</code></td>\n <td align="right">512</td><td align="right">0x200</td><td align="right">9</td>\n <td style="background:#4C99B2"></td><td>#4C99B2</td><td>76, 153, 178</td>\n <td style="background:#878787"></td>\n </tr>\n <tr>\n <td><code>colors.purple</code></td>\n <td align="right">1024</td><td align="right">0x400</td><td align="right">a</td>\n <td style="background:#B266E5"></td><td>#B266E5</td><td>178, 102, 229</td>\n <td style="background:#A9A9A9"></td>\n </tr>\n <tr>\n <td><code>colors.blue</code></td>\n <td align="right">2048</td><td align="right">0x800</td><td align="right">b</td>\n <td style="background:#3366CC"></td><td>#3366CC</td><td>51, 102, 204</td>\n <td style="background:#777777"></td>\n </tr>\n <tr>\n <td><code>colors.brown</code></td>\n <td align="right">4096</td><td align="right">0x1000</td><td align="right">c</td>\n <td style="background:#7F664C"></td><td>#7F664C</td><td>127, 102, 76</td>\n <td style="background:#656565"></td>\n </tr>\n <tr>\n <td><code>colors.green</code></td>\n <td align="right">8192</td><td align="right">0x2000</td><td align="right">d</td>\n <td style="background:#57A64E"></td><td>#57A64E</td><td>87, 166, 78</td>\n <td style="background:#6E6E6E"></td>\n </tr>\n <tr>\n <td><code>colors.red</code></td>\n <td align="right">16384</td><td align="right">0x4000</td><td align="right">e</td>\n <td style="background:#CC4C4C"></td><td>#CC4C4C</td><td>204, 76, 76</td>\n <td style="background:#767676"></td>\n </tr>\n <tr>\n <td><code>colors.black</code></td>\n <td align="right">32768</td><td align="right">0x8000</td><td align="right">f</td>\n <td style="background:#111111"></td><td>#111111</td><td>17, 17, 17</td>\n <td style="background:#111111"></td>\n </tr>\n</tbody>\n</table>\n\n@see colours\n@module colors\n]]\n\nlocal expect = dofile("rom/modules/main/cc/expect.lua").expect\n\n--- White: Written as `0` in paint files and [`term.blit`], has a default\n-- terminal colour of #F0F0F0.\nwhite = 0x1\n\n--- Orange: Written as `1` in paint files and [`term.blit`], has a\n-- default terminal colour of #F2B233.\norange = 0x2\n\n--- Magenta: Written as `2` in paint files and [`term.blit`], has a\n-- default terminal colour of #E57FD8.\nmagenta = 0x4\n\n--- Light blue: Written as `3` in paint files and [`term.blit`], has a\n-- default terminal colour of #99B2F2.\nlightBlue = 0x8\n\n--- Yellow: Written as `4` in paint files and [`term.blit`], has a\n-- default terminal colour of #DEDE6C.\nyellow = 0x10\n\n--- Lime: Written as `5` in paint files and [`term.blit`], has a default\n-- terminal colour of #7FCC19.\nlime = 0x20\n\n--- Pink: Written as `6` in paint files and [`term.blit`], has a default\n-- terminal colour of #F2B2CC.\npink = 0x40\n\n--- Gray: Written as `7` in paint files and [`term.blit`], has a default\n-- terminal colour of #4C4C4C.\ngray = 0x80\n\n--- Light gray: Written as `8` in paint files and [`term.blit`], has a\n-- default terminal colour of #999999.\nlightGray = 0x100\n\n--- Cyan: Written as `9` in paint files and [`term.blit`], has a default\n-- terminal colour of #4C99B2.\ncyan = 0x200\n\n--- Purple: Written as `a` in paint files and [`term.blit`], has a\n-- default terminal colour of #B266E5.\npurple = 0x400\n\n--- Blue: Written as `b` in paint files and [`term.blit`], has a default\n-- terminal colour of #3366CC.\nblue = 0x800\n\n--- Brown: Written as `c` in paint files and [`term.blit`], has a default\n-- terminal colour of #7F664C.\nbrown = 0x1000\n\n--- Green: Written as `d` in paint files and [`term.blit`], has a default\n-- terminal colour of #57A64E.\ngreen = 0x2000\n\n--- Red: Written as `e` in paint files and [`term.blit`], has a default\n-- terminal colour of #CC4C4C.\nred = 0x4000\n\n--- Black: Written as `f` in paint files and [`term.blit`], has a default\n-- terminal colour of #111111.\nblack = 0x8000\n\n--- Combines a set of colors (or sets of colors) into a larger set. Useful for\n-- Bundled Cables.\n--\n-- @tparam number ... The colors to combine.\n-- @treturn number The union of the color sets given in `...`\n-- @since 1.2\n-- @usage\n-- ```lua\n-- colors.combine(colors.white, colors.magenta, colours.lightBlue)\n-- -- => 13\n-- ```\nfunction combine(...)\n local r = 0\n for i = 1, select(\'#\', ...) do\n local c = select(i, ...)\n expect(i, c, "number")\n r = bit32.bor(r, c)\n end\n return r\nend\n\n--- Removes one or more colors (or sets of colors) from an initial set. Useful\n-- for Bundled Cables.\n--\n-- Each parameter beyond the first may be a single color or may be a set of\n-- colors (in the latter case, all colors in the set are removed from the\n-- original set).\n--\n-- @tparam number colors The color from which to subtract.\n-- @tparam number ... The colors to subtract.\n-- @treturn number The resulting color.\n-- @since 1.2\n-- @usage\n-- ```lua\n-- colours.subtract(colours.lime, colours.orange, colours.white)\n-- -- => 32\n-- ```\nfunction subtract(colors, ...)\n expect(1, colors, "number")\n local r = colors\n for i = 1, select(\'#\', ...) do\n local c = select(i, ...)\n expect(i + 1, c, "number")\n r = bit32.band(r, bit32.bnot(c))\n end\n return r\nend\n\n--- Tests whether `color` is contained within `colors`. Useful for Bundled\n-- Cables.\n--\n-- @tparam number colors A color, or color set\n-- @tparam number color A color or set of colors that `colors` should contain.\n-- @treturn boolean If `colors` contains all colors within `color`.\n-- @since 1.2\n-- @usage\n-- ```lua\n-- colors.test(colors.combine(colors.white, colors.magenta, colours.lightBlue), colors.lightBlue)\n-- -- => true\n-- ```\nfunction test(colors, color)\n expect(1, colors, "number")\n expect(2, color, "number")\n return bit32.band(colors, color) == color\nend\n\n--- Combine a three-colour RGB value into one hexadecimal representation.\n--\n-- @tparam number r The red channel, should be between 0 and 1.\n-- @tparam number g The green channel, should be between 0 and 1.\n-- @tparam number b The blue channel, should be between 0 and 1.\n-- @treturn number The combined hexadecimal colour.\n-- @usage\n-- ```lua\n-- colors.packRGB(0.7, 0.2, 0.6)\n-- -- => 0xb23399\n-- ```\n-- @since 1.81.0\nfunction packRGB(r, g, b)\n expect(1, r, "number")\n expect(2, g, "number")\n expect(3, b, "number")\n return\n bit32.band(r * 255, 0xFF) * 2 ^ 16 +\n bit32.band(g * 255, 0xFF) * 2 ^ 8 +\n bit32.band(b * 255, 0xFF)\nend\n\n--- Separate a hexadecimal RGB colour into its three constituent channels.\n--\n-- @tparam number rgb The combined hexadecimal colour.\n-- @treturn number The red channel, will be between 0 and 1.\n-- @treturn number The green channel, will be between 0 and 1.\n-- @treturn number The blue channel, will be between 0 and 1.\n-- @usage\n-- ```lua\n-- colors.unpackRGB(0xb23399)\n-- -- => 0.7, 0.2, 0.6\n-- ```\n-- @see colors.packRGB\n-- @since 1.81.0\nfunction unpackRGB(rgb)\n expect(1, rgb, "number")\n return\n bit32.band(bit32.rshift(rgb, 16), 0xFF) / 255,\n bit32.band(bit32.rshift(rgb, 8), 0xFF) / 255,\n bit32.band(rgb, 0xFF) / 255\nend\n\n--- Either calls [`colors.packRGB`] or [`colors.unpackRGB`], depending on how many\n-- arguments it receives.\n--\n-- @tparam[1] number r The red channel, as an argument to [`colors.packRGB`].\n-- @tparam[1] number g The green channel, as an argument to [`colors.packRGB`].\n-- @tparam[1] number b The blue channel, as an argument to [`colors.packRGB`].\n-- @tparam[2] number rgb The combined hexadecimal color, as an argument to [`colors.unpackRGB`].\n-- @treturn[1] number The combined hexadecimal colour, as returned by [`colors.packRGB`].\n-- @treturn[2] number The red channel, as returned by [`colors.unpackRGB`]\n-- @treturn[2] number The green channel, as returned by [`colors.unpackRGB`]\n-- @treturn[2] number The blue channel, as returned by [`colors.unpackRGB`]\n-- @deprecated Use [`packRGB`] or [`unpackRGB`] directly.\n-- @usage\n-- ```lua\n-- colors.rgb8(0xb23399)\n-- -- => 0.7, 0.2, 0.6\n-- ```\n-- @usage\n-- ```lua\n-- colors.rgb8(0.7, 0.2, 0.6)\n-- -- => 0xb23399\n-- ```\n-- @since 1.80pr1\n-- @changed 1.81.0 Deprecated in favor of colors.(un)packRGB.\nfunction rgb8(r, g, b)\n if g == nil and b == nil then\n return unpackRGB(r)\n else\n return packRGB(r, g, b)\n end\nend\n\n-- Colour to hex lookup table for toBlit\nlocal color_hex_lookup = {}\nfor i = 0, 15 do\n color_hex_lookup[2 ^ i] = string.format("%x", i)\nend\n\n--[[- Converts the given color to a paint/blit hex character (0-9a-f).\n\nThis is equivalent to converting floor(log_2(color)) to hexadecimal.\n\n@tparam number color The color to convert.\n@treturn string The blit hex code of the color.\n@usage\n```lua\ncolors.toBlit(colors.red)\n-- => "c"\n```\n@see colors.fromBlit\n@since 1.94.0\n]]\nfunction toBlit(color)\n expect(1, color, "number")\n return color_hex_lookup[color] or string.format("%x", math.floor(math.log(color, 2)))\nend\n\n--[[- Converts the given paint/blit hex character (0-9a-f) to a color.\n\nThis is equivalent to converting the hex character to a number and then 2 ^ decimal\n\n@tparam string hex The paint/blit hex character to convert\n@treturn number The color\n@usage\n```lua\ncolors.fromBlit("e")\n-- => 16384\n```\n@see colors.toBlit\n@since 1.105.0\n]]\nfunction fromBlit(hex)\n expect(1, hex, "string")\n\n if #hex ~= 1 then return nil end\n local value = tonumber(hex, 16)\n if not value then return nil end\n\n return 2 ^ value\nend\n',"rom/apis/colours.lua":"-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--- An alternative version of [`colors`] for lovers of British spelling.\n--\n-- @see colors\n-- @module colours\n-- @since 1.2\n\nlocal colours = _ENV\nfor k, v in pairs(colors) do\n colours[k] = v\nend\n\n--- Grey. Written as `7` in paint files and [`term.blit`], has a default\n-- terminal colour of #4C4C4C.\n--\n-- @see colors.gray\ncolours.grey = colors.gray\ncolours.gray = nil --- @local\n\n--- Light grey. Written as `8` in paint files and [`term.blit`], has a\n-- default terminal colour of #999999.\n--\n-- @see colors.lightGray\ncolours.lightGrey = colors.lightGray\ncolours.lightGray = nil --- @local\n","rom/apis/command/commands.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[- Execute [Minecraft commands][mc] and gather data from the results from\na command computer.\n\n> [!NOTE]\n> This API is only available on Command computers. It is not accessible to normal\n> players.\n\nWhile one may use [`commands.exec`] directly to execute a command, the\ncommands API also provides helper methods to execute every command. For\ninstance, `commands.say("Hi!")` is equivalent to `commands.exec("say Hi!")`.\n\n[`commands.async`] provides a similar interface to execute asynchronous\ncommands. `commands.async.say("Hi!")` is equivalent to\n`commands.execAsync("say Hi!")`.\n\n[mc]: https://minecraft.wiki/w/Commands\n\n@module commands\n@usage Set the block above this computer to stone:\n\n commands.setblock("~", "~1", "~", "minecraft:stone")\n]]\nif not commands then\n error("Cannot load command API on normal computer", 2)\nend\n\n--- The builtin commands API, without any generated command helper functions\n--\n-- This may be useful if a built-in function (such as [`commands.list`]) has been\n-- overwritten by a command.\nlocal native = commands.native or commands\n\nlocal function collapseArgs(bJSONIsNBT, ...)\n local args = table.pack(...)\n for i = 1, #args do\n local arg = args[i]\n if type(arg) == "boolean" or type(arg) == "number" or type(arg) == "string" then\n args[i] = tostring(arg)\n elseif type(arg) == "table" then\n args[i] = textutils.serialiseJSON(arg, bJSONIsNBT)\n else\n error("Expected string, number, boolean or table", 3)\n end\n end\n\n return table.concat(args, " ")\nend\n\n-- Put native functions into the environment\nlocal env = _ENV\nenv.native = native\nfor k, v in pairs(native) do\n env[k] = v\nend\n\n-- Create wrapper functions for all the commands\nlocal tAsync = {}\nlocal tNonNBTJSONCommands = {\n ["tellraw"] = true,\n ["title"] = true,\n}\n\nlocal command_mt = {}\nfunction command_mt.__call(self, ...)\n local meta = self[command_mt]\n local sCommand = collapseArgs(meta.json, table.concat(meta.name, " "), ...)\n return meta.func(sCommand)\nend\n\nfunction command_mt.__tostring(self)\n local meta = self[command_mt]\n return ("command %q"):format("/" .. table.concat(meta.name, " "))\nend\n\nlocal function mk_command(name, json, func)\n return setmetatable({\n [command_mt] = {\n name = name,\n func = func,\n json = json,\n },\n }, command_mt)\nend\n\nfunction command_mt.__index(self, key)\n local meta = self[command_mt]\n if meta.children then return nil end\n meta.children = true\n\n local name = meta.name\n for _, child in ipairs(native.list(table.unpack(name))) do\n local child_name = { table.unpack(name) }\n child_name[#child_name + 1] = child\n self[child] = mk_command(child_name, meta.json, meta.func)\n end\n\n return self[key]\nend\n\nfor _, sCommandName in ipairs(native.list()) do\n if env[sCommandName] == nil then\n local bJSONIsNBT = tNonNBTJSONCommands[sCommandName] == nil\n env[sCommandName] = mk_command({ sCommandName }, bJSONIsNBT, native.exec)\n tAsync[sCommandName] = mk_command({ sCommandName }, bJSONIsNBT, native.execAsync)\n end\nend\n\n--- A table containing asynchronous wrappers for all commands.\n--\n-- As with [`commands.execAsync`], this returns the "task id" of the enqueued\n-- command.\n-- @see execAsync\n-- @usage Asynchronously sets the block above the computer to stone.\n--\n-- commands.async.setblock("~", "~1", "~", "minecraft:stone")\nenv.async = tAsync\n',"rom/apis/disk.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[- Interact with disk drives.\n\nThese functions can operate on locally attached or remote disk drives. To use a\nlocally attached drive, specify “side” as one of the six sides (e.g. `left`); to\nuse a remote disk drive, specify its name as printed when enabling its modem\n(e.g. `drive_0`).\n\n> [!TIP]\n> All computers (except command computers), turtles and pocket computers can be\n> placed within a disk drive to access it\'s internal storage like a disk.\n\n@module disk\n@since 1.2\n]]\n\nlocal function isDrive(name)\n if type(name) ~= "string" then\n error("bad argument #1 (string expected, got " .. type(name) .. ")", 3)\n end\n return peripheral.getType(name) == "drive"\nend\n\n--- Checks whether any item at all is in the disk drive\n--\n-- @tparam string name The name of the disk drive.\n-- @treturn boolean If something is in the disk drive.\n-- @usage disk.isPresent("top")\nfunction isPresent(name)\n if isDrive(name) then\n return peripheral.call(name, "isDiskPresent")\n end\n return false\nend\n\n--- Get the label of the floppy disk, record, or other media within the given\n-- disk drive.\n--\n-- If there is a computer or turtle within the drive, this will set the label as\n-- read by `os.getComputerLabel`.\n--\n-- @tparam string name The name of the disk drive.\n-- @treturn string|nil The name of the current media, or `nil` if the drive is\n-- not present or empty.\n-- @see disk.setLabel\nfunction getLabel(name)\n if isDrive(name) then\n return peripheral.call(name, "getDiskLabel")\n end\n return nil\nend\n\n--- Set the label of the floppy disk or other media\n--\n-- @tparam string name The name of the disk drive.\n-- @tparam string|nil label The new label of the disk\nfunction setLabel(name, label)\n if isDrive(name) then\n peripheral.call(name, "setDiskLabel", label)\n end\nend\n\n--- Check whether the current disk provides a mount.\n--\n-- This will return true for disks and computers, but not records.\n--\n-- @tparam string name The name of the disk drive.\n-- @treturn boolean If the disk is present and provides a mount.\n-- @see disk.getMountPath\nfunction hasData(name)\n if isDrive(name) then\n return peripheral.call(name, "hasData")\n end\n return false\nend\n\n--- Find the directory name on the local computer where the contents of the\n-- current floppy disk (or other mount) can be found.\n--\n-- @tparam string name The name of the disk drive.\n-- @treturn string|nil The mount\'s directory, or `nil` if the drive does not\n-- contain a floppy or computer.\n-- @see disk.hasData\nfunction getMountPath(name)\n if isDrive(name) then\n return peripheral.call(name, "getMountPath")\n end\n return nil\nend\n\n--- Whether the current disk is a [music disk][disk] as opposed to a floppy disk\n-- or other item.\n--\n-- If this returns true, you will can [play][`disk.playAudio`] the record.\n--\n-- [disk]: https://minecraft.wiki/w/Music_Disc\n--\n-- @tparam string name The name of the disk drive.\n-- @treturn boolean If the disk is present and has audio saved on it.\nfunction hasAudio(name)\n if isDrive(name) then\n return peripheral.call(name, "hasAudio")\n end\n return false\nend\n\n--- Get the title of the audio track from the music record in the drive.\n--\n-- This generally returns the same as [`disk.getLabel`] for records.\n--\n-- @tparam string name The name of the disk drive.\n-- @treturn string|false|nil The track title, [`false`] if there is not a music\n-- record in the drive or `nil` if no drive is present.\nfunction getAudioTitle(name)\n if isDrive(name) then\n return peripheral.call(name, "getAudioTitle")\n end\n return nil\nend\n\n--- Starts playing the music record in the drive.\n--\n-- If any record is already playing on any disk drive, it stops before the\n-- target drive starts playing. The record stops when it reaches the end of the\n-- track, when it is removed from the drive, when [`disk.stopAudio`] is called, or\n-- when another record is started.\n--\n-- @tparam string name The name of the disk drive.\n-- @usage disk.playAudio("bottom")\nfunction playAudio(name)\n if isDrive(name) then\n peripheral.call(name, "playAudio")\n end\nend\n\n--- Stops the music record in the drive from playing, if it was started with\n-- [`disk.playAudio`].\n--\n-- @tparam string name The name o the disk drive.\nfunction stopAudio(name)\n if not name then\n for _, sName in ipairs(peripheral.getNames()) do\n stopAudio(sName)\n end\n else\n if isDrive(name) then\n peripheral.call(name, "stopAudio")\n end\n end\nend\n\n--- Ejects any item currently in the drive, spilling it into the world as a loose item.\n--\n-- @tparam string name The name of the disk drive.\n-- @usage disk.eject("bottom")\nfunction eject(name)\n if isDrive(name) then\n peripheral.call(name, "ejectDisk")\n end\nend\n\n--- Returns a number which uniquely identifies the disk in the drive.\n--\n-- Note, unlike [`disk.getLabel`], this does not return anything for other media,\n-- such as computers or turtles.\n--\n-- @tparam string name The name of the disk drive.\n-- @treturn string|nil The disk ID, or `nil` if the drive does not contain a floppy disk.\n-- @since 1.4\nfunction getID(name)\n if isDrive(name) then\n return peripheral.call(name, "getDiskID")\n end\n return nil\nend\n',"rom/apis/fs.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--- @module fs\n\nlocal expect = dofile("rom/modules/main/cc/expect.lua")\nlocal expect, field = expect.expect, expect.field\n\nlocal native = fs\n\nlocal fs = _ENV\nfor k, v in pairs(native) do fs[k] = v end\n\n--[[- Provides completion for a file or directory name, suitable for use with\n[`_G.read`].\n\nWhen a directory is a possible candidate for completion, two entries are\nincluded - one with a trailing slash (indicating that entries within this\ndirectory exist) and one without it (meaning this entry is an immediate\ncompletion candidate). `include_dirs` can be set to [`false`] to only include\nthose with a trailing slash.\n\n@tparam[1] string path The path to complete.\n@tparam[1] string location The location where paths are resolved from.\n@tparam[1,opt=true] boolean include_files When [`false`], only directories will\nbe included in the returned list.\n@tparam[1,opt=true] boolean include_dirs When [`false`], "raw" directories will\nnot be included in the returned list.\n\n@tparam[2] string path The path to complete.\n@tparam[2] string location The location where paths are resolved from.\n@tparam[2] {\n include_dirs? = boolean, include_files? = boolean,\n include_hidden? = boolean\n} options\nThis table form is an expanded version of the previous syntax. The\n`include_files` and `include_dirs` arguments from above are passed in as fields.\n\nThis table also accepts the following options:\n - `include_hidden`: Whether to include hidden files (those starting with `.`)\n by default. They will still be shown when typing a `.`.\n\n@treturn { string... } A list of possible completion candidates.\n@since 1.74\n@changed 1.101.0\n@usage Complete files in the root directory.\n\n read(nil, nil, function(str)\n return fs.complete(str, "", true, false)\n end)\n\n@usage Complete files in the root directory, hiding hidden files by default.\n\n read(nil, nil, function(str)\n return fs.complete(str, "", {\n include_files = true,\n include_dirs = false,\n include_hidden = false,\n })\n end)\n]]\nfunction fs.complete(sPath, sLocation, bIncludeFiles, bIncludeDirs)\n expect(1, sPath, "string")\n expect(2, sLocation, "string")\n local bIncludeHidden = nil\n if type(bIncludeFiles) == "table" then\n bIncludeDirs = field(bIncludeFiles, "include_dirs", "boolean", "nil")\n bIncludeHidden = field(bIncludeFiles, "include_hidden", "boolean", "nil")\n bIncludeFiles = field(bIncludeFiles, "include_files", "boolean", "nil")\n else\n expect(3, bIncludeFiles, "boolean", "nil")\n expect(4, bIncludeDirs, "boolean", "nil")\n end\n\n bIncludeHidden = bIncludeHidden ~= false\n bIncludeFiles = bIncludeFiles ~= false\n bIncludeDirs = bIncludeDirs ~= false\n local sDir = sLocation\n local nStart = 1\n local nSlash = string.find(sPath, "[/\\\\]", nStart)\n if nSlash == 1 then\n sDir = ""\n nStart = 2\n end\n local sName\n while not sName do\n local nSlash = string.find(sPath, "[/\\\\]", nStart)\n if nSlash then\n local sPart = string.sub(sPath, nStart, nSlash - 1)\n sDir = fs.combine(sDir, sPart)\n nStart = nSlash + 1\n else\n sName = string.sub(sPath, nStart)\n end\n end\n\n if fs.isDir(sDir) then\n local tResults = {}\n if bIncludeDirs and sPath == "" then\n table.insert(tResults, ".")\n end\n if sDir ~= "" then\n if sPath == "" then\n table.insert(tResults, bIncludeDirs and ".." or "../")\n elseif sPath == "." then\n table.insert(tResults, bIncludeDirs and "." or "./")\n end\n end\n local tFiles = fs.list(sDir)\n for n = 1, #tFiles do\n local sFile = tFiles[n]\n if #sFile >= #sName and string.sub(sFile, 1, #sName) == sName and (\n bIncludeHidden or sFile:sub(1, 1) ~= "." or sName:sub(1, 1) == "."\n ) then\n local bIsDir = fs.isDir(fs.combine(sDir, sFile))\n local sResult = string.sub(sFile, #sName + 1)\n if bIsDir then\n table.insert(tResults, sResult .. "/")\n if bIncludeDirs and #sResult > 0 then\n table.insert(tResults, sResult)\n end\n else\n if bIncludeFiles and #sResult > 0 then\n table.insert(tResults, sResult)\n end\n end\n end\n end\n return tResults\n end\n\n return {}\nend\n\nlocal function find_aux(path, parts, i, out)\n local part = parts[i]\n if not part then\n -- If we\'re at the end of the pattern, ensure our path exists and append it.\n if fs.exists(path) then out[#out + 1] = path end\n elseif part.exact then\n -- If we\'re an exact match, just recurse into this directory.\n return find_aux(fs.combine(path, part.contents), parts, i + 1, out)\n else\n -- Otherwise we\'re a pattern. Check we\'re a directory, then recurse into each\n -- matching file.\n if not fs.isDir(path) then return end\n\n local files = fs.list(path)\n for j = 1, #files do\n local file = files[j]\n if file:find(part.contents) then find_aux(fs.combine(path, file), parts, i + 1, out) end\n end\n end\nend\n\nlocal find_escape = {\n -- Escape standard Lua pattern characters\n ["^"] = "%^", ["$"] = "%$", ["("] = "%(", [")"] = "%)", ["%"] = "%%",\n ["."] = "%.", ["["] = "%[", ["]"] = "%]", ["+"] = "%+", ["-"] = "%-",\n -- Aside from our wildcards.\n ["*"] = ".*",\n ["?"] = ".",\n}\n\n--[[- Searches for files matching a string with wildcards.\n\nThis string looks like a normal path string, but can include wildcards, which\ncan match multiple paths:\n\n - "?" matches any single character in a file name.\n - "*" matches any number of characters.\n\nFor example, `rom/*/command*` will look for any path starting with `command`\ninside any subdirectory of `/rom`.\n\nNote that these wildcards match a single segment of the path. For instance\n`rom/*.lua` will include `rom/startup.lua` but _not_ include `rom/programs/list.lua`.\n\n@tparam string path The wildcard-qualified path to search for.\n@treturn { string... } A list of paths that match the search string.\n@throws If the supplied path was invalid.\n@since 1.6\n@changed 1.106.0 Added support for the `?` wildcard.\n\n@usage List all Markdown files in the help folder\n\n fs.find("rom/help/*.md")\n]]\nfunction fs.find(pattern)\n expect(1, pattern, "string")\n\n pattern = fs.combine(pattern) -- Normalise the path, removing ".."s.\n\n -- If the pattern is trying to search outside the computer root, just abort.\n -- This will fail later on anyway.\n if pattern == ".." or pattern:sub(1, 3) == "../" then\n error("/" .. pattern .. ": Invalid Path", 2)\n end\n\n -- If we\'ve no wildcards, just check the file exists.\n if not pattern:find("[*?]") then\n if fs.exists(pattern) then return { pattern } else return {} end\n end\n\n local parts = {}\n for part in pattern:gmatch("[^/]+") do\n if part:find("[*?]") then\n parts[#parts + 1] = {\n exact = false,\n contents = "^" .. part:gsub(".", find_escape) .. "$",\n }\n else\n parts[#parts + 1] = { exact = true, contents = part }\n end\n end\n\n local out = {}\n find_aux("", parts, 1, out)\n return out\nend\n\n--- Returns true if a path is mounted to the parent filesystem.\n--\n-- The root filesystem "/" is considered a mount, along with disk folders and\n-- the rom folder. Other programs (such as network shares) can exstend this to\n-- make other mount types by correctly assigning their return value for getDrive.\n--\n-- @tparam string path The path to check.\n-- @treturn boolean If the path is mounted, rather than a normal file/folder.\n-- @throws If the path does not exist.\n-- @see getDrive\n-- @since 1.87.0\nfunction fs.isDriveRoot(sPath)\n expect(1, sPath, "string")\n -- Force the root directory to be a mount.\n return fs.getDir(sPath) == ".." or fs.getDrive(sPath) ~= fs.getDrive(fs.getDir(sPath))\nend\n',"rom/apis/gps.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[- Use [modems][`modem`] to locate the position of the current turtle or\ncomputers.\n\nIt broadcasts a PING message over [`rednet`] and wait for responses. In order for\nthis system to work, there must be at least 4 computers used as gps hosts which\nwill respond and allow trilateration. Three of these hosts should be in a plane,\nand the fourth should be either above or below the other three. The three in a\nplane should not be in a line with each other. You can set up hosts using the\ngps program.\n\n> [!NOTE]\n> When entering in the coordinates for the host you need to put in the `x`, `y`,\n> and `z` coordinates of the block that the modem is connected to, not the modem.\n> All modem distances are measured from the block that the modem is placed on.\n\nAlso note that you may choose which axes x, y, or z refers to - so long as your\nsystems have the same definition as any GPS servers that\'re in range, it works\njust the same. For example, you might build a GPS cluster according to [this\ntutorial][1], using z to account for height, or you might use y to account for\nheight in the way that Minecraft\'s debug screen displays.\n\n[1]: http://www.computercraft.info/forums2/index.php?/topic/3088-how-to-guide-gps-global-position-system/\n\n@module gps\n@since 1.31\n@see gps_setup For more detailed instructions on setting up GPS\n]]\n\nlocal expect = dofile("rom/modules/main/cc/expect.lua").expect\n\n--- The channel which GPS requests and responses are broadcast on.\nCHANNEL_GPS = 65534\n\nlocal function trilaterate(A, B, C)\n local a2b = B.vPosition - A.vPosition\n local a2c = C.vPosition - A.vPosition\n\n if math.abs(a2b:normalize():dot(a2c:normalize())) > 0.999 then\n return nil\n end\n\n local d = a2b:length()\n local ex = a2b:normalize( )\n local i = ex:dot(a2c)\n local ey = (a2c - ex * i):normalize()\n local j = ey:dot(a2c)\n local ez = ex:cross(ey)\n\n local r1 = A.nDistance\n local r2 = B.nDistance\n local r3 = C.nDistance\n\n local x = (r1 * r1 - r2 * r2 + d * d) / (2 * d)\n local y = (r1 * r1 - r3 * r3 - x * x + (x - i) * (x - i) + j * j) / (2 * j)\n\n local result = A.vPosition + ex * x + ey * y\n\n local zSquared = r1 * r1 - x * x - y * y\n if zSquared > 0 then\n local z = math.sqrt(zSquared)\n local result1 = result + ez * z\n local result2 = result - ez * z\n\n local rounded1, rounded2 = result1:round(0.01), result2:round(0.01)\n if rounded1.x ~= rounded2.x or rounded1.y ~= rounded2.y or rounded1.z ~= rounded2.z then\n return rounded1, rounded2\n else\n return rounded1\n end\n end\n return result:round(0.01)\n\nend\n\nlocal function narrow(p1, p2, fix)\n local dist1 = math.abs((p1 - fix.vPosition):length() - fix.nDistance)\n local dist2 = math.abs((p2 - fix.vPosition):length() - fix.nDistance)\n\n if math.abs(dist1 - dist2) < 0.01 then\n return p1, p2\n elseif dist1 < dist2 then\n return p1:round(0.01)\n else\n return p2:round(0.01)\n end\nend\n\n--- Tries to retrieve the computer or turtles own location.\n--\n-- @tparam[opt=2] number timeout The maximum time in seconds taken to establish our\n-- position.\n-- @tparam[opt=false] boolean debug Print debugging messages\n-- @treturn[1] number This computer\'s `x` position.\n-- @treturn[1] number This computer\'s `y` position.\n-- @treturn[1] number This computer\'s `z` position.\n-- @treturn[2] nil If the position could not be established.\nfunction locate(_nTimeout, _bDebug)\n expect(1, _nTimeout, "number", "nil")\n expect(2, _bDebug, "boolean", "nil")\n -- Let command computers use their magic fourth-wall-breaking special abilities\n if commands then\n return commands.getBlockPosition()\n end\n\n -- Find a modem\n local sModemSide = nil\n for _, sSide in ipairs(rs.getSides()) do\n if peripheral.getType(sSide) == "modem" and peripheral.call(sSide, "isWireless") then\n sModemSide = sSide\n break\n end\n end\n\n if sModemSide == nil then\n if _bDebug then\n print("No wireless modem attached")\n end\n return nil\n end\n\n if _bDebug then\n print("Finding position...")\n end\n\n -- Open GPS channel to listen for ping responses\n local modem = peripheral.wrap(sModemSide)\n local bCloseChannel = false\n if not modem.isOpen(CHANNEL_GPS) then\n modem.open(CHANNEL_GPS)\n bCloseChannel = true\n end\n\n -- Send a ping to listening GPS hosts\n modem.transmit(CHANNEL_GPS, CHANNEL_GPS, "PING")\n\n -- Wait for the responses\n local tFixes = {}\n local pos1, pos2 = nil, nil\n local timeout = os.startTimer(_nTimeout or 2)\n while true do\n local e, p1, p2, p3, p4, p5 = os.pullEvent()\n if e == "modem_message" then\n -- We received a reply from a modem\n local sSide, sChannel, sReplyChannel, tMessage, nDistance = p1, p2, p3, p4, p5\n if sSide == sModemSide and sChannel == CHANNEL_GPS and sReplyChannel == CHANNEL_GPS and nDistance then\n -- Received the correct message from the correct modem: use it to determine position\n if type(tMessage) == "table" and #tMessage == 3 and tonumber(tMessage[1]) and tonumber(tMessage[2]) and tonumber(tMessage[3]) then\n local tFix = { vPosition = vector.new(tMessage[1], tMessage[2], tMessage[3]), nDistance = nDistance }\n if _bDebug then\n print(tFix.nDistance .. " metres from " .. tostring(tFix.vPosition))\n end\n if tFix.nDistance == 0 then\n pos1, pos2 = tFix.vPosition, nil\n else\n -- Insert our new position in our table, with a maximum of three items. If this is close to a\n -- previous position, replace that instead of inserting.\n local insIndex = math.min(3, #tFixes + 1)\n for i, older in pairs(tFixes) do\n if (older.vPosition - tFix.vPosition):length() < 1 then\n insIndex = i\n break\n end\n end\n tFixes[insIndex] = tFix\n\n if #tFixes >= 3 then\n if not pos1 then\n pos1, pos2 = trilaterate(tFixes[1], tFixes[2], tFixes[3])\n else\n pos1, pos2 = narrow(pos1, pos2, tFixes[3])\n end\n end\n end\n if pos1 and not pos2 then\n break\n end\n end\n end\n\n elseif e == "timer" then\n -- We received a timeout\n local timer = p1\n if timer == timeout then\n break\n end\n\n end\n end\n\n -- Close the channel, if we opened one\n if bCloseChannel then\n modem.close(CHANNEL_GPS)\n end\n\n -- Return the response\n if pos1 and pos2 then\n if _bDebug then\n print("Ambiguous position")\n print("Could be " .. pos1.x .. "," .. pos1.y .. "," .. pos1.z .. " or " .. pos2.x .. "," .. pos2.y .. "," .. pos2.z)\n end\n return nil\n elseif pos1 then\n if _bDebug then\n print("Position is " .. pos1.x .. "," .. pos1.y .. "," .. pos1.z)\n end\n return pos1.x, pos1.y, pos1.z\n else\n if _bDebug then\n print("Could not determine position")\n end\n return nil\n end\nend\n',"rom/apis/help.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--- Find help files on the current computer.\n--\n-- @module help\n-- @since 1.2\n\nlocal expect = dofile("rom/modules/main/cc/expect.lua").expect\n\nlocal sPath = "/rom/help"\n\n--- Returns a colon-separated list of directories where help files are searched\n-- for. All directories are absolute.\n--\n-- @treturn string The current help search path, separated by colons.\n-- @see help.setPath\nfunction path()\n return sPath\nend\n\n--- Sets the colon-separated list of directories where help files are searched\n-- for to `newPath`\n--\n-- @tparam string newPath The new path to use.\n-- @usage help.setPath( "/disk/help/" )\n-- @usage help.setPath( help.path() .. ":/myfolder/help/" )\n-- @see help.path\nfunction setPath(_sPath)\n expect(1, _sPath, "string")\n sPath = _sPath\nend\n\nlocal extensions = { "", ".md", ".txt" }\n\n--- Returns the location of the help file for the given topic.\n--\n-- @tparam string topic The topic to find\n-- @treturn string|nil The path to the given topic\'s help file, or `nil` if it\n-- cannot be found.\n-- @usage help.lookup("disk")\n-- @changed 1.80pr1 Now supports finding .txt files.\n-- @changed 1.97.0 Now supports finding Markdown files.\nfunction lookup(topic)\n expect(1, topic, "string")\n -- Look on the path variable\n for path in string.gmatch(sPath, "[^:]+") do\n path = fs.combine(path, topic)\n for _, extension in ipairs(extensions) do\n local file = path .. extension\n if fs.exists(file) and not fs.isDir(file) then\n return file\n end\n end\n end\n\n -- Not found\n return nil\nend\n\n--- Returns a list of topics that can be looked up and/or displayed.\n--\n-- @treturn table A list of topics in alphabetical order.\n-- @usage help.topics()\nfunction topics()\n -- Add index\n local tItems = {\n ["index"] = true,\n }\n\n -- Add topics from the path\n for sPath in string.gmatch(sPath, "[^:]+") do\n if fs.isDir(sPath) then\n local tList = fs.list(sPath)\n for _, sFile in pairs(tList) do\n if string.sub(sFile, 1, 1) ~= "." then\n if not fs.isDir(fs.combine(sPath, sFile)) then\n for i = 2, #extensions do\n local extension = extensions[i]\n if #sFile > #extension and sFile:sub(-#extension) == extension then\n sFile = sFile:sub(1, -#extension - 1)\n end\n end\n tItems[sFile] = true\n end\n end\n end\n end\n end\n\n -- Sort and return\n local tItemList = {}\n for sItem in pairs(tItems) do\n table.insert(tItemList, sItem)\n end\n table.sort(tItemList)\n return tItemList\nend\n\n--- Returns a list of topic endings that match the prefix. Can be used with\n-- `read` to allow input of a help topic.\n--\n-- @tparam string prefix The prefix to match\n-- @treturn table A list of matching topics.\n-- @since 1.74\nfunction completeTopic(sText)\n expect(1, sText, "string")\n local tTopics = topics()\n local tResults = {}\n for n = 1, #tTopics do\n local sTopic = tTopics[n]\n if #sTopic > #sText and string.sub(sTopic, 1, #sText) == sText then\n table.insert(tResults, string.sub(sTopic, #sText + 1))\n end\n end\n return tResults\nend\n',"rom/apis/http/http.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[- Make HTTP requests, sending and receiving data to a remote web server.\n\n@module http\n@since 1.1\n@see local_ips To allow accessing servers running on your local network.\n]]\n\nlocal expect = dofile("rom/modules/main/cc/expect.lua").expect\n\nlocal native = http\nlocal nativeHTTPRequest = http.request\n\nlocal methods = {\n GET = true, POST = true, HEAD = true,\n OPTIONS = true, PUT = true, DELETE = true,\n PATCH = true, TRACE = true,\n}\n\nlocal function check_key(options, key, ty, opt)\n local value = options[key]\n local valueTy = type(value)\n\n if (value ~= nil or not opt) and valueTy ~= ty then\n error(("bad field \'%s\' (%s expected, got %s"):format(key, ty, valueTy), 4)\n end\nend\n\nlocal function check_request_options(options, body)\n check_key(options, "url", "string")\n if body == false then\n check_key(options, "body", "nil")\n else\n check_key(options, "body", "string", not body)\n end\n check_key(options, "headers", "table", true)\n check_key(options, "method", "string", true)\n check_key(options, "redirect", "boolean", true)\n check_key(options, "timeout", "number", true)\n\n if options.method and not methods[options.method] then\n error("Unsupported HTTP method", 3)\n end\nend\n\nlocal function wrap_request(_url, ...)\n local ok, err = nativeHTTPRequest(...)\n if ok then\n while true do\n local event, param1, param2, param3 = os.pullEvent()\n if event == "http_success" and param1 == _url then\n return param2\n elseif event == "http_failure" and param1 == _url then\n return nil, param2, param3\n end\n end\n end\n return nil, err\nend\n\n--[[- Make a HTTP GET request to the given url.\n\n@tparam string url The url to request\n@tparam[opt] { [string] = string } headers Additional headers to send as part\nof this request.\n@tparam[opt] boolean binary Whether to make a binary HTTP request. If true,\nthe body will not be UTF-8 encoded, and the received response will not be\ndecoded.\n\n@tparam[2] {\n url = string, headers? = { [string] = string },\n binary? = boolean, method? = string, redirect? = boolean,\n timeout? = number,\n} request Options for the request. See [`http.request`] for details on how\nthese options behave.\n\n@treturn Response The resulting http response, which can be read from.\n@treturn[2] nil When the http request failed, such as in the event of a 404\nerror or connection timeout.\n@treturn string A message detailing why the request failed.\n@treturn Response|nil The failing http response, if available.\n\n@changed 1.63 Added argument for headers.\n@changed 1.80pr1 Response handles are now returned on error if available.\n@changed 1.80pr1 Added argument for binary handles.\n@changed 1.80pr1.6 Added support for table argument.\n@changed 1.86.0 Added PATCH and TRACE methods.\n@changed 1.105.0 Added support for custom timeouts.\n\n@usage Make a request to [example.tweaked.cc](https://example.tweaked.cc),\nand print the returned page.\n\n```lua\nlocal request = http.get("https://example.tweaked.cc")\nprint(request.readAll())\n-- => HTTP is working!\nrequest.close()\n```\n]]\nfunction get(_url, _headers, _binary)\n if type(_url) == "table" then\n check_request_options(_url, false)\n return wrap_request(_url.url, _url)\n end\n\n expect(1, _url, "string")\n expect(2, _headers, "table", "nil")\n expect(3, _binary, "boolean", "nil")\n return wrap_request(_url, _url, nil, _headers, _binary)\nend\n\n--[[- Make a HTTP POST request to the given url.\n\n@tparam string url The url to request\n@tparam string body The body of the POST request.\n@tparam[opt] { [string] = string } headers Additional headers to send as part\nof this request.\n@tparam[opt] boolean binary Whether to make a binary HTTP request. If true,\nthe body will not be UTF-8 encoded, and the received response will not be\ndecoded.\n\n@tparam[2] {\n url = string, body? = string, headers? = { [string] = string },\n binary? = boolean, method? = string, redirect? = boolean,\n timeout? = number,\n} request Options for the request. See [`http.request`] for details on how\nthese options behave.\n\n@treturn Response The resulting http response, which can be read from.\n@treturn[2] nil When the http request failed, such as in the event of a 404\nerror or connection timeout.\n@treturn string A message detailing why the request failed.\n@treturn Response|nil The failing http response, if available.\n\n@since 1.31\n@changed 1.63 Added argument for headers.\n@changed 1.80pr1 Response handles are now returned on error if available.\n@changed 1.80pr1 Added argument for binary handles.\n@changed 1.80pr1.6 Added support for table argument.\n@changed 1.86.0 Added PATCH and TRACE methods.\n@changed 1.105.0 Added support for custom timeouts.\n]]\nfunction post(_url, _post, _headers, _binary)\n if type(_url) == "table" then\n check_request_options(_url, true)\n return wrap_request(_url.url, _url)\n end\n\n expect(1, _url, "string")\n expect(2, _post, "string")\n expect(3, _headers, "table", "nil")\n expect(4, _binary, "boolean", "nil")\n return wrap_request(_url, _url, _post, _headers, _binary)\nend\n\n--[[- Asynchronously make a HTTP request to the given url.\n\nThis returns immediately, a [`http_success`] or [`http_failure`] will be queued\nonce the request has completed.\n\n@tparam string url The url to request\n@tparam[opt] string body An optional string containing the body of the\nrequest. If specified, a `POST` request will be made instead.\n@tparam[opt] { [string] = string } headers Additional headers to send as part\nof this request.\n@tparam[opt] boolean binary Whether to make a binary HTTP request. If true,\nthe body will not be UTF-8 encoded, and the received response will not be\ndecoded.\n\n@tparam[2] {\n url = string, body? = string, headers? = { [string] = string },\n binary? = boolean, method? = string, redirect? = boolean,\n timeout? = number,\n} request Options for the request.\n\nThis table form is an expanded version of the previous syntax. All arguments\nfrom above are passed in as fields instead (for instance,\n`http.request("https://example.com")` becomes `http.request { url =\n"https://example.com" }`).\n This table also accepts several additional options:\n\n - `method`: Which HTTP method to use, for instance `"PATCH"` or `"DELETE"`.\n - `redirect`: Whether to follow HTTP redirects. Defaults to true.\n - `timeout`: The connection timeout, in seconds.\n\n@see http.get For a synchronous way to make GET requests.\n@see http.post For a synchronous way to make POST requests.\n\n@changed 1.63 Added argument for headers.\n@changed 1.80pr1 Added argument for binary handles.\n@changed 1.80pr1.6 Added support for table argument.\n@changed 1.86.0 Added PATCH and TRACE methods.\n@changed 1.105.0 Added support for custom timeouts.\n]]\nfunction request(_url, _post, _headers, _binary)\n local url\n if type(_url) == "table" then\n check_request_options(_url)\n url = _url.url\n else\n expect(1, _url, "string")\n expect(2, _post, "string", "nil")\n expect(3, _headers, "table", "nil")\n expect(4, _binary, "boolean", "nil")\n url = _url\n end\n\n local ok, err = nativeHTTPRequest(_url, _post, _headers, _binary)\n if not ok then\n os.queueEvent("http_failure", url, err)\n end\n\n -- Return true/false for legacy reasons. Undocumented, as it shouldn\'t be relied on.\n return ok, err\nend\n\nlocal nativeCheckURL = native.checkURL\n\n--[[- Asynchronously determine whether a URL can be requested.\n\nIf this returns `true`, one should also listen for [`http_check`] which will\ncontainer further information about whether the URL is allowed or not.\n\n@tparam string url The URL to check.\n@treturn true When this url is not invalid. This does not imply that it is\nallowed - see the comment above.\n@treturn[2] false When this url is invalid.\n@treturn string A reason why this URL is not valid (for instance, if it is\nmalformed, or blocked).\n\n@see http.checkURL For a synchronous version.\n]]\ncheckURLAsync = nativeCheckURL\n\n--[[- Determine whether a URL can be requested.\n\nIf this returns `true`, one should also listen for [`http_check`] which will\ncontainer further information about whether the URL is allowed or not.\n\n@tparam string url The URL to check.\n@treturn true When this url is valid and can be requested via [`http.request`].\n@treturn[2] false When this url is invalid.\n@treturn string A reason why this URL is not valid (for instance, if it is\nmalformed, or blocked).\n\n@see http.checkURLAsync For an asynchronous version.\n\n@usage\n```lua\nprint(http.checkURL("https://example.tweaked.cc/"))\n-- => true\nprint(http.checkURL("http://localhost/"))\n-- => false Domain not permitted\nprint(http.checkURL("not a url"))\n-- => false URL malformed\n```\n]]\nfunction checkURL(_url)\n expect(1, _url, "string")\n local ok, err = nativeCheckURL(_url)\n if not ok then return ok, err end\n\n while true do\n local _, url, ok, err = os.pullEvent("http_check")\n if url == _url then return ok, err end\n end\nend\n\nlocal nativeWebsocket = native.websocket\n\nlocal function check_websocket_options(options, body)\n check_key(options, "url", "string")\n check_key(options, "headers", "table", true)\n check_key(options, "timeout", "number", true)\nend\n\n\n--[[- Asynchronously open a websocket.\n\nThis returns immediately, a [`websocket_success`] or [`websocket_failure`]\nwill be queued once the request has completed.\n\n@tparam[1] string url The websocket url to connect to. This should have the\n`ws://` or `wss://` protocol.\n@tparam[1, opt] { [string] = string } headers Additional headers to send as part\nof the initial websocket connection.\n\n@tparam[2] {\n url = string, headers? = { [string] = string }, timeout ?= number,\n} request Options for the websocket. See [`http.websocket`] for details on how\nthese options behave.\n\n@since 1.80pr1.3\n@changed 1.95.3 Added User-Agent to default headers.\n@changed 1.105.0 Added support for table argument and custom timeout.\n@see websocket_success\n@see websocket_failure\n]]\nfunction websocketAsync(url, headers)\n local actual_url\n if type(url) == "table" then\n check_websocket_options(url)\n actual_url = url.url\n else\n expect(1, url, "string")\n expect(2, headers, "table", "nil")\n actual_url = url\n end\n\n local ok, err = nativeWebsocket(url, headers)\n if not ok then\n os.queueEvent("websocket_failure", actual_url, err)\n end\n\n -- Return true/false for legacy reasons. Undocumented, as it shouldn\'t be relied on.\n return ok, err\nend\n\n--[[- Open a websocket.\n\n@tparam[1] string url The websocket url to connect to. This should have the\n`ws://` or `wss://` protocol.\n@tparam[1,opt] { [string] = string } headers Additional headers to send as part\nof the initial websocket connection.\n\n@tparam[2] {\n url = string, headers? = { [string] = string }, timeout ?= number,\n} request Options for the websocket.\n\nThis table form is an expanded version of the previous syntax. All arguments\nfrom above are passed in as fields instead (for instance,\n`http.websocket("https://example.com")` becomes `http.websocket { url =\n"https://example.com" }`).\n This table also accepts the following additional options:\n\n - `timeout`: The connection timeout, in seconds.\n\n@treturn Websocket The websocket connection.\n@treturn[2] false If the websocket connection failed.\n@treturn string An error message describing why the connection failed.\n\n@since 1.80pr1.1\n@changed 1.80pr1.3 No longer asynchronous.\n@changed 1.95.3 Added User-Agent to default headers.\n@changed 1.105.0 Added support for table argument and custom timeout.\n\n@usage Connect to an echo websocket and send a message.\n\n local ws = assert(http.websocket("wss://example.tweaked.cc/echo"))\n ws.send("Hello!") -- Send a message\n print(ws.receive()) -- And receive the reply\n ws.close()\n\n]]\nfunction websocket(url, headers)\n local actual_url\n if type(url) == "table" then\n check_websocket_options(url)\n actual_url = url.url\n else\n expect(1, url, "string")\n expect(2, headers, "table", "nil")\n actual_url = url\n end\n\n local ok, err = nativeWebsocket(url, headers)\n if not ok then return ok, err end\n\n while true do\n local event, url, param = os.pullEvent( )\n if event == "websocket_success" and url == actual_url then\n return param\n elseif event == "websocket_failure" and url == actual_url then\n return false, param\n end\n end\nend\n',"rom/apis/io.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--- Emulates Lua\'s standard [io library][io].\n--\n-- [io]: https://www.lua.org/manual/5.1/manual.html#5.7\n--\n-- @module io\n\nlocal expect, type_of = dofile("rom/modules/main/cc/expect.lua").expect, _G.type\n\n--- If we return nil then close the file, as we\'ve reached the end.\n-- We use this weird wrapper function as we wish to preserve the varargs\nlocal function checkResult(handle, ...)\n if ... == nil and handle._autoclose and not handle._closed then handle:close() end\n return ...\nend\n\n--- A file handle which can be read or written to.\n--\n-- @type Handle\nlocal handleMetatable\nhandleMetatable = {\n __name = "FILE*",\n __tostring = function(self)\n if self._closed then\n return "file (closed)"\n else\n local hash = tostring(self._handle):match("table: (%x+)")\n return "file (" .. hash .. ")"\n end\n end,\n\n __index = {\n --- Close this file handle, freeing any resources it uses.\n --\n -- @treturn[1] true If this handle was successfully closed.\n -- @treturn[2] nil If this file handle could not be closed.\n -- @treturn[2] string The reason it could not be closed.\n -- @throws If this handle was already closed.\n close = function(self)\n if type_of(self) ~= "table" or getmetatable(self) ~= handleMetatable then\n error("bad argument #1 (FILE expected, got " .. type_of(self) .. ")", 2)\n end\n if self._closed then error("attempt to use a closed file", 2) end\n\n local handle = self._handle\n if handle.close then\n self._closed = true\n handle.close()\n return true\n else\n return nil, "attempt to close standard stream"\n end\n end,\n\n --- Flush any buffered output, forcing it to be written to the file\n --\n -- @throws If the handle has been closed\n flush = function(self)\n if type_of(self) ~= "table" or getmetatable(self) ~= handleMetatable then\n error("bad argument #1 (FILE expected, got " .. type_of(self) .. ")", 2)\n end\n if self._closed then error("attempt to use a closed file", 2) end\n\n local handle = self._handle\n if handle.flush then handle.flush() end\n return true\n end,\n\n --[[- Returns an iterator that, each time it is called, returns a new\n line from the file.\n\n This can be used in a for loop to iterate over all lines of a file\n\n Once the end of the file has been reached, [`nil`] will be returned. The file is\n *not* automatically closed.\n\n @param ... The argument to pass to [`Handle:read`] for each line.\n @treturn function():string|nil The line iterator.\n @throws If the file cannot be opened for reading\n @since 1.3\n\n @see io.lines\n @usage Iterate over every line in a file and print it out.\n\n ```lua\n local file = io.open("/rom/help/intro.txt")\n for line in file:lines() do\n print(line)\n end\n file:close()\n ```\n ]]\n lines = function(self, ...)\n if type_of(self) ~= "table" or getmetatable(self) ~= handleMetatable then\n error("bad argument #1 (FILE expected, got " .. type_of(self) .. ")", 2)\n end\n if self._closed then error("attempt to use a closed file", 2) end\n\n local handle = self._handle\n if not handle.read then return nil, "file is not readable" end\n\n local args = table.pack(...)\n return function()\n if self._closed then error("file is already closed", 2) end\n return checkResult(self, self:read(table.unpack(args, 1, args.n)))\n end\n end,\n\n --[[- Reads data from the file, using the specified formats. For each\n format provided, the function returns either the data read, or `nil` if\n no data could be read.\n\n The following formats are available:\n - `l`: Returns the next line (without a newline on the end).\n - `L`: Returns the next line (with a newline on the end).\n - `a`: Returns the entire rest of the file.\n - ~~`n`: Returns a number~~ (not implemented in CC).\n\n These formats can be preceded by a `*` to make it compatible with Lua 5.1.\n\n If no format is provided, `l` is assumed.\n\n @param ... The formats to use.\n @treturn (string|nil)... The data read from the file.\n ]]\n read = function(self, ...)\n if type_of(self) ~= "table" or getmetatable(self) ~= handleMetatable then\n error("bad argument #1 (FILE expected, got " .. type_of(self) .. ")", 2)\n end\n if self._closed then error("attempt to use a closed file", 2) end\n\n local handle = self._handle\n if not handle.read and not handle.readLine then return nil, "Not opened for reading" end\n\n local n = select("#", ...)\n local output = {}\n for i = 1, n do\n local arg = select(i, ...)\n local res\n if type_of(arg) == "number" then\n if handle.read then res = handle.read(arg) end\n elseif type_of(arg) == "string" then\n local format = arg:gsub("^%*", ""):sub(1, 1)\n\n if format == "l" then\n if handle.readLine then res = handle.readLine() end\n elseif format == "L" and handle.readLine then\n if handle.readLine then res = handle.readLine(true) end\n elseif format == "a" then\n if handle.readAll then res = handle.readAll() or "" end\n elseif format == "n" then\n res = nil -- Skip this format as we can\'t really handle it\n else\n error("bad argument #" .. i .. " (invalid format)", 2)\n end\n else\n error("bad argument #" .. i .. " (string expected, got " .. type_of(arg) .. ")", 2)\n end\n\n output[i] = res\n if not res then break end\n end\n\n -- Default to "l" if possible\n if n == 0 and handle.readLine then return handle.readLine() end\n return table.unpack(output, 1, n)\n end,\n\n --[[- Seeks the file cursor to the specified position, and returns the\n new position.\n\n `whence` controls where the seek operation starts, and is a string that\n may be one of these three values:\n - `set`: base position is 0 (beginning of the file)\n - `cur`: base is current position\n - `end`: base is end of file\n\n The default value of `whence` is `cur`, and the default value of `offset`\n is 0. This means that `file:seek()` without arguments returns the current\n position without moving.\n\n @tparam[opt] string whence The place to set the cursor from.\n @tparam[opt] number offset The offset from the start to move to.\n @treturn number The new location of the file cursor.\n ]]\n seek = function(self, whence, offset)\n if type_of(self) ~= "table" or getmetatable(self) ~= handleMetatable then\n error("bad argument #1 (FILE expected, got " .. type_of(self) .. ")", 2)\n end\n if self._closed then error("attempt to use a closed file", 2) end\n\n local handle = self._handle\n if not handle.seek then return nil, "file is not seekable" end\n\n -- It\'s a tail call, so error positions are preserved\n return handle.seek(whence, offset)\n end,\n\n --[[- Sets the buffering mode for an output file.\n\n This has no effect under ComputerCraft, and exists with compatility\n with base Lua.\n @tparam string mode The buffering mode.\n @tparam[opt] number size The size of the buffer.\n @see file:setvbuf Lua\'s documentation for `setvbuf`.\n @deprecated This has no effect in CC.\n ]]\n setvbuf = function(self, mode, size) end,\n\n --- Write one or more values to the file\n --\n -- @tparam string|number ... The values to write.\n -- @treturn[1] Handle The current file, allowing chained calls.\n -- @treturn[2] nil If the file could not be written to.\n -- @treturn[2] string The error message which occurred while writing.\n -- @changed 1.81.0 Multiple arguments are now allowed.\n write = function(self, ...)\n if type_of(self) ~= "table" or getmetatable(self) ~= handleMetatable then\n error("bad argument #1 (FILE expected, got " .. type_of(self) .. ")", 2)\n end\n if self._closed then error("attempt to use a closed file", 2) end\n\n local handle = self._handle\n if not handle.write then return nil, "file is not writable" end\n\n for i = 1, select("#", ...) do\n local arg = select(i, ...)\n expect(i, arg, "string", "number")\n handle.write(arg)\n end\n return self\n end,\n },\n}\n\nlocal function make_file(handle)\n return setmetatable({ _handle = handle }, handleMetatable)\nend\n\nlocal defaultInput = make_file({ readLine = _G.read })\n\nlocal defaultOutput = make_file({ write = _G.write })\n\nlocal defaultError = make_file({\n write = function(...)\n local oldColour\n if term.isColour() then\n oldColour = term.getTextColour()\n term.setTextColour(colors.red)\n end\n _G.write(...)\n if term.isColour() then term.setTextColour(oldColour) end\n end,\n})\n\nlocal currentInput = defaultInput\nlocal currentOutput = defaultOutput\n\n--- A file handle representing the "standard input". Reading from this\n-- file will prompt the user for input.\nstdin = defaultInput\n\n--- A file handle representing the "standard output". Writing to this\n-- file will display the written text to the screen.\nstdout = defaultOutput\n\n--- A file handle representing the "standard error" stream.\n--\n-- One may use this to display error messages, writing to it will display\n-- them on the terminal.\nstderr = defaultError\n\n--- Closes the provided file handle.\n--\n-- @tparam[opt] Handle file The file handle to close, defaults to the\n-- current output file.\n--\n-- @see Handle:close\n-- @see io.output\n-- @since 1.55\nfunction close(file)\n if file == nil then return currentOutput:close() end\n\n if type_of(file) ~= "table" or getmetatable(file) ~= handleMetatable then\n error("bad argument #1 (FILE expected, got " .. type_of(file) .. ")", 2)\n end\n return file:close()\nend\n\n--- Flushes the current output file.\n--\n-- @see Handle:flush\n-- @see io.output\n-- @since 1.55\nfunction flush()\n return currentOutput:flush()\nend\n\n--- Get or set the current input file.\n--\n-- @tparam[opt] Handle|string file The new input file, either as a file path or pre-existing handle.\n-- @treturn Handle The current input file.\n-- @throws If the provided filename cannot be opened for reading.\n-- @since 1.55\nfunction input(file)\n if type_of(file) == "string" then\n local res, err = open(file, "rb")\n if not res then error(err, 2) end\n currentInput = res\n elseif type_of(file) == "table" and getmetatable(file) == handleMetatable then\n currentInput = file\n elseif file ~= nil then\n error("bad fileument #1 (FILE expected, got " .. type_of(file) .. ")", 2)\n end\n\n return currentInput\nend\n\n--[[- Opens the given file name in read mode and returns an iterator that,\neach time it is called, returns a new line from the file.\n\nThis can be used in a for loop to iterate over all lines of a file\n\nOnce the end of the file has been reached, [`nil`] will be returned. The file is\nautomatically closed.\n\nIf no file name is given, the [current input][`io.input`] will be used instead.\nIn this case, the handle is not used.\n\n@tparam[opt] string filename The name of the file to extract lines from\n@param ... The argument to pass to [`Handle:read`] for each line.\n@treturn function():string|nil The line iterator.\n@throws If the file cannot be opened for reading\n\n@see Handle:lines\n@see io.input\n@since 1.55\n@usage Iterate over every line in a file and print it out.\n\n```lua\nfor line in io.lines("/rom/help/intro.txt") do\n print(line)\nend\n```\n]]\nfunction lines(filename, ...)\n expect(1, filename, "string", "nil")\n if filename then\n local ok, err = open(filename, "rb")\n if not ok then error(err, 2) end\n\n -- We set this magic flag to mark this file as being opened by io.lines and so should be\n -- closed automatically\n ok._autoclose = true\n return ok:lines(...)\n else\n return currentInput:lines(...)\n end\nend\n\n--- Open a file with the given mode, either returning a new file handle\n-- or [`nil`], plus an error message.\n--\n-- The `mode` string can be any of the following:\n-- - **"r"**: Read mode\n-- - **"w"**: Write mode\n-- - **"a"**: Append mode\n--\n-- The mode may also have a `b` at the end, which opens the file in "binary\n-- mode". This allows you to read binary files, as well as seek within a file.\n--\n-- @tparam string filename The name of the file to open.\n-- @tparam[opt] string mode The mode to open the file with. This defaults to `rb`.\n-- @treturn[1] Handle The opened file.\n-- @treturn[2] nil In case of an error.\n-- @treturn[2] string The reason the file could not be opened.\nfunction open(filename, mode)\n expect(1, filename, "string")\n expect(2, mode, "string", "nil")\n\n local sMode = mode and mode:gsub("%+", "") or "rb"\n local file, err = fs.open(filename, sMode)\n if not file then return nil, err end\n\n return make_file(file)\nend\n\n--- Get or set the current output file.\n--\n-- @tparam[opt] Handle|string file The new output file, either as a file path or pre-existing handle.\n-- @treturn Handle The current output file.\n-- @throws If the provided filename cannot be opened for writing.\n-- @since 1.55\nfunction output(file)\n if type_of(file) == "string" then\n local res, err = open(file, "wb")\n if not res then error(err, 2) end\n currentOutput = res\n elseif type_of(file) == "table" and getmetatable(file) == handleMetatable then\n currentOutput = file\n elseif file ~= nil then\n error("bad argument #1 (FILE expected, got " .. type_of(file) .. ")", 2)\n end\n\n return currentOutput\nend\n\n--- Read from the currently opened input file.\n--\n-- This is equivalent to `io.input():read(...)`. See [the documentation][`Handle:read`]\n-- there for full details.\n--\n-- @tparam string ... The formats to read, defaulting to a whole line.\n-- @treturn (string|nil)... The data read, or [`nil`] if nothing can be read.\nfunction read(...)\n return currentInput:read(...)\nend\n\n--- Checks whether `handle` is a given file handle, and determine if it is open\n-- or not.\n--\n-- @param obj The value to check\n-- @treturn string|nil `"file"` if this is an open file, `"closed file"` if it\n-- is a closed file handle, or `nil` if not a file handle.\nfunction type(obj)\n if type_of(obj) == "table" and getmetatable(obj) == handleMetatable then\n if obj._closed then\n return "closed file"\n else\n return "file"\n end\n end\n return nil\nend\n\n--- Write to the currently opened output file.\n--\n-- This is equivalent to `io.output():write(...)`. See [the documentation][`Handle:write`]\n-- there for full details.\n--\n-- @tparam string ... The strings to write\n-- @changed 1.81.0 Multiple arguments are now allowed.\nfunction write(...)\n return currentOutput:write(...)\nend\n',"rom/apis/keys.lua":"-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--- Constants for all keyboard \"key codes\", as queued by the [`key`] event.\n--\n-- These values are not guaranteed to remain the same between versions. It is\n-- recommended that you use the constants provided by this file, rather than\n-- the underlying numerical values.\n--\n-- @module keys\n-- @since 1.4\n\nlocal expect = dofile(\"rom/modules/main/cc/expect.lua\").expect\n\nlocal tKeys = {}\ntKeys[32] = 'space'\ntKeys[39] = 'apostrophe'\ntKeys[44] = 'comma'\ntKeys[45] = 'minus'\ntKeys[46] = 'period'\ntKeys[47] = 'slash'\ntKeys[48] = 'zero'\ntKeys[49] = 'one'\ntKeys[50] = 'two'\ntKeys[51] = 'three'\ntKeys[52] = 'four'\ntKeys[53] = 'five'\ntKeys[54] = 'six'\ntKeys[55] = 'seven'\ntKeys[56] = 'eight'\ntKeys[57] = 'nine'\ntKeys[59] = 'semicolon'\ntKeys[61] = 'equals'\ntKeys[65] = 'a'\ntKeys[66] = 'b'\ntKeys[67] = 'c'\ntKeys[68] = 'd'\ntKeys[69] = 'e'\ntKeys[70] = 'f'\ntKeys[71] = 'g'\ntKeys[72] = 'h'\ntKeys[73] = 'i'\ntKeys[74] = 'j'\ntKeys[75] = 'k'\ntKeys[76] = 'l'\ntKeys[77] = 'm'\ntKeys[78] = 'n'\ntKeys[79] = 'o'\ntKeys[80] = 'p'\ntKeys[81] = 'q'\ntKeys[82] = 'r'\ntKeys[83] = 's'\ntKeys[84] = 't'\ntKeys[85] = 'u'\ntKeys[86] = 'v'\ntKeys[87] = 'w'\ntKeys[88] = 'x'\ntKeys[89] = 'y'\ntKeys[90] = 'z'\ntKeys[91] = 'leftBracket'\ntKeys[92] = 'backslash'\ntKeys[93] = 'rightBracket'\ntKeys[96] = 'grave'\n-- tKeys[161] = 'world1'\n-- tKeys[162] = 'world2'\ntKeys[257] = 'enter'\ntKeys[258] = 'tab'\ntKeys[259] = 'backspace'\ntKeys[260] = 'insert'\ntKeys[261] = 'delete'\ntKeys[262] = 'right'\ntKeys[263] = 'left'\ntKeys[264] = 'down'\ntKeys[265] = 'up'\ntKeys[266] = 'pageUp'\ntKeys[267] = 'pageDown'\ntKeys[268] = 'home'\ntKeys[269] = 'end'\ntKeys[280] = 'capsLock'\ntKeys[281] = 'scrollLock'\ntKeys[282] = 'numLock'\ntKeys[283] = 'printScreen'\ntKeys[284] = 'pause'\ntKeys[290] = 'f1'\ntKeys[291] = 'f2'\ntKeys[292] = 'f3'\ntKeys[293] = 'f4'\ntKeys[294] = 'f5'\ntKeys[295] = 'f6'\ntKeys[296] = 'f7'\ntKeys[297] = 'f8'\ntKeys[298] = 'f9'\ntKeys[299] = 'f10'\ntKeys[300] = 'f11'\ntKeys[301] = 'f12'\ntKeys[302] = 'f13'\ntKeys[303] = 'f14'\ntKeys[304] = 'f15'\ntKeys[305] = 'f16'\ntKeys[306] = 'f17'\ntKeys[307] = 'f18'\ntKeys[308] = 'f19'\ntKeys[309] = 'f20'\ntKeys[310] = 'f21'\ntKeys[311] = 'f22'\ntKeys[312] = 'f23'\ntKeys[313] = 'f24'\ntKeys[314] = 'f25'\ntKeys[320] = 'numPad0'\ntKeys[321] = 'numPad1'\ntKeys[322] = 'numPad2'\ntKeys[323] = 'numPad3'\ntKeys[324] = 'numPad4'\ntKeys[325] = 'numPad5'\ntKeys[326] = 'numPad6'\ntKeys[327] = 'numPad7'\ntKeys[328] = 'numPad8'\ntKeys[329] = 'numPad9'\ntKeys[330] = 'numPadDecimal'\ntKeys[331] = 'numPadDivide'\ntKeys[332] = 'numPadMultiply'\ntKeys[333] = 'numPadSubtract'\ntKeys[334] = 'numPadAdd'\ntKeys[335] = 'numPadEnter'\ntKeys[336] = 'numPadEqual'\ntKeys[340] = 'leftShift'\ntKeys[341] = 'leftCtrl'\ntKeys[342] = 'leftAlt'\ntKeys[343] = 'leftSuper'\ntKeys[344] = 'rightShift'\ntKeys[345] = 'rightCtrl'\ntKeys[346] = 'rightAlt'\n-- tKeys[347] = 'rightSuper'\ntKeys[348] = 'menu'\n\nlocal keys = _ENV\nfor nKey, sKey in pairs(tKeys) do\n keys[sKey] = nKey\nend\n\n-- Alias some keys for ease-of-use and backwards compatibility\nkeys[\"return\"] = keys.enter --- @local\nkeys.scollLock = keys.scrollLock --- @local\nkeys.cimcumflex = keys.circumflex --- @local\n\n--- Translates a numerical key code to a human-readable name. The human-readable\n-- name is one of the constants in the keys API.\n--\n-- @tparam number code The key code to look up.\n-- @treturn string|nil The name of the key, or `nil` if not a valid key code.\n-- @usage keys.getName(keys.enter)\nfunction getName(_nKey)\n expect(1, _nKey, \"number\")\n return tKeys[_nKey]\nend\n","rom/apis/paintutils.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--- Utilities for drawing more complex graphics, such as pixels, lines and\n-- images.\n--\n-- @module paintutils\n-- @since 1.45\n\nlocal expect = dofile("rom/modules/main/cc/expect.lua").expect\n\nlocal function drawPixelInternal(xPos, yPos)\n term.setCursorPos(xPos, yPos)\n term.write(" ")\nend\n\nlocal tColourLookup = {}\nfor n = 1, 16 do\n tColourLookup[string.byte("0123456789abcdef", n, n)] = 2 ^ (n - 1)\nend\n\nlocal function parseLine(tImageArg, sLine)\n local tLine = {}\n for x = 1, sLine:len() do\n tLine[x] = tColourLookup[string.byte(sLine, x, x)] or 0\n end\n table.insert(tImageArg, tLine)\nend\n\n-- Sorts pairs of startX/startY/endX/endY such that the start is always the min\nlocal function sortCoords(startX, startY, endX, endY)\n local minX, maxX, minY, maxY\n\n if startX <= endX then\n minX, maxX = startX, endX\n else\n minX, maxX = endX, startX\n end\n\n if startY <= endY then\n minY, maxY = startY, endY\n else\n minY, maxY = endY, startY\n end\n\n return minX, maxX, minY, maxY\nend\n\n--- Parses an image from a multi-line string\n--\n-- @tparam string image The string containing the raw-image data.\n-- @treturn table The parsed image data, suitable for use with\n-- [`paintutils.drawImage`].\n-- @since 1.80pr1\nfunction parseImage(image)\n expect(1, image, "string")\n local tImage = {}\n for sLine in (image .. "\\n"):gmatch("(.-)\\n") do\n parseLine(tImage, sLine)\n end\n return tImage\nend\n\n--- Loads an image from a file.\n--\n-- You can create a file suitable for being loaded using the `paint` program.\n--\n-- @tparam string path The file to load.\n--\n-- @treturn table|nil The parsed image data, suitable for use with\n-- [`paintutils.drawImage`], or `nil` if the file does not exist.\n-- @usage Load an image and draw it.\n--\n-- local image = paintutils.loadImage("data/example.nfp")\n-- paintutils.drawImage(image, term.getCursorPos())\nfunction loadImage(path)\n expect(1, path, "string")\n\n if fs.exists(path) then\n local file = io.open(path, "r")\n local sContent = file:read("*a")\n file:close()\n return parseImage(sContent)\n end\n return nil\nend\n\n--- Draws a single pixel to the current term at the specified position.\n--\n-- Be warned, this may change the position of the cursor and the current\n-- background colour. You should not expect either to be preserved.\n--\n-- @tparam number xPos The x position to draw at, where 1 is the far left.\n-- @tparam number yPos The y position to draw at, where 1 is the very top.\n-- @tparam[opt] number colour The [color][`colors`] of this pixel. This will be\n-- the current background colour if not specified.\nfunction drawPixel(xPos, yPos, colour)\n expect(1, xPos, "number")\n expect(2, yPos, "number")\n expect(3, colour, "number", "nil")\n\n if colour then\n term.setBackgroundColor(colour)\n end\n return drawPixelInternal(xPos, yPos)\nend\n\n--- Draws a straight line from the start to end position.\n--\n-- Be warned, this may change the position of the cursor and the current\n-- background colour. You should not expect either to be preserved.\n--\n-- @tparam number startX The starting x position of the line.\n-- @tparam number startY The starting y position of the line.\n-- @tparam number endX The end x position of the line.\n-- @tparam number endY The end y position of the line.\n-- @tparam[opt] number colour The [color][`colors`] of this pixel. This will be\n-- the current background colour if not specified.\n-- @usage paintutils.drawLine(2, 3, 30, 7, colors.red)\nfunction drawLine(startX, startY, endX, endY, colour)\n expect(1, startX, "number")\n expect(2, startY, "number")\n expect(3, endX, "number")\n expect(4, endY, "number")\n expect(5, colour, "number", "nil")\n\n startX = math.floor(startX)\n startY = math.floor(startY)\n endX = math.floor(endX)\n endY = math.floor(endY)\n\n if colour then\n term.setBackgroundColor(colour)\n end\n if startX == endX and startY == endY then\n drawPixelInternal(startX, startY)\n return\n end\n\n local minX = math.min(startX, endX)\n local maxX, minY, maxY\n if minX == startX then\n minY = startY\n maxX = endX\n maxY = endY\n else\n minY = endY\n maxX = startX\n maxY = startY\n end\n\n -- TODO: clip to screen rectangle?\n\n local xDiff = maxX - minX\n local yDiff = maxY - minY\n\n if xDiff > math.abs(yDiff) then\n local y = minY\n local dy = yDiff / xDiff\n for x = minX, maxX do\n drawPixelInternal(x, math.floor(y + 0.5))\n y = y + dy\n end\n else\n local x = minX\n local dx = xDiff / yDiff\n if maxY >= minY then\n for y = minY, maxY do\n drawPixelInternal(math.floor(x + 0.5), y)\n x = x + dx\n end\n else\n for y = minY, maxY, -1 do\n drawPixelInternal(math.floor(x + 0.5), y)\n x = x - dx\n end\n end\n end\nend\n\n--- Draws the outline of a box on the current term from the specified start\n-- position to the specified end position.\n--\n-- Be warned, this may change the position of the cursor and the current\n-- background colour. You should not expect either to be preserved.\n--\n-- @tparam number startX The starting x position of the line.\n-- @tparam number startY The starting y position of the line.\n-- @tparam number endX The end x position of the line.\n-- @tparam number endY The end y position of the line.\n-- @tparam[opt] number colour The [color][`colors`] of this pixel. This will be\n-- the current background colour if not specified.\n-- @usage paintutils.drawBox(2, 3, 30, 7, colors.red)\nfunction drawBox(startX, startY, endX, endY, nColour)\n expect(1, startX, "number")\n expect(2, startY, "number")\n expect(3, endX, "number")\n expect(4, endY, "number")\n expect(5, nColour, "number", "nil")\n\n startX = math.floor(startX)\n startY = math.floor(startY)\n endX = math.floor(endX)\n endY = math.floor(endY)\n\n if nColour then\n term.setBackgroundColor(nColour) -- Maintain legacy behaviour\n else\n nColour = term.getBackgroundColour()\n end\n local colourHex = colours.toBlit(nColour)\n\n if startX == endX and startY == endY then\n drawPixelInternal(startX, startY)\n return\n end\n\n local minX, maxX, minY, maxY = sortCoords(startX, startY, endX, endY)\n local width = maxX - minX + 1\n\n for y = minY, maxY do\n if y == minY or y == maxY then\n term.setCursorPos(minX, y)\n term.blit((" "):rep(width), colourHex:rep(width), colourHex:rep(width))\n else\n term.setCursorPos(minX, y)\n term.blit(" ", colourHex, colourHex)\n term.setCursorPos(maxX, y)\n term.blit(" ", colourHex, colourHex)\n end\n end\nend\n\n--- Draws a filled box on the current term from the specified start position to\n-- the specified end position.\n--\n-- Be warned, this may change the position of the cursor and the current\n-- background colour. You should not expect either to be preserved.\n--\n-- @tparam number startX The starting x position of the line.\n-- @tparam number startY The starting y position of the line.\n-- @tparam number endX The end x position of the line.\n-- @tparam number endY The end y position of the line.\n-- @tparam[opt] number colour The [color][`colors`] of this pixel. This will be\n-- the current background colour if not specified.\n-- @usage paintutils.drawFilledBox(2, 3, 30, 7, colors.red)\nfunction drawFilledBox(startX, startY, endX, endY, nColour)\n expect(1, startX, "number")\n expect(2, startY, "number")\n expect(3, endX, "number")\n expect(4, endY, "number")\n expect(5, nColour, "number", "nil")\n\n startX = math.floor(startX)\n startY = math.floor(startY)\n endX = math.floor(endX)\n endY = math.floor(endY)\n\n if nColour then\n term.setBackgroundColor(nColour) -- Maintain legacy behaviour\n else\n nColour = term.getBackgroundColour()\n end\n local colourHex = colours.toBlit(nColour)\n\n if startX == endX and startY == endY then\n drawPixelInternal(startX, startY)\n return\n end\n\n local minX, maxX, minY, maxY = sortCoords(startX, startY, endX, endY)\n local width = maxX - minX + 1\n\n for y = minY, maxY do\n term.setCursorPos(minX, y)\n term.blit((" "):rep(width), colourHex:rep(width), colourHex:rep(width))\n end\nend\n\n--- Draw an image loaded by [`paintutils.parseImage`] or [`paintutils.loadImage`].\n--\n-- @tparam table image The parsed image data.\n-- @tparam number xPos The x position to start drawing at.\n-- @tparam number yPos The y position to start drawing at.\nfunction drawImage(image, xPos, yPos)\n expect(1, image, "table")\n expect(2, xPos, "number")\n expect(3, yPos, "number")\n for y = 1, #image do\n local tLine = image[y]\n for x = 1, #tLine do\n if tLine[x] > 0 then\n term.setBackgroundColor(tLine[x])\n drawPixelInternal(x + xPos - 1, y + yPos - 1)\n end\n end\n end\nend\n',"rom/apis/parallel.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[- A simple way to run several functions at once.\n\nFunctions are not actually executed simultaneously, but rather this API will\nautomatically switch between them whenever they yield (e.g. whenever they call\n[`coroutine.yield`], or functions that call that - such as [`os.pullEvent`] - or\nfunctions that call that, etc - basically, anything that causes the function\nto "pause").\n\nEach function executed in "parallel" gets its own copy of the event queue,\nand so "event consuming" functions (again, mostly anything that causes the\nscript to pause - eg [`os.sleep`], [`rednet.receive`], most of the [`turtle`] API,\netc) can safely be used in one without affecting the event queue accessed by\nthe other.\n\n\n> [!WARNING]\n> When using this API, be careful to pass the functions you want to run in\n> parallel, and _not_ the result of calling those functions.\n>\n> For instance, the following is correct:\n>\n> ```lua\n> local function do_sleep() sleep(1) end\n> parallel.waitForAny(do_sleep, rednet.receive)\n> ```\n>\n> but the following is **NOT**:\n>\n> ```lua\n> local function do_sleep() sleep(1) end\n> parallel.waitForAny(do_sleep(), rednet.receive)\n> ```\n\n@module parallel\n@since 1.2\n]]\n\nlocal function create(...)\n local tFns = table.pack(...)\n local tCos = {}\n for i = 1, tFns.n, 1 do\n local fn = tFns[i]\n if type(fn) ~= "function" then\n error("bad argument #" .. i .. " (function expected, got " .. type(fn) .. ")", 3)\n end\n\n tCos[i] = coroutine.create(fn)\n end\n\n return tCos\nend\n\nlocal function runUntilLimit(_routines, _limit)\n local count = #_routines\n if count < 1 then return 0 end\n local living = count\n\n local tFilters = {}\n local eventData = { n = 0 }\n while true do\n for n = 1, count do\n local r = _routines[n]\n if r then\n if tFilters[r] == nil or tFilters[r] == eventData[1] or eventData[1] == "terminate" then\n local ok, param = coroutine.resume(r, table.unpack(eventData, 1, eventData.n))\n if not ok then\n error(param, 0)\n else\n tFilters[r] = param\n end\n if coroutine.status(r) == "dead" then\n _routines[n] = nil\n living = living - 1\n if living <= _limit then\n return n\n end\n end\n end\n end\n end\n for n = 1, count do\n local r = _routines[n]\n if r and coroutine.status(r) == "dead" then\n _routines[n] = nil\n living = living - 1\n if living <= _limit then\n return n\n end\n end\n end\n eventData = table.pack(os.pullEventRaw())\n end\nend\n\n--[[- Switches between execution of the functions, until any of them\nfinishes. If any of the functions errors, the message is propagated upwards\nfrom the [`parallel.waitForAny`] call.\n\n@tparam function ... The functions this task will run\n@usage Print a message every second until the `q` key is pressed.\n\n local function tick()\n while true do\n os.sleep(1)\n print("Tick")\n end\n end\n local function wait_for_q()\n repeat\n local _, key = os.pullEvent("key")\n until key == keys.q\n print("Q was pressed!")\n end\n\n parallel.waitForAny(tick, wait_for_q)\n print("Everything done!")\n]]\nfunction waitForAny(...)\n local routines = create(...)\n return runUntilLimit(routines, #routines - 1)\nend\n\n--[[- Switches between execution of the functions, until all of them are\nfinished. If any of the functions errors, the message is propagated upwards\nfrom the [`parallel.waitForAll`] call.\n\n@tparam function ... The functions this task will run\n@usage Start off two timers and wait for them both to run.\n\n local function a()\n os.sleep(1)\n print("A is done")\n end\n local function b()\n os.sleep(3)\n print("B is done")\n end\n\n parallel.waitForAll(a, b)\n print("Everything done!")\n]]\nfunction waitForAll(...)\n local routines = create(...)\n return runUntilLimit(routines, 0)\nend\n',"rom/apis/peripheral.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[- Find and control peripherals attached to this computer.\n\nPeripherals are blocks (or turtle and pocket computer upgrades) which can\nbe controlled by a computer. For instance, the [`speaker`] peripheral allows a\ncomputer to play music and the [`monitor`] peripheral allows you to display text\nin the world.\n\n## Referencing peripherals\n\nComputers can interact with adjacent peripherals. Each peripheral is given a\nname based on which direction it is in. For instance, a disk drive below your\ncomputer will be called `"bottom"` in your Lua code, one to the left called\n`"left"` , and so on for all 6 directions (`"bottom"`, `"top"`, `"left"`,\n`"right"`, `"front"`, `"back"`).\n\nYou can list the names of all peripherals with the `peripherals` program, or the\n[`peripheral.getNames`] function.\n\nIt\'s also possible to use peripherals which are further away from your computer\nthrough the use of [Wired Modems][`modem`]. Place one modem against your computer\n(you may need to sneak and right click), run Networking Cable to your\nperipheral, and then place another modem against that block. You can then right\nclick the modem to use (or *attach*) the peripheral. This will print a\nperipheral name to chat, which can then be used just like a direction name to\naccess the peripheral. You can click on the message to copy the name to your\nclipboard.\n\n## Using peripherals\n\nOnce you have the name of a peripheral, you can call functions on it using the\n[`peripheral.call`] function. This takes the name of our peripheral, the name of\nthe function we want to call, and then its arguments.\n\n> [!INFO]\n> Some bits of the peripheral API call peripheral functions *methods* instead\n> (for example, the [`peripheral.getMethods`] function). Don\'t worry, they\'re the\n> same thing!\n\nLet\'s say we have a monitor above our computer (and so "top") and want to\n[write some text to it][`monitor.write`]. We\'d write the following:\n\n```lua\nperipheral.call("top", "write", "This is displayed on a monitor!")\n```\n\nOnce you start calling making a couple of peripheral calls this can get very\nrepetitive, and so we can [wrap][`peripheral.wrap`] a peripheral. This builds a\ntable of all the peripheral\'s functions so you can use it like an API or module.\n\nFor instance, we could have written the above example as follows:\n\n```lua\nlocal my_monitor = peripheral.wrap("top")\nmy_monitor.write("This is displayed on a monitor!")\n```\n\n## Finding peripherals\n\nSometimes when you\'re writing a program you don\'t care what a peripheral is\ncalled, you just need to know it\'s there. For instance, if you\'re writing a\nmusic player, you just need a speaker - it doesn\'t matter if it\'s above or below\nthe computer.\n\nThankfully there\'s a quick way to do this: [`peripheral.find`]. This takes a\n*peripheral type* and returns all the attached peripherals which are of this\ntype.\n\nWhat is a peripheral type though? This is a string which describes what a\nperipheral is, and so what functions are available on it. For instance, speakers\nare just called `"speaker"`, and monitors `"monitor"`. Some peripherals might\nhave more than one type - a Minecraft chest is both a `"minecraft:chest"` and\n`"inventory"`.\n\nYou can get all the types a peripheral has with [`peripheral.getType`], and check\na peripheral is a specific type with [`peripheral.hasType`].\n\nTo return to our original example, let\'s use [`peripheral.find`] to find an\nattached speaker:\n\n```lua\nlocal speaker = peripheral.find("speaker")\nspeaker.playNote("harp")\n```\n\n@module peripheral\n@see event!peripheral This event is fired whenever a new peripheral is attached.\n@see event!peripheral_detach This event is fired whenever a peripheral is detached.\n@since 1.3\n@changed 1.51 Add support for wired modems.\n@changed 1.99 Peripherals can have multiple types.\n]]\n\nlocal expect = dofile("rom/modules/main/cc/expect.lua").expect\n\nlocal native = peripheral\nlocal sides = rs.getSides()\n\n--- Provides a list of all peripherals available.\n--\n-- If a device is located directly next to the system, then its name will be\n-- listed as the side it is attached to. If a device is attached via a Wired\n-- Modem, then it\'ll be reported according to its name on the wired network.\n--\n-- @treturn { string... } A list of the names of all attached peripherals.\n-- @since 1.51\nfunction getNames()\n local results = {}\n for n = 1, #sides do\n local side = sides[n]\n if native.isPresent(side) then\n table.insert(results, side)\n if native.hasType(side, "peripheral_hub") then\n local remote = native.call(side, "getNamesRemote")\n for _, name in ipairs(remote) do\n table.insert(results, name)\n end\n end\n end\n end\n return results\nend\n\n--- Determines if a peripheral is present with the given name.\n--\n-- @tparam string name The side or network name that you want to check.\n-- @treturn boolean If a peripheral is present with the given name.\n-- @usage peripheral.isPresent("top")\n-- @usage peripheral.isPresent("monitor_0")\nfunction isPresent(name)\n expect(1, name, "string")\n if native.isPresent(name) then\n return true\n end\n\n for n = 1, #sides do\n local side = sides[n]\n if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", name) then\n return true\n end\n end\n return false\nend\n\n--[[- Get the types of a named or wrapped peripheral.\n\n@tparam string|table peripheral The name of the peripheral to find, or a\nwrapped peripheral instance.\n@treturn string... The peripheral\'s types, or `nil` if it is not present.\n@changed 1.88.0 Accepts a wrapped peripheral as an argument.\n@changed 1.99 Now returns multiple types.\n@usage Get the type of a peripheral above this computer.\n\n peripheral.getType("top")\n]]\nfunction getType(peripheral)\n expect(1, peripheral, "string", "table")\n if type(peripheral) == "string" then -- Peripheral name passed\n if native.isPresent(peripheral) then\n return native.getType(peripheral)\n end\n for n = 1, #sides do\n local side = sides[n]\n if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", peripheral) then\n return native.call(side, "getTypeRemote", peripheral)\n end\n end\n return nil\n else\n local mt = getmetatable(peripheral)\n if not mt or mt.__name ~= "peripheral" or type(mt.types) ~= "table" then\n error("bad argument #1 (table is not a peripheral)", 2)\n end\n return table.unpack(mt.types)\n end\nend\n\n--[[- Check if a peripheral is of a particular type.\n\n@tparam string|table peripheral The name of the peripheral or a wrapped peripheral instance.\n@tparam string peripheral_type The type to check.\n\n@treturn boolean|nil If a peripheral has a particular type, or `nil` if it is not present.\n@since 1.99\n]]\nfunction hasType(peripheral, peripheral_type)\n expect(1, peripheral, "string", "table")\n expect(2, peripheral_type, "string")\n if type(peripheral) == "string" then -- Peripheral name passed\n if native.isPresent(peripheral) then\n return native.hasType(peripheral, peripheral_type)\n end\n for n = 1, #sides do\n local side = sides[n]\n if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", peripheral) then\n return native.call(side, "hasTypeRemote", peripheral, peripheral_type)\n end\n end\n return nil\n else\n local mt = getmetatable(peripheral)\n if not mt or mt.__name ~= "peripheral" or type(mt.types) ~= "table" then\n error("bad argument #1 (table is not a peripheral)", 2)\n end\n return mt.types[peripheral_type] ~= nil\n end\nend\n\n--- Get all available methods for the peripheral with the given name.\n--\n-- @tparam string name The name of the peripheral to find.\n-- @treturn { string... }|nil A list of methods provided by this peripheral, or `nil` if\n-- it is not present.\nfunction getMethods(name)\n expect(1, name, "string")\n if native.isPresent(name) then\n return native.getMethods(name)\n end\n for n = 1, #sides do\n local side = sides[n]\n if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", name) then\n return native.call(side, "getMethodsRemote", name)\n end\n end\n return nil\nend\n\n--- Get the name of a peripheral wrapped with [`peripheral.wrap`].\n--\n-- @tparam table peripheral The peripheral to get the name of.\n-- @treturn string The name of the given peripheral.\n-- @since 1.88.0\nfunction getName(peripheral)\n expect(1, peripheral, "table")\n local mt = getmetatable(peripheral)\n if not mt or mt.__name ~= "peripheral" or type(mt.name) ~= "string" then\n error("bad argument #1 (table is not a peripheral)", 2)\n end\n return mt.name\nend\n\n--- Call a method on the peripheral with the given name.\n--\n-- @tparam string name The name of the peripheral to invoke the method on.\n-- @tparam string method The name of the method\n-- @param ... Additional arguments to pass to the method\n-- @return The return values of the peripheral method.\n--\n-- @usage Open the modem on the top of this computer.\n--\n-- peripheral.call("top", "open", 1)\nfunction call(name, method, ...)\n expect(1, name, "string")\n expect(2, method, "string")\n if native.isPresent(name) then\n return native.call(name, method, ...)\n end\n\n for n = 1, #sides do\n local side = sides[n]\n if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", name) then\n return native.call(side, "callRemote", name, method, ...)\n end\n end\n return nil\nend\n\n--- Get a table containing all functions available on a peripheral. These can\n-- then be called instead of using [`peripheral.call`] every time.\n--\n-- @tparam string name The name of the peripheral to wrap.\n-- @treturn table|nil The table containing the peripheral\'s methods, or `nil` if\n-- there is no peripheral present with the given name.\n-- @usage Open the modem on the top of this computer.\n--\n-- local modem = peripheral.wrap("top")\n-- modem.open(1)\nfunction wrap(name)\n expect(1, name, "string")\n\n local methods = peripheral.getMethods(name)\n if not methods then\n return nil\n end\n\n -- We store our types array as a list (for getType) and a lookup table (for hasType).\n local types = { peripheral.getType(name) }\n for i = 1, #types do types[types[i]] = true end\n local result = setmetatable({}, {\n __name = "peripheral",\n name = name,\n type = types[1],\n types = types,\n })\n for _, method in ipairs(methods) do\n result[method] = function(...)\n return peripheral.call(name, method, ...)\n end\n end\n return result\nend\n\n--[[- Find all peripherals of a specific type, and return the\n[wrapped][`peripheral.wrap`] peripherals.\n\n@tparam string ty The type of peripheral to look for.\n@tparam[opt] function(name:string, wrapped:table):boolean filter A\nfilter function, which takes the peripheral\'s name and wrapped table\nand returns if it should be included in the result.\n@treturn table... 0 or more wrapped peripherals matching the given filters.\n@usage Find all monitors and store them in a table, writing "Hello" on each one.\n\n local monitors = { peripheral.find("monitor") }\n for _, monitor in pairs(monitors) do\n monitor.write("Hello")\n end\n\n@usage Find all wireless modems connected to this computer.\n\n local modems = { peripheral.find("modem", function(name, modem)\n return modem.isWireless() -- Check this modem is wireless.\n end) }\n\n@usage This abuses the `filter` argument to call [`rednet.open`] on every modem.\n\n peripheral.find("modem", rednet.open)\n@since 1.6\n]]\nfunction find(ty, filter)\n expect(1, ty, "string")\n expect(2, filter, "function", "nil")\n\n local results = {}\n for _, name in ipairs(peripheral.getNames()) do\n if peripheral.hasType(name, ty) then\n local wrapped = peripheral.wrap(name)\n if filter == nil or filter(name, wrapped) then\n table.insert(results, wrapped)\n end\n end\n end\n return table.unpack(results)\nend\n',"rom/apis/rednet.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[- Communicate with other computers by using [modems][`modem`]. [`rednet`]\nprovides a layer of abstraction on top of the main [`modem`] peripheral, making\nit slightly easier to use.\n\n## Basic usage\nIn order to send a message between two computers, each computer must have a\nmodem on one of its sides (or in the case of pocket computers and turtles, the\nmodem must be equipped as an upgrade). The two computers should then call\n[`rednet.open`], which sets up the modems ready to send and receive messages.\n\nOnce rednet is opened, you can send messages using [`rednet.send`] and receive\nthem using [`rednet.receive`]. It\'s also possible to send a message to _every_\nrednet-using computer using [`rednet.broadcast`].\n\n> [Network security][!WARNING]\n>\n> While rednet provides a friendly way to send messages to specific computers, it\n> doesn\'t provide any guarantees about security. Other computers could be\n> listening in to your messages, or even pretending to send messages from other computers!\n>\n> If you\'re playing on a multi-player server (or at least one where you don\'t\n> trust other players), it\'s worth encrypting or signing your rednet messages.\n\n## Protocols and hostnames\nSeveral rednet messages accept "protocol"s - simple string names describing what\na message is about. When sending messages using [`rednet.send`] and\n[`rednet.broadcast`], you can optionally specify a protocol for the message. This\nsame protocol can then be given to [`rednet.receive`], to ignore all messages not\nusing this protocol.\n\nIt\'s also possible to look-up computers based on protocols, providing a basic\nsystem for service discovery and [DNS]. A computer can advertise that it\nsupports a particular protocol with [`rednet.host`], also providing a friendly\n"hostname". Other computers may then find all computers which support this\nprotocol using [`rednet.lookup`].\n\n[DNS]: https://en.wikipedia.org/wiki/Domain_Name_System "Domain Name System"\n\n@module rednet\n@since 1.2\n@see rednet_message Queued when a rednet message is received.\n@see modem Rednet is built on top of the modem peripheral. Modems provide a more\nbare-bones but flexible interface.\n]]\n\nlocal expect = dofile("rom/modules/main/cc/expect.lua").expect\n\n--- The channel used by the Rednet API to [`broadcast`] messages.\nCHANNEL_BROADCAST = 65535\n\n--- The channel used by the Rednet API to repeat messages.\nCHANNEL_REPEAT = 65533\n\n--- The number of channels rednet reserves for computer IDs. Computers with IDs\n-- greater or equal to this limit wrap around to 0.\nMAX_ID_CHANNELS = 65500\n\nlocal received_messages = {}\nlocal hostnames = {}\nlocal prune_received_timer\n\nlocal function id_as_channel(id)\n return (id or os.getComputerID()) % MAX_ID_CHANNELS\nend\n\n--[[- Opens a modem with the given [`peripheral`] name, allowing it to send and\nreceive messages over rednet.\n\nThis will open the modem on two channels: one which has the same\n[ID][`os.getComputerID`] as the computer, and another on\n[the broadcast channel][`CHANNEL_BROADCAST`].\n\n@tparam string modem The name of the modem to open.\n@throws If there is no such modem with the given name\n@usage Open rednet on the back of the computer, allowing you to send and receive\nrednet messages using it.\n\n rednet.open("back")\n\n@usage Open rednet on all attached modems. This abuses the "filter" argument to\n[`peripheral.find`].\n\n peripheral.find("modem", rednet.open)\n@see rednet.close\n@see rednet.isOpen\n]]\nfunction open(modem)\n expect(1, modem, "string")\n if peripheral.getType(modem) ~= "modem" then\n error("No such modem: " .. modem, 2)\n end\n peripheral.call(modem, "open", id_as_channel())\n peripheral.call(modem, "open", CHANNEL_BROADCAST)\nend\n\n--- Close a modem with the given [`peripheral`] name, meaning it can no longer\n-- send and receive rednet messages.\n--\n-- @tparam[opt] string modem The side the modem exists on. If not given, all\n-- open modems will be closed.\n-- @throws If there is no such modem with the given name\n-- @see rednet.open\nfunction close(modem)\n expect(1, modem, "string", "nil")\n if modem then\n -- Close a specific modem\n if peripheral.getType(modem) ~= "modem" then\n error("No such modem: " .. modem, 2)\n end\n peripheral.call(modem, "close", id_as_channel())\n peripheral.call(modem, "close", CHANNEL_BROADCAST)\n else\n -- Close all modems\n for _, modem in ipairs(peripheral.getNames()) do\n if isOpen(modem) then\n close(modem)\n end\n end\n end\nend\n\n--- Determine if rednet is currently open.\n--\n-- @tparam[opt] string modem Which modem to check. If not given, all connected\n-- modems will be checked.\n-- @treturn boolean If the given modem is open.\n-- @since 1.31\n-- @see rednet.open\nfunction isOpen(modem)\n expect(1, modem, "string", "nil")\n if modem then\n -- Check if a specific modem is open\n if peripheral.getType(modem) == "modem" then\n return peripheral.call(modem, "isOpen", id_as_channel()) and peripheral.call(modem, "isOpen", CHANNEL_BROADCAST)\n end\n else\n -- Check if any modem is open\n for _, modem in ipairs(peripheral.getNames()) do\n if isOpen(modem) then\n return true\n end\n end\n end\n return false\nend\n\n--[[- Allows a computer or turtle with an attached modem to send a message\nintended for a sycomputer with a specific ID. At least one such modem must first\nbe [opened][`rednet.open`] before sending is possible.\n\nAssuming the target was in range and also had a correctly opened modem, the\ntarget computer may then use [`rednet.receive`] to collect the message.\n\n@tparam number recipient The ID of the receiving computer.\n@param message The message to send. Like with [`modem.transmit`], this can\ncontain any primitive type (numbers, booleans and strings) as well as\ntables. Other types (like functions), as well as metatables, will not be\ntransmitted.\n@tparam[opt] string protocol The "protocol" to send this message under. When\nusing [`rednet.receive`] one can filter to only receive messages sent under a\nparticular protocol.\n@treturn boolean If this message was successfully sent (i.e. if rednet is\ncurrently [open][`rednet.open`]). Note, this does not guarantee the message was\nactually _received_.\n@changed 1.6 Added protocol parameter.\n@changed 1.82.0 Now returns whether the message was successfully sent.\n@see rednet.receive\n@usage Send a message to computer #2.\n\n rednet.send(2, "Hello from rednet!")\n]]\nfunction send(recipient, message, protocol)\n expect(1, recipient, "number")\n expect(3, protocol, "string", "nil")\n -- Generate a (probably) unique message ID\n -- We could do other things to guarantee uniqueness, but we really don\'t need to\n -- Store it to ensure we don\'t get our own messages back\n local message_id = math.random(1, 2147483647)\n received_messages[message_id] = os.clock() + 9.5\n if not prune_received_timer then prune_received_timer = os.startTimer(10) end\n\n -- Create the message\n local reply_channel = id_as_channel()\n local message_wrapper = {\n nMessageID = message_id,\n nRecipient = recipient,\n nSender = os.getComputerID(),\n message = message,\n sProtocol = protocol,\n }\n\n local sent = false\n if recipient == os.getComputerID() then\n -- Loopback to ourselves\n os.queueEvent("rednet_message", os.getComputerID(), message, protocol)\n sent = true\n else\n -- Send on all open modems, to the target and to repeaters\n if recipient ~= CHANNEL_BROADCAST then\n recipient = id_as_channel(recipient)\n end\n\n for _, modem in ipairs(peripheral.getNames()) do\n if isOpen(modem) then\n peripheral.call(modem, "transmit", recipient, reply_channel, message_wrapper)\n peripheral.call(modem, "transmit", CHANNEL_REPEAT, reply_channel, message_wrapper)\n sent = true\n end\n end\n end\n\n return sent\nend\n\n--[[- Broadcasts a string message over the predefined [`CHANNEL_BROADCAST`]\nchannel. The message will be received by every device listening to rednet.\n\n@param message The message to send. This should not contain coroutines or\nfunctions, as they will be converted to [`nil`].\n@tparam[opt] string protocol The "protocol" to send this message under. When\nusing [`rednet.receive`] one can filter to only receive messages sent under a\nparticular protocol.\n@see rednet.receive\n@changed 1.6 Added protocol parameter.\n@usage Broadcast the words "Hello, world!" to every computer using rednet.\n\n rednet.broadcast("Hello, world!")\n]]\nfunction broadcast(message, protocol)\n expect(2, protocol, "string", "nil")\n send(CHANNEL_BROADCAST, message, protocol)\nend\n\n--[[- Wait for a rednet message to be received, or until `nTimeout` seconds have\nelapsed.\n\n@tparam[opt] string protocol_filter The protocol the received message must be\nsent with. If specified, any messages not sent under this protocol will be\ndiscarded.\n@tparam[opt] number timeout The number of seconds to wait if no message is\nreceived.\n@treturn[1] number The computer which sent this message\n@return[1] The received message\n@treturn[1] string|nil The protocol this message was sent under.\n@treturn[2] nil If the timeout elapsed and no message was received.\n@see rednet.broadcast\n@see rednet.send\n@changed 1.6 Added protocol filter parameter.\n@usage Receive a rednet message.\n\n local id, message = rednet.receive()\n print(("Computer %d sent message %s"):format(id, message))\n\n@usage Receive a message, stopping after 5 seconds if no message was received.\n\n local id, message = rednet.receive(nil, 5)\n if not id then\n printError("No message received")\n else\n print(("Computer %d sent message %s"):format(id, message))\n end\n\n@usage Receive a message from computer #2.\n\n local id, message\n repeat\n id, message = rednet.receive()\n until id == 2\n\n print(message)\n]]\nfunction receive(protocol_filter, timeout)\n -- The parameters used to be ( nTimeout ), detect this case for backwards compatibility\n if type(protocol_filter) == "number" and timeout == nil then\n protocol_filter, timeout = nil, protocol_filter\n end\n expect(1, protocol_filter, "string", "nil")\n expect(2, timeout, "number", "nil")\n\n -- Start the timer\n local timer = nil\n local event_filter = nil\n if timeout then\n timer = os.startTimer(timeout)\n event_filter = nil\n else\n event_filter = "rednet_message"\n end\n\n -- Wait for events\n while true do\n local event, p1, p2, p3 = os.pullEvent(event_filter)\n if event == "rednet_message" then\n -- Return the first matching rednet_message\n local sender_id, message, protocol = p1, p2, p3\n if protocol_filter == nil or protocol == protocol_filter then\n return sender_id, message, protocol\n end\n elseif event == "timer" then\n -- Return nil if we timeout\n if p1 == timer then\n return nil\n end\n end\n end\nend\n\n--[[- Register the system as "hosting" the desired protocol under the specified\nname. If a rednet [lookup][`rednet.lookup`] is performed for that protocol (and\nmaybe name) on the same network, the registered system will automatically\nrespond via a background process, hence providing the system performing the\nlookup with its ID number.\n\nMultiple computers may not register themselves on the same network as having the\nsame names against the same protocols, and the title `localhost` is specifically\nreserved. They may, however, share names as long as their hosted protocols are\ndifferent, or if they only join a given network after "registering" themselves\nbefore doing so (eg while offline or part of a different network).\n\n@tparam string protocol The protocol this computer provides.\n@tparam string hostname The name this computer exposes for the given protocol.\n@throws If trying to register a hostname which is reserved, or currently in use.\n@see rednet.unhost\n@see rednet.lookup\n@since 1.6\n]]\nfunction host(protocol, hostname)\n expect(1, protocol, "string")\n expect(2, hostname, "string")\n if hostname == "localhost" then\n error("Reserved hostname", 2)\n end\n if hostnames[protocol] ~= hostname then\n if lookup(protocol, hostname) ~= nil then\n error("Hostname in use", 2)\n end\n hostnames[protocol] = hostname\n end\nend\n\n--- Stop [hosting][`rednet.host`] a specific protocol, meaning it will no longer\n-- respond to [`rednet.lookup`] requests.\n--\n-- @tparam string protocol The protocol to unregister your self from.\n-- @since 1.6\nfunction unhost(protocol)\n expect(1, protocol, "string")\n hostnames[protocol] = nil\nend\n\n--[[- Search the local rednet network for systems [hosting][`rednet.host`] the\ndesired protocol and returns any computer IDs that respond as "registered"\nagainst it.\n\nIf a hostname is specified, only one ID will be returned (assuming an exact\nmatch is found).\n\n@tparam string protocol The protocol to search for.\n@tparam[opt] string hostname The hostname to search for.\n\n@treturn[1] number... A list of computer IDs hosting the given protocol.\n@treturn[2] number|nil The computer ID with the provided hostname and protocol,\nor [`nil`] if none exists.\n@since 1.6\n@usage Find all computers which are hosting the `"chat"` protocol.\n\n local computers = {rednet.lookup("chat")}\n print(#computers .. " computers available to chat")\n for _, computer in pairs(computers) do\n print("Computer #" .. computer)\n end\n\n@usage Find a computer hosting the `"chat"` protocol with a hostname of `"my_host"`.\n\n local id = rednet.lookup("chat", "my_host")\n if id then\n print("Found my_host at computer #" .. id)\n else\n printError("Cannot find my_host")\n end\n\n]]\nfunction lookup(protocol, hostname)\n expect(1, protocol, "string")\n expect(2, hostname, "string", "nil")\n\n -- Build list of host IDs\n local results = nil\n if hostname == nil then\n results = {}\n end\n\n -- Check localhost first\n if hostnames[protocol] then\n if hostname == nil then\n table.insert(results, os.getComputerID())\n elseif hostname == "localhost" or hostname == hostnames[protocol] then\n return os.getComputerID()\n end\n end\n\n if not isOpen() then\n if results then\n return table.unpack(results)\n end\n return nil\n end\n\n -- Broadcast a lookup packet\n broadcast({\n sType = "lookup",\n sProtocol = protocol,\n sHostname = hostname,\n }, "dns")\n\n -- Start a timer\n local timer = os.startTimer(2)\n\n -- Wait for events\n while true do\n local event, p1, p2, p3 = os.pullEvent()\n if event == "rednet_message" then\n -- Got a rednet message, check if it\'s the response to our request\n local sender_id, message, message_protocol = p1, p2, p3\n if message_protocol == "dns" and type(message) == "table" and message.sType == "lookup response" then\n if message.sProtocol == protocol then\n if hostname == nil then\n table.insert(results, sender_id)\n elseif message.sHostname == hostname then\n return sender_id\n end\n end\n end\n elseif event == "timer" and p1 == timer then\n -- Got a timer event, check it\'s the end of our timeout\n break\n end\n end\n if results then\n return table.unpack(results)\n end\n return nil\nend\n\nlocal started = false\n\n--- Listen for modem messages and converts them into rednet messages, which may\n-- then be [received][`receive`].\n--\n-- This is automatically started in the background on computer startup, and\n-- should not be called manually.\nfunction run()\n if started then\n error("rednet is already running", 2)\n end\n started = true\n\n while true do\n local event, p1, p2, p3, p4 = os.pullEventRaw()\n if event == "modem_message" then\n -- Got a modem message, process it and add it to the rednet event queue\n local modem, channel, reply_channel, message = p1, p2, p3, p4\n if channel == id_as_channel() or channel == CHANNEL_BROADCAST then\n if type(message) == "table" and type(message.nMessageID) == "number"\n and message.nMessageID == message.nMessageID and not received_messages[message.nMessageID]\n and (type(message.nSender) == "nil" or (type(message.nSender) == "number" and message.nSender == message.nSender))\n and ((message.nRecipient and message.nRecipient == os.getComputerID()) or channel == CHANNEL_BROADCAST)\n and isOpen(modem)\n then\n received_messages[message.nMessageID] = os.clock() + 9.5\n if not prune_received_timer then prune_received_timer = os.startTimer(10) end\n os.queueEvent("rednet_message", message.nSender or reply_channel, message.message, message.sProtocol)\n end\n end\n\n elseif event == "rednet_message" then\n -- Got a rednet message (queued from above), respond to dns lookup\n local sender, message, protocol = p1, p2, p3\n if protocol == "dns" and type(message) == "table" and message.sType == "lookup" then\n local hostname = hostnames[message.sProtocol]\n if hostname ~= nil and (message.sHostname == nil or message.sHostname == hostname) then\n send(sender, {\n sType = "lookup response",\n sHostname = hostname,\n sProtocol = message.sProtocol,\n }, "dns")\n end\n end\n\n elseif event == "timer" and p1 == prune_received_timer then\n -- Got a timer event, use it to prune the set of received messages\n prune_received_timer = nil\n local now, has_more = os.clock(), nil\n for message_id, deadline in pairs(received_messages) do\n if deadline <= now then received_messages[message_id] = nil\n else has_more = true end\n end\n prune_received_timer = has_more and os.startTimer(10)\n end\n end\nend\n',"rom/apis/settings.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[- Read and write configuration options for CraftOS and your programs.\n\nWhen a computer starts, it reads the current value of settings from the\n`/.settings` file. These values then may be [read][`settings.get`] or\n[modified][`settings.set`].\n\n> [!WARNING]\n> Calling [`settings.set`] does _not_ update the settings file by default. You\n> _must_ call [`settings.save`] to persist values.\n\n@module settings\n@since 1.78\n@usage Define an basic setting `123` and read its value.\n\n settings.define("my.setting", {\n description = "An example setting",\n default = 123,\n type = number,\n })\n print("my.setting = " .. settings.get("my.setting")) -- 123\n\nYou can then use the `set` program to change its value (e.g. `set my.setting 456`),\nand then re-run the `example` program to check it has changed.\n\n]]\n\nlocal expect = dofile("rom/modules/main/cc/expect.lua")\nlocal type, expect, field = type, expect.expect, expect.field\n\nlocal details, values = {}, {}\n\nlocal function reserialize(value)\n if type(value) ~= "table" then return value end\n return textutils.unserialize(textutils.serialize(value))\nend\n\nlocal function copy(value)\n if type(value) ~= "table" then return value end\n local result = {}\n for k, v in pairs(value) do result[k] = copy(v) end\n return result\nend\n\nlocal valid_types = { "number", "string", "boolean", "table" }\nfor _, v in ipairs(valid_types) do valid_types[v] = true end\n\n--- Define a new setting, optional specifying various properties about it.\n--\n-- While settings do not have to be added before being used, doing so allows\n-- you to provide defaults and additional metadata.\n--\n-- @tparam string name The name of this option\n-- @tparam[opt] { description? = string, default? = any, type? = string } options\n-- Options for this setting. This table accepts the following fields:\n--\n-- - `description`: A description which may be printed when running the `set` program.\n-- - `default`: A default value, which is returned by [`settings.get`] if the\n-- setting has not been changed.\n-- - `type`: Require values to be of this type. [Setting][`set`] the value to another type\n-- will error.\n-- @since 1.87.0\nfunction define(name, options)\n expect(1, name, "string")\n expect(2, options, "table", "nil")\n\n if options then\n options = {\n description = field(options, "description", "string", "nil"),\n default = reserialize(field(options, "default", "number", "string", "boolean", "table", "nil")),\n type = field(options, "type", "string", "nil"),\n }\n\n if options.type and not valid_types[options.type] then\n error(("Unknown type %q. Expected one of %s."):format(options.type, table.concat(valid_types, ", ")), 2)\n end\n else\n options = {}\n end\n\n details[name] = options\nend\n\n--- Remove a [definition][`define`] of a setting.\n--\n-- If a setting has been changed, this does not remove its value. Use [`settings.unset`]\n-- for that.\n--\n-- @tparam string name The name of this option\n-- @since 1.87.0\nfunction undefine(name)\n expect(1, name, "string")\n details[name] = nil\nend\n\nlocal function set_value(name, new)\n local old = values[name]\n if old == nil then\n local opt = details[name]\n old = opt and opt.default\n end\n\n values[name] = new\n if old ~= new then\n -- This should be safe, as os.queueEvent copies values anyway.\n os.queueEvent("setting_changed", name, new, old)\n end\nend\n\n--[[- Set the value of a setting.\n\n> [!WARNING]\n> Calling [`settings.set`] does _not_ update the settings file by default. You\n> _must_ call [`settings.save`] to persist values.\n\n@tparam string name The name of the setting to set\n@param value The setting\'s value. This cannot be `nil`, and must be\nserialisable by [`textutils.serialize`].\n@throws If this value cannot be serialised\n@see settings.unset\n]]\nfunction set(name, value)\n expect(1, name, "string")\n expect(2, value, "number", "string", "boolean", "table")\n\n local opt = details[name]\n if opt and opt.type then expect(2, value, opt.type) end\n\n set_value(name, reserialize(value))\nend\n\n--- Get the value of a setting.\n--\n-- @tparam string name The name of the setting to get.\n-- @param[opt] default The value to use should there be pre-existing value for\n-- this setting. If not given, it will use the setting\'s default value if given,\n-- or `nil` otherwise.\n-- @return The setting\'s, or the default if the setting has not been changed.\n-- @changed 1.87.0 Now respects default value if pre-defined and `default` is unset.\nfunction get(name, default)\n expect(1, name, "string")\n local result = values[name]\n if result ~= nil then\n return copy(result)\n elseif default ~= nil then\n return default\n else\n local opt = details[name]\n return opt and copy(opt.default)\n end\nend\n\n--- Get details about a specific setting.\n--\n-- @tparam string name The name of the setting to get.\n-- @treturn { description? = string, default? = any, type? = string, value? = any }\n-- Information about this setting. This includes all information from [`settings.define`],\n-- as well as this setting\'s value.\n-- @since 1.87.0\nfunction getDetails(name)\n expect(1, name, "string")\n local deets = copy(details[name]) or {}\n deets.value = values[name]\n deets.changed = deets.value ~= nil\n if deets.value == nil then deets.value = deets.default end\n return deets\nend\n\n--- Remove the value of a setting, setting it to the default.\n--\n-- [`settings.get`] will return the default value until the setting\'s value is\n-- [set][`settings.set`], or the computer is rebooted.\n--\n-- @tparam string name The name of the setting to unset.\n-- @see settings.set\n-- @see settings.clear\nfunction unset(name)\n expect(1, name, "string")\n set_value(name, nil)\nend\n\n--- Resets the value of all settings. Equivalent to calling [`settings.unset`]\n--- on every setting.\n--\n-- @see settings.unset\nfunction clear()\n for name in pairs(values) do\n set_value(name, nil)\n end\nend\n\n--- Get the names of all currently defined settings.\n--\n-- @treturn { string } An alphabetically sorted list of all currently-defined\n-- settings.\nfunction getNames()\n local result, n = {}, 1\n for k in pairs(details) do\n result[n], n = k, n + 1\n end\n for k in pairs(values) do\n if not details[k] then result[n], n = k, n + 1 end\n end\n table.sort(result)\n return result\nend\n\n--- Load settings from the given file.\n--\n-- Existing settings will be merged with any pre-existing ones. Conflicting\n-- entries will be overwritten, but any others will be preserved.\n--\n-- @tparam[opt] string sPath The file to load from, defaulting to `.settings`.\n-- @treturn boolean Whether settings were successfully read from this\n-- file. Reasons for failure may include the file not existing or being\n-- corrupted.\n--\n-- @see settings.save\n-- @changed 1.87.0 `sPath` is now optional.\nfunction load(sPath)\n expect(1, sPath, "string", "nil")\n local file = fs.open(sPath or ".settings", "r")\n if not file then\n return false\n end\n\n local sText = file.readAll()\n file.close()\n\n local tFile = textutils.unserialize(sText)\n if type(tFile) ~= "table" then\n return false\n end\n\n for k, v in pairs(tFile) do\n local ty_v = type(v)\n if type(k) == "string" and (ty_v == "string" or ty_v == "number" or ty_v == "boolean" or ty_v == "table") then\n local opt = details[k]\n if not opt or not opt.type or ty_v == opt.type then\n -- This may fail if the table is recursive (or otherwise cannot be serialized).\n local ok, v = pcall(reserialize, v)\n if ok then set_value(k, v) end\n end\n end\n end\n\n return true\nend\n\n--- Save settings to the given file.\n--\n-- This will entirely overwrite the pre-existing file. Settings defined in the\n-- file, but not currently loaded will be removed.\n--\n-- @tparam[opt] string sPath The path to save settings to, defaulting to `.settings`.\n-- @treturn boolean If the settings were successfully saved.\n--\n-- @see settings.load\n-- @changed 1.87.0 `sPath` is now optional.\nfunction save(sPath)\n expect(1, sPath, "string", "nil")\n local file = fs.open(sPath or ".settings", "w")\n if not file then\n return false\n end\n\n file.write(textutils.serialize(values))\n file.close()\n\n return true\nend\n',"rom/apis/term.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--- @module term\n\nlocal expect = dofile("rom/modules/main/cc/expect.lua").expect\n\nlocal native = term.native and term.native() or term\nlocal redirectTarget = native\n\nlocal function wrap(_sFunction)\n return function(...)\n return redirectTarget[_sFunction](...)\n end\nend\n\nlocal term = _ENV\n\n--- Redirects terminal output to a monitor, a [`window`], or any other custom\n-- terminal object. Once the redirect is performed, any calls to a "term"\n-- function - or to a function that makes use of a term function, as [`print`] -\n-- will instead operate with the new terminal object.\n--\n-- A "terminal object" is simply a table that contains functions with the same\n-- names - and general features - as those found in the term table. For example,\n-- a wrapped monitor is suitable.\n--\n-- The redirect can be undone by pointing back to the previous terminal object\n-- (which this function returns whenever you switch).\n--\n-- @tparam Redirect target The terminal redirect the [`term`] API will draw to.\n-- @treturn Redirect The previous redirect object, as returned by\n-- [`term.current`].\n-- @since 1.31\n-- @usage\n-- Redirect to a monitor on the right of the computer.\n-- term.redirect(peripheral.wrap("right"))\nterm.redirect = function(target)\n expect(1, target, "table")\n if target == term or target == _G.term then\n error("term is not a recommended redirect target, try term.current() instead", 2)\n end\n for k, v in pairs(native) do\n if type(k) == "string" and type(v) == "function" then\n if type(target[k]) ~= "function" then\n target[k] = function()\n error("Redirect object is missing method " .. k .. ".", 2)\n end\n end\n end\n end\n local oldRedirectTarget = redirectTarget\n redirectTarget = target\n return oldRedirectTarget\nend\n\n--- Returns the current terminal object of the computer.\n--\n-- @treturn Redirect The current terminal redirect\n-- @since 1.6\n-- @usage\n-- Create a new [`window`] which draws to the current redirect target.\n--\n-- window.create(term.current(), 1, 1, 10, 10)\nterm.current = function()\n return redirectTarget\nend\n\n--- Get the native terminal object of the current computer.\n--\n-- It is recommended you do not use this function unless you absolutely have\n-- to. In a multitasked environment, [`term.native`] will _not_ be the current\n-- terminal object, and so drawing may interfere with other programs.\n--\n-- @treturn Redirect The native terminal redirect.\n-- @since 1.6\nterm.native = function()\n return native\nend\n\n-- Some methods shouldn\'t go through redirects, so we move them to the main\n-- term API.\nfor _, method in ipairs { "nativePaletteColor", "nativePaletteColour" } do\n term[method] = native[method]\n native[method] = nil\nend\n\nfor k, v in pairs(native) do\n if type(k) == "string" and type(v) == "function" and rawget(term, k) == nil then\n term[k] = wrap(k)\n end\nend\n',"rom/apis/textutils.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--- Helpful utilities for formatting and manipulating strings.\n--\n-- @module textutils\n-- @since 1.2\n\nlocal expect = dofile("rom/modules/main/cc/expect.lua")\nlocal expect, field = expect.expect, expect.field\nlocal wrap = dofile("rom/modules/main/cc/strings.lua").wrap\n\n--- Slowly writes string text at current cursor position,\n-- character-by-character.\n--\n-- Like [`_G.write`], this does not insert a newline at the end.\n--\n-- @tparam string text The the text to write to the screen\n-- @tparam[opt] number rate The number of characters to write each second,\n-- Defaults to 20.\n-- @usage textutils.slowWrite("Hello, world!")\n-- @usage textutils.slowWrite("Hello, world!", 5)\n-- @since 1.3\nfunction slowWrite(text, rate)\n expect(2, rate, "number", "nil")\n rate = rate or 20\n if rate < 0 then\n error("Rate must be positive", 2)\n end\n local to_sleep = 1 / rate\n\n local wrapped_lines = wrap(tostring(text), (term.getSize()))\n local wrapped_str = table.concat(wrapped_lines, "\\n")\n\n for n = 1, #wrapped_str do\n sleep(to_sleep)\n write(wrapped_str:sub(n, n))\n end\nend\n\n--- Slowly prints string text at current cursor position,\n-- character-by-character.\n--\n-- Like [`print`], this inserts a newline after printing.\n--\n-- @tparam string sText The the text to write to the screen\n-- @tparam[opt] number nRate The number of characters to write each second,\n-- Defaults to 20.\n-- @usage textutils.slowPrint("Hello, world!")\n-- @usage textutils.slowPrint("Hello, world!", 5)\nfunction slowPrint(sText, nRate)\n slowWrite(sText, nRate)\n print()\nend\n\n--- Takes input time and formats it in a more readable format such as `6:30 PM`.\n--\n-- @tparam number nTime The time to format, as provided by [`os.time`].\n-- @tparam[opt] boolean bTwentyFourHour Whether to format this as a 24-hour\n-- clock (`18:30`) rather than a 12-hour one (`6:30 AM`)\n-- @treturn string The formatted time\n-- @usage Print the current in-game time as a 12-hour clock.\n--\n-- textutils.formatTime(os.time())\n-- @usage Print the local time as a 24-hour clock.\n--\n-- textutils.formatTime(os.time("local"), true)\nfunction formatTime(nTime, bTwentyFourHour)\n expect(1, nTime, "number")\n expect(2, bTwentyFourHour, "boolean", "nil")\n local sTOD = nil\n if not bTwentyFourHour then\n if nTime >= 12 then\n sTOD = "PM"\n else\n sTOD = "AM"\n end\n if nTime >= 13 then\n nTime = nTime - 12\n end\n end\n\n local nHour = math.floor(nTime)\n local nMinute = math.floor((nTime - nHour) * 60)\n if sTOD then\n return string.format("%d:%02d %s", nHour == 0 and 12 or nHour, nMinute, sTOD)\n else\n return string.format("%d:%02d", nHour, nMinute)\n end\nend\n\nlocal function makePagedScroll(_term, _nFreeLines)\n local nativeScroll = _term.scroll\n local nFreeLines = _nFreeLines or 0\n return function(_n)\n for _ = 1, _n do\n nativeScroll(1)\n\n if nFreeLines <= 0 then\n local _, h = _term.getSize()\n _term.setCursorPos(1, h)\n _term.write("Press any key to continue")\n os.pullEvent("key")\n _term.clearLine()\n _term.setCursorPos(1, h)\n else\n nFreeLines = nFreeLines - 1\n end\n end\n end\nend\n\n--[[- Prints a given string to the display.\n\nIf the action can be completed without scrolling, it acts much the same as\n[`print`]; otherwise, it will throw up a "Press any key to continue" prompt at\nthe bottom of the display. Each press will cause it to scroll down and write a\nsingle line more before prompting again, if need be.\n\n@tparam string text The text to print to the screen.\n@tparam[opt] number free_lines The number of lines which will be\nautomatically scrolled before the first prompt appears (meaning free_lines +\n1 lines will be printed). This can be set to the cursor\'s y position - 2 to\nalways try to fill the screen. Defaults to 0, meaning only one line is\ndisplayed before prompting.\n@treturn number The number of lines printed.\n\n@usage Generates several lines of text and then prints it, paging once the\nbottom of the terminal is reached.\n\n local lines = {}\n for i = 1, 30 do lines[i] = ("This is line #%d"):format(i) end\n local message = table.concat(lines, "\\n")\n\n local width, height = term.getCursorPos()\n textutils.pagedPrint(message, height - 2)\n]]\nfunction pagedPrint(text, free_lines)\n expect(2, free_lines, "number", "nil")\n -- Setup a redirector\n local oldTerm = term.current()\n local newTerm = {}\n for k, v in pairs(oldTerm) do\n newTerm[k] = v\n end\n\n newTerm.scroll = makePagedScroll(oldTerm, free_lines)\n term.redirect(newTerm)\n\n -- Print the text\n local result\n local ok, err = pcall(function()\n if text ~= nil then\n result = print(text)\n else\n result = print()\n end\n end)\n\n -- Removed the redirector\n term.redirect(oldTerm)\n\n -- Propagate errors\n if not ok then\n error(err, 0)\n end\n return result\nend\n\nlocal function tabulateCommon(bPaged, ...)\n local tAll = table.pack(...)\n for i = 1, tAll.n do\n expect(i, tAll[i], "number", "table")\n end\n\n local w, h = term.getSize()\n local nMaxLen = w / 8\n for n, t in ipairs(tAll) do\n if type(t) == "table" then\n for nu, sItem in pairs(t) do\n local ty = type(sItem)\n if ty ~= "string" and ty ~= "number" then\n error("bad argument #" .. n .. "." .. nu .. " (string expected, got " .. ty .. ")", 3)\n end\n nMaxLen = math.max(#tostring(sItem) + 1, nMaxLen)\n end\n end\n end\n local nCols = math.floor(w / nMaxLen)\n local nLines = 0\n local function newLine()\n if bPaged and nLines >= h - 3 then\n pagedPrint()\n else\n print()\n end\n nLines = nLines + 1\n end\n\n local function drawCols(_t)\n local nCol = 1\n for _, s in ipairs(_t) do\n if nCol > nCols then\n nCol = 1\n newLine()\n end\n\n local cx, cy = term.getCursorPos()\n cx = 1 + (nCol - 1) * nMaxLen\n term.setCursorPos(cx, cy)\n term.write(s)\n\n nCol = nCol + 1\n end\n print()\n end\n\n local previous_colour = term.getTextColour()\n for _, t in ipairs(tAll) do\n if type(t) == "table" then\n if #t > 0 then\n drawCols(t)\n end\n elseif type(t) == "number" then\n term.setTextColor(t)\n end\n end\n term.setTextColor(previous_colour)\nend\n\n--[[- Prints tables in a structured form.\n\nThis accepts multiple arguments, either a table or a number. When\nencountering a table, this will be treated as a table row, with each column\nwidth being auto-adjusted.\n\nWhen encountering a number, this sets the text color of the subsequent rows to it.\n\n@tparam {string...}|number ... The rows and text colors to display.\n@since 1.3\n@usage\n\n textutils.tabulate(\n colors.orange, { "1", "2", "3" },\n colors.lightBlue, { "A", "B", "C" }\n )\n]]\nfunction tabulate(...)\n return tabulateCommon(false, ...)\nend\n\n--[[- Prints tables in a structured form, stopping and prompting for input should\nthe result not fit on the terminal.\n\nThis functions identically to [`textutils.tabulate`], but will prompt for user\ninput should the whole output not fit on the display.\n\n@tparam {string...}|number ... The rows and text colors to display.\n@see textutils.tabulate\n@see textutils.pagedPrint\n@since 1.3\n\n@usage Generates a long table, tabulates it, and prints it to the screen.\n\n local rows = {}\n for i = 1, 30 do rows[i] = {("Row #%d"):format(i), math.random(1, 400)} end\n\n textutils.pagedTabulate(colors.orange, {"Column", "Value"}, colors.lightBlue, table.unpack(rows))\n]]\nfunction pagedTabulate(...)\n return tabulateCommon(true, ...)\nend\n\nlocal g_tLuaKeywords = {\n ["and"] = true,\n ["break"] = true,\n ["do"] = true,\n ["else"] = true,\n ["elseif"] = true,\n ["end"] = true,\n ["false"] = true,\n ["for"] = true,\n ["function"] = true,\n ["if"] = true,\n ["in"] = true,\n ["local"] = true,\n ["nil"] = true,\n ["not"] = true,\n ["or"] = true,\n ["repeat"] = true,\n ["return"] = true,\n ["then"] = true,\n ["true"] = true,\n ["until"] = true,\n ["while"] = true,\n}\n\n--- A version of the ipairs iterator which ignores metamethods\nlocal function inext(tbl, i)\n i = (i or 0) + 1\n local v = rawget(tbl, i)\n if v == nil then return nil else return i, v end\nend\n\nlocal serialize_infinity = math.huge\nlocal function serialize_impl(t, tracking, indent, opts)\n local sType = type(t)\n if sType == "table" then\n if tracking[t] ~= nil then\n if tracking[t] == false then\n error("Cannot serialize table with repeated entries", 0)\n else\n error("Cannot serialize table with recursive entries", 0)\n end\n end\n tracking[t] = true\n\n local result\n if next(t) == nil then\n -- Empty tables are simple\n result = "{}"\n else\n -- Other tables take more work\n local open, sub_indent, open_key, close_key, equal, comma = "{\\n", indent .. " ", "[ ", " ] = ", " = ", ",\\n"\n if opts.compact then\n open, sub_indent, open_key, close_key, equal, comma = "{", "", "[", "]=", "=", ","\n end\n\n result = open\n local seen_keys = {}\n for k, v in inext, t do\n seen_keys[k] = true\n result = result .. sub_indent .. serialize_impl(v, tracking, sub_indent, opts) .. comma\n end\n for k, v in next, t do\n if not seen_keys[k] then\n local sEntry\n if type(k) == "string" and not g_tLuaKeywords[k] and string.match(k, "^[%a_][%a%d_]*$") then\n sEntry = k .. equal .. serialize_impl(v, tracking, sub_indent, opts) .. comma\n else\n sEntry = open_key .. serialize_impl(k, tracking, sub_indent, opts) .. close_key .. serialize_impl(v, tracking, sub_indent, opts) .. comma\n end\n result = result .. sub_indent .. sEntry\n end\n end\n result = result .. indent .. "}"\n end\n\n if opts.allow_repetitions then\n tracking[t] = nil\n else\n tracking[t] = false\n end\n return result\n\n elseif sType == "string" then\n return string.format("%q", t)\n\n elseif sType == "number" then\n if t ~= t then --nan\n return "0/0"\n elseif t == serialize_infinity then\n return "1/0"\n elseif t == -serialize_infinity then\n return "-1/0"\n else\n return tostring(t)\n end\n\n elseif sType == "boolean" or sType == "nil" then\n return tostring(t)\n\n else\n error("Cannot serialize type " .. sType, 0)\n\n end\nend\n\nlocal function mk_tbl(str, name)\n local msg = "attempt to mutate textutils." .. name\n return setmetatable({}, {\n __newindex = function() error(msg, 2) end,\n __tostring = function() return str end,\n })\nend\n\n--- A table representing an empty JSON array, in order to distinguish it from an\n-- empty JSON object.\n--\n-- The contents of this table should not be modified.\n--\n-- @usage textutils.serialiseJSON(textutils.empty_json_array)\n-- @see textutils.serialiseJSON\n-- @see textutils.unserialiseJSON\nempty_json_array = mk_tbl("[]", "empty_json_array")\n\n--- A table representing the JSON null value.\n--\n-- The contents of this table should not be modified.\n--\n-- @usage textutils.serialiseJSON(textutils.json_null)\n-- @see textutils.serialiseJSON\n-- @see textutils.unserialiseJSON\njson_null = mk_tbl("null", "json_null")\n\nlocal serializeJSONString\ndo\n local function hexify(c)\n return ("\\\\u00%02X"):format(c:byte())\n end\n\n local map = {\n ["\\""] = "\\\\\\"",\n ["\\\\"] = "\\\\\\\\",\n ["\\b"] = "\\\\b",\n ["\\f"] = "\\\\f",\n ["\\n"] = "\\\\n",\n ["\\r"] = "\\\\r",\n ["\\t"] = "\\\\t",\n }\n for i = 0, 0x1f do\n local c = string.char(i)\n if map[c] == nil then map[c] = hexify(c) end\n end\n\n serializeJSONString = function(s, options)\n if options and options.unicode_strings and s:find("[\\x80-\\xff]") then\n local retval = \'"\'\n for _, code in utf8.codes(s) do\n if code > 0xFFFF then\n -- Encode the codepoint as a UTF-16 surrogate pair\n code = code - 0x10000\n local high, low = bit32.extract(code, 10, 10) + 0xD800, bit32.extract(code, 0, 10) + 0xDC00\n retval = retval .. ("\\\\u%04X\\\\u%04X"):format(high, low)\n elseif code <= 0x5C and map[string.char(code)] then -- 0x5C = `\\`, don\'t run `string.char` if we don\'t need to\n retval = retval .. map[string.char(code)]\n elseif code < 0x20 or code >= 0x7F then\n retval = retval .. ("\\\\u%04X"):format(code)\n else\n retval = retval .. string.char(code)\n end\n end\n return retval .. \'"\'\n else\n return (\'"%s"\'):format(s:gsub("[\\0-\\x1f\\"\\\\]", map):gsub("[\\x7f-\\xff]", hexify))\n end\n end\nend\n\nlocal function serializeJSONImpl(t, tTracking, options)\n local sType = type(t)\n if t == empty_json_array then return "[]"\n elseif t == json_null then return "null"\n\n elseif sType == "table" then\n if tTracking[t] ~= nil then\n error("Cannot serialize table with recursive entries", 0)\n end\n tTracking[t] = true\n\n if next(t) == nil then\n -- Empty tables are simple\n return "{}"\n else\n -- Other tables take more work\n local sObjectResult = "{"\n local sArrayResult = "["\n local nObjectSize = 0\n local nArraySize = 0\n local largestArrayIndex = 0\n local bNBTStyle = options and options.nbt_style\n for k, v in pairs(t) do\n if type(k) == "string" then\n local sEntry\n if bNBTStyle then\n sEntry = tostring(k) .. ":" .. serializeJSONImpl(v, tTracking, options)\n else\n sEntry = serializeJSONString(k, options) .. ":" .. serializeJSONImpl(v, tTracking, options)\n end\n if nObjectSize == 0 then\n sObjectResult = sObjectResult .. sEntry\n else\n sObjectResult = sObjectResult .. "," .. sEntry\n end\n nObjectSize = nObjectSize + 1\n elseif type(k) == "number" and k > largestArrayIndex then --the largest index is kept to avoid losing half the array if there is any single nil in that array\n largestArrayIndex = k\n end\n end\n for k = 1, largestArrayIndex, 1 do --the array is read up to the very last valid array index, ipairs() would stop at the first nil value and we would lose any data after.\n local sEntry\n if t[k] == nil then --if the array is nil at index k the value is "null" as to keep the unused indexes in between used ones.\n sEntry = "null"\n else -- if the array index does not point to a nil we serialise it\'s content.\n sEntry = serializeJSONImpl(t[k], tTracking, options)\n end\n if nArraySize == 0 then\n sArrayResult = sArrayResult .. sEntry\n else\n sArrayResult = sArrayResult .. "," .. sEntry\n end\n nArraySize = nArraySize + 1\n end\n sObjectResult = sObjectResult .. "}"\n sArrayResult = sArrayResult .. "]"\n if nObjectSize > 0 or nArraySize == 0 then\n return sObjectResult\n else\n return sArrayResult\n end\n end\n\n elseif sType == "string" then\n return serializeJSONString(t, options)\n\n elseif sType == "number" or sType == "boolean" then\n return tostring(t)\n\n else\n error("Cannot serialize type " .. sType, 0)\n\n end\nend\n\nlocal unserialise_json\ndo\n local sub, find, match, concat, tonumber = string.sub, string.find, string.match, table.concat, tonumber\n\n --- Skip any whitespace\n local function skip(str, pos)\n local _, last = find(str, "^[ \\n\\r\\t]+", pos)\n if last then return last + 1 else return pos end\n end\n\n local escapes = {\n ["b"] = \'\\b\', ["f"] = \'\\f\', ["n"] = \'\\n\', ["r"] = \'\\r\', ["t"] = \'\\t\',\n ["\\""] = "\\"", ["/"] = "/", ["\\\\"] = "\\\\",\n }\n\n local mt = {}\n\n local function error_at(pos, msg, ...)\n if select(\'#\', ...) > 0 then msg = msg:format(...) end\n error(setmetatable({ pos = pos, msg = msg }, mt))\n end\n\n local function expected(pos, actual, exp)\n if actual == "" then actual = "end of input" else actual = ("%q"):format(actual) end\n error_at(pos, "Unexpected %s, expected %s.", actual, exp)\n end\n\n local function parse_string(str, pos, terminate)\n local buf, n = {}, 1\n\n -- We attempt to match all non-special characters at once using Lua patterns, as this\n -- provides a significant speed boost. This is all characters >= " " except \\ and the\n -- terminator (\' or ").\n local char_pat = "^[ !#-[%]^-\\255]+"\n if terminate == "\'" then char_pat = "^[ -&(-[%]^-\\255]+" end\n\n while true do\n local c = sub(str, pos, pos)\n if c == "" then error_at(pos, "Unexpected end of input, expected \'\\"\'.") end\n if c == terminate then break end\n\n if c == "\\\\" then\n -- Handle the various escapes\n c = sub(str, pos + 1, pos + 1)\n if c == "" then error_at(pos, "Unexpected end of input, expected escape sequence.") end\n\n if c == "u" then\n local num_str = match(str, "^%x%x%x%x", pos + 2)\n if not num_str then error_at(pos, "Malformed unicode escape %q.", sub(str, pos + 2, pos + 5)) end\n buf[n], n, pos = utf8.char(tonumber(num_str, 16)), n + 1, pos + 6\n else\n local unesc = escapes[c]\n if not unesc then error_at(pos + 1, "Unknown escape character %q.", c) end\n buf[n], n, pos = unesc, n + 1, pos + 2\n end\n elseif c >= " " then\n local _, finish = find(str, char_pat, pos)\n buf[n], n = sub(str, pos, finish), n + 1\n pos = finish + 1\n else\n error_at(pos + 1, "Unescaped whitespace %q.", c)\n end\n end\n\n return concat(buf, "", 1, n - 1), pos + 1\n end\n\n local num_types = { b = true, B = true, s = true, S = true, l = true, L = true, f = true, F = true, d = true, D = true }\n local function parse_number(str, pos, opts)\n local _, last, num_str = find(str, \'^(-?%d+%.?%d*[eE]?[+-]?%d*)\', pos)\n local val = tonumber(num_str)\n if not val then error_at(pos, "Malformed number %q.", num_str) end\n\n if opts.nbt_style and num_types[sub(str, last + 1, last + 1)] then return val, last + 2 end\n\n return val, last + 1\n end\n\n local function parse_ident(str, pos)\n local _, last, val = find(str, \'^([%a][%w_]*)\', pos)\n return val, last + 1\n end\n\n local arr_types = { I = true, L = true, B = true }\n local function decode_impl(str, pos, opts)\n local c = sub(str, pos, pos)\n if c == \'"\' then return parse_string(str, pos + 1, \'"\')\n elseif c == "\'" and opts.nbt_style then return parse_string(str, pos + 1, "\\\'")\n elseif c == "-" or c >= "0" and c <= "9" then return parse_number(str, pos, opts)\n elseif c == "t" then\n if sub(str, pos + 1, pos + 3) == "rue" then return true, pos + 4 end\n elseif c == \'f\' then\n if sub(str, pos + 1, pos + 4) == "alse" then return false, pos + 5 end\n elseif c == \'n\' then\n if sub(str, pos + 1, pos + 3) == "ull" then\n if opts.parse_null then\n return json_null, pos + 4\n else\n return nil, pos + 4\n end\n end\n elseif c == "{" then\n local obj = {}\n\n pos = skip(str, pos + 1)\n c = sub(str, pos, pos)\n\n if c == "" then return error_at(pos, "Unexpected end of input, expected \'}\'.") end\n if c == "}" then return obj, pos + 1 end\n\n while true do\n local key, value\n if c == "\\"" then key, pos = parse_string(str, pos + 1, "\\"")\n elseif opts.nbt_style then key, pos = parse_ident(str, pos)\n else return expected(pos, c, "object key")\n end\n\n pos = skip(str, pos)\n\n c = sub(str, pos, pos)\n if c ~= ":" then return expected(pos, c, "\':\'") end\n\n value, pos = decode_impl(str, skip(str, pos + 1), opts)\n obj[key] = value\n\n -- Consume the next delimiter\n pos = skip(str, pos)\n c = sub(str, pos, pos)\n if c == "}" then break\n elseif c == "," then pos = skip(str, pos + 1)\n else return expected(pos, c, "\',\' or \'}\'")\n end\n\n c = sub(str, pos, pos)\n end\n\n return obj, pos + 1\n\n elseif c == "[" then\n local arr, n = {}, 1\n\n pos = skip(str, pos + 1)\n c = sub(str, pos, pos)\n\n if arr_types[c] and sub(str, pos + 1, pos + 1) == ";" and opts.nbt_style then\n pos = skip(str, pos + 2)\n c = sub(str, pos, pos)\n end\n\n if c == "" then return expected(pos, c, "\']\'") end\n if c == "]" then\n if opts.parse_empty_array ~= false then\n return empty_json_array, pos + 1\n else\n return {}, pos + 1\n end\n end\n\n while true do\n n, arr[n], pos = n + 1, decode_impl(str, pos, opts)\n\n -- Consume the next delimiter\n pos = skip(str, pos)\n c = sub(str, pos, pos)\n if c == "]" then break\n elseif c == "," then pos = skip(str, pos + 1)\n else return expected(pos, c, "\',\' or \']\'")\n end\n end\n\n return arr, pos + 1\n elseif c == "" then error_at(pos, \'Unexpected end of input.\')\n end\n\n error_at(pos, "Unexpected character %q.", c)\n end\n\n --[[- Converts a serialised JSON string back into a reassembled Lua object.\n\n This may be used with [`textutils.serializeJSON`], or when communicating\n with command blocks or web APIs.\n\n If a `null` value is encountered, it is converted into `nil`. It can be converted\n into [`textutils.json_null`] with the `parse_null` option.\n\n If an empty array is encountered, it is converted into [`textutils.empty_json_array`].\n It can be converted into a new empty table with the `parse_empty_array` option.\n\n @tparam string s The serialised string to deserialise.\n @tparam[opt] { nbt_style? = boolean, parse_null? = boolean, parse_empty_array? = boolean } options\n Options which control how this JSON object is parsed.\n\n - `nbt_style`: When true, this will accept [stringified NBT][nbt] strings,\n as produced by many commands.\n - `parse_null`: When true, `null` will be parsed as [`json_null`], rather than\n `nil`.\n - `parse_empty_array`: When false, empty arrays will be parsed as a new table.\n By default (or when this value is true), they are parsed as [`empty_json_array`].\n\n [nbt]: https://minecraft.wiki/w/NBT_format\n @return[1] The deserialised object\n @treturn[2] nil If the object could not be deserialised.\n @treturn string A message describing why the JSON string is invalid.\n @since 1.87.0\n @changed 1.100.6 Added `parse_empty_array` option\n @see textutils.json_null Use to serialize a JSON `null` value.\n @see textutils.empty_json_array Use to serialize a JSON empty array.\n @usage Unserialise a basic JSON object\n\n textutils.unserialiseJSON(\'{"name": "Steve", "age": null}\')\n\n @usage Unserialise a basic JSON object, returning null values as [`json_null`].\n\n textutils.unserialiseJSON(\'{"name": "Steve", "age": null}\', { parse_null = true })\n ]]\n unserialise_json = function(s, options)\n expect(1, s, "string")\n expect(2, options, "table", "nil")\n\n if options then\n field(options, "nbt_style", "boolean", "nil")\n field(options, "parse_null", "boolean", "nil")\n field(options, "parse_empty_array", "boolean", "nil")\n else\n options = {}\n end\n\n local ok, res, pos = pcall(decode_impl, s, skip(s, 1), options)\n if not ok then\n if type(res) == "table" and getmetatable(res) == mt then\n return nil, ("Malformed JSON at position %d: %s"):format(res.pos, res.msg)\n end\n\n error(res, 0)\n end\n\n pos = skip(s, pos)\n if pos <= #s then\n return nil, ("Malformed JSON at position %d: Unexpected trailing character %q."):format(pos, sub(s, pos, pos))\n end\n return res\n\n end\nend\n\n--[[- Convert a Lua object into a textual representation, suitable for\nsaving in a file or pretty-printing.\n\n@param t The object to serialise\n@tparam { compact? = boolean, allow_repetitions? = boolean } opts Options for serialisation.\n - `compact`: Do not emit indentation and other whitespace between terms.\n - `allow_repetitions`: Relax the check for recursive tables, allowing them to appear multiple\n times (as long as tables do not appear inside themselves).\n\n@treturn string The serialised representation\n@throws If the object contains a value which cannot be\nserialised. This includes functions and tables which appear multiple\ntimes.\n@see cc.pretty.pretty_print An alternative way to display a table, often more\nsuitable for pretty printing.\n@since 1.3\n@changed 1.97.0 Added `opts` argument.\n@usage Serialise a basic table.\n\n textutils.serialise({ 1, 2, 3, a = 1, ["another key"] = { true } })\n\n@usage Demonstrates some of the other options\n\n local tbl = { 1, 2, 3 }\n print(textutils.serialise({ tbl, tbl }, { allow_repetitions = true }))\n\n print(textutils.serialise(tbl, { compact = true }))\n]]\nfunction serialize(t, opts)\n local tTracking = {}\n expect(2, opts, "table", "nil")\n\n if opts then\n field(opts, "compact", "boolean", "nil")\n field(opts, "allow_repetitions", "boolean", "nil")\n else\n opts = {}\n end\n return serialize_impl(t, tTracking, "", opts)\nend\n\nserialise = serialize -- GB version\n\n--- Converts a serialised string back into a reassembled Lua object.\n--\n-- This is mainly used together with [`textutils.serialise`].\n--\n-- @tparam string s The serialised string to deserialise.\n-- @return[1] The deserialised object\n-- @treturn[2] nil If the object could not be deserialised.\n-- @since 1.3\nfunction unserialize(s)\n expect(1, s, "string")\n local func = load("return " .. s, "unserialize", "t", {})\n if func then\n local ok, result = pcall(func)\n if ok then\n return result\n end\n end\n return nil\nend\n\nunserialise = unserialize -- GB version\n\n--[[- Returns a JSON representation of the given data.\n\nThis function attempts to guess whether a table is a JSON array or\nobject. However, empty tables are assumed to be empty objects - use\n[`textutils.empty_json_array`] to mark an empty array.\n\nThis is largely intended for interacting with various functions from the\n[`commands`] API, though may also be used in making [`http`] requests.\n\n@param[1] t The value to serialise. Like [`textutils.serialise`], this should not\ncontain recursive tables or functions.\n@tparam[1,opt] { nbt_style? = boolean, unicode_strings? = boolean } options Options for serialisation.\n- `nbt_style`: Whether to produce NBT-style JSON (non-quoted keys) instead of standard JSON.\n- `unicode_strings`: Whether to treat strings as containing UTF-8 characters instead of\n using the default 8-bit character set.\n\n@param[2] t The value to serialise. Like [`textutils.serialise`], this should not\ncontain recursive tables or functions.\n@tparam[2] boolean bNBTStyle Whether to produce NBT-style JSON (non-quoted keys)\ninstead of standard JSON.\n\n@treturn string The JSON representation of the input.\n@throws If the object contains a value which cannot be serialised. This includes\nfunctions and tables which appear multiple times.\n\n@usage Serialise a simple object\n\n textutils.serialiseJSON({ values = { 1, "2", true } })\n\n@usage Serialise an object to a NBT-style string\n\n textutils.serialiseJSON({ values = { 1, "2", true } }, { nbt_style = true })\n\n@since 1.7\n@changed 1.106.0 Added `options` overload and `unicode_strings` option.\n\n@see textutils.json_null Use to serialise a JSON `null` value.\n@see textutils.empty_json_array Use to serialise a JSON empty array.\n]]\nfunction serializeJSON(t, options)\n expect(1, t, "table", "string", "number", "boolean")\n expect(2, options, "table", "boolean", "nil")\n if type(options) == "boolean" then\n options = { nbt_style = options }\n elseif type(options) == "table" then\n field(options, "nbt_style", "boolean", "nil")\n field(options, "unicode_strings", "boolean", "nil")\n end\n\n local tTracking = {}\n return serializeJSONImpl(t, tTracking, options)\nend\n\nserialiseJSON = serializeJSON -- GB version\n\nunserializeJSON = unserialise_json\nunserialiseJSON = unserialise_json\n\n--- Replaces certain characters in a string to make it safe for use in URLs or POST data.\n--\n-- @tparam string str The string to encode\n-- @treturn string The encoded string.\n-- @usage print("https://example.com/?view=" .. textutils.urlEncode("some text&things"))\n-- @since 1.31\nfunction urlEncode(str)\n expect(1, str, "string")\n if str then\n str = string.gsub(str, "\\n", "\\r\\n")\n str = string.gsub(str, "([^A-Za-z0-9 %-%_%.])", function(c)\n local n = string.byte(c)\n if n < 128 then\n -- ASCII\n return string.format("%%%02X", n)\n else\n -- Non-ASCII (encode as UTF-8)\n return\n string.format("%%%02X", 192 + bit32.band(bit32.arshift(n, 6), 31)) ..\n string.format("%%%02X", 128 + bit32.band(n, 63))\n end\n end)\n str = string.gsub(str, " ", "+")\n end\n return str\nend\n\nlocal tEmpty = {}\n\n--- Provides a list of possible completions for a partial Lua expression.\n--\n-- If the completed element is a table, suggestions will have `.` appended to\n-- them. Similarly, functions have `(` appended to them.\n--\n-- @tparam string sSearchText The partial expression to complete, such as a\n-- variable name or table index.\n--\n-- @tparam[opt] table tSearchTable The table to find variables in, defaulting to\n-- the global environment ([`_G`]). The function also searches the "parent"\n-- environment via the `__index` metatable field.\n--\n-- @treturn { string... } The (possibly empty) list of completions.\n-- @see shell.setCompletionFunction\n-- @see _G.read\n-- @usage textutils.complete( "pa", _ENV )\n-- @since 1.74\nfunction complete(sSearchText, tSearchTable)\n expect(1, sSearchText, "string")\n expect(2, tSearchTable, "table", "nil")\n\n if g_tLuaKeywords[sSearchText] then return tEmpty end\n local nStart = 1\n local nDot = string.find(sSearchText, ".", nStart, true)\n local tTable = tSearchTable or _ENV\n while nDot do\n local sPart = string.sub(sSearchText, nStart, nDot - 1)\n local value = tTable[sPart]\n if type(value) == "table" then\n tTable = value\n nStart = nDot + 1\n nDot = string.find(sSearchText, ".", nStart, true)\n else\n return tEmpty\n end\n end\n local nColon = string.find(sSearchText, ":", nStart, true)\n if nColon then\n local sPart = string.sub(sSearchText, nStart, nColon - 1)\n local value = tTable[sPart]\n if type(value) == "table" then\n tTable = value\n nStart = nColon + 1\n else\n return tEmpty\n end\n end\n\n local sPart = string.sub(sSearchText, nStart)\n local nPartLength = #sPart\n\n local tResults = {}\n local tSeen = {}\n while tTable do\n for k, v in pairs(tTable) do\n if not tSeen[k] and type(k) == "string" then\n if string.find(k, sPart, 1, true) == 1 then\n if not g_tLuaKeywords[k] and string.match(k, "^[%a_][%a%d_]*$") then\n local sResult = string.sub(k, nPartLength + 1)\n if nColon then\n if type(v) == "function" then\n table.insert(tResults, sResult .. "(")\n elseif type(v) == "table" then\n local tMetatable = getmetatable(v)\n if tMetatable and (type(tMetatable.__call) == "function" or type(tMetatable.__call) == "table") then\n table.insert(tResults, sResult .. "(")\n end\n end\n else\n if type(v) == "function" then\n sResult = sResult .. "("\n elseif type(v) == "table" and next(v) ~= nil then\n sResult = sResult .. "."\n end\n table.insert(tResults, sResult)\n end\n end\n end\n end\n tSeen[k] = true\n end\n local tMetatable = getmetatable(tTable)\n if tMetatable and type(tMetatable.__index) == "table" then\n tTable = tMetatable.__index\n else\n tTable = nil\n end\n end\n\n table.sort(tResults)\n return tResults\nend\n',"rom/apis/turtle/turtle.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--- @module turtle\n\nif not turtle then\n error("Cannot load turtle API on computer", 2)\nend\n\n--- The builtin turtle API, without any generated helper functions.\n--\n-- @deprecated Historically this table behaved differently to the main turtle API, but this is no longer the case. You\n-- should not need to use it.\nnative = turtle.native or turtle\n\nlocal function addCraftMethod(object)\n if peripheral.getType("left") == "workbench" then\n object.craft = function(...)\n return peripheral.call("left", "craft", ...)\n end\n elseif peripheral.getType("right") == "workbench" then\n object.craft = function(...)\n return peripheral.call("right", "craft", ...)\n end\n else\n object.craft = nil\n end\nend\n\n-- Put commands into environment table\nlocal env = _ENV\nfor k, v in pairs(native) do\n if k == "equipLeft" or k == "equipRight" then\n env[k] = function(...)\n local result, err = v(...)\n addCraftMethod(turtle)\n return result, err\n end\n else\n env[k] = v\n end\nend\naddCraftMethod(env)\n',"rom/apis/vector.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--- A basic 3D vector type and some common vector operations. This may be useful\n-- when working with coordinates in Minecraft\'s world (such as those from the\n-- [`gps`] API).\n--\n-- An introduction to vectors can be found on [Wikipedia][wiki].\n--\n-- [wiki]: http://en.wikipedia.org/wiki/Euclidean_vector\n--\n-- @module vector\n-- @since 1.31\n\n--- A 3-dimensional vector, with `x`, `y`, and `z` values.\n--\n-- This is suitable for representing both position and directional vectors.\n--\n-- @type Vector\nlocal vector = {\n --- Adds two vectors together.\n --\n -- @tparam Vector self The first vector to add.\n -- @tparam Vector o The second vector to add.\n -- @treturn Vector The resulting vector\n -- @usage v1:add(v2)\n -- @usage v1 + v2\n add = function(self, o)\n return vector.new(\n self.x + o.x,\n self.y + o.y,\n self.z + o.z\n )\n end,\n\n --- Subtracts one vector from another.\n --\n -- @tparam Vector self The vector to subtract from.\n -- @tparam Vector o The vector to subtract.\n -- @treturn Vector The resulting vector\n -- @usage v1:sub(v2)\n -- @usage v1 - v2\n sub = function(self, o)\n return vector.new(\n self.x - o.x,\n self.y - o.y,\n self.z - o.z\n )\n end,\n\n --- Multiplies a vector by a scalar value.\n --\n -- @tparam Vector self The vector to multiply.\n -- @tparam number m The scalar value to multiply with.\n -- @treturn Vector A vector with value `(x * m, y * m, z * m)`.\n -- @usage v:mul(3)\n -- @usage v * 3\n mul = function(self, m)\n return vector.new(\n self.x * m,\n self.y * m,\n self.z * m\n )\n end,\n\n --- Divides a vector by a scalar value.\n --\n -- @tparam Vector self The vector to divide.\n -- @tparam number m The scalar value to divide by.\n -- @treturn Vector A vector with value `(x / m, y / m, z / m)`.\n -- @usage v:div(3)\n -- @usage v / 3\n div = function(self, m)\n return vector.new(\n self.x / m,\n self.y / m,\n self.z / m\n )\n end,\n\n --- Negate a vector\n --\n -- @tparam Vector self The vector to negate.\n -- @treturn Vector The negated vector.\n -- @usage -v\n unm = function(self)\n return vector.new(\n -self.x,\n -self.y,\n -self.z\n )\n end,\n\n --- Compute the dot product of two vectors\n --\n -- @tparam Vector self The first vector to compute the dot product of.\n -- @tparam Vector o The second vector to compute the dot product of.\n -- @treturn Vector The dot product of `self` and `o`.\n -- @usage v1:dot(v2)\n dot = function(self, o)\n return self.x * o.x + self.y * o.y + self.z * o.z\n end,\n\n --- Compute the cross product of two vectors\n --\n -- @tparam Vector self The first vector to compute the cross product of.\n -- @tparam Vector o The second vector to compute the cross product of.\n -- @treturn Vector The cross product of `self` and `o`.\n -- @usage v1:cross(v2)\n cross = function(self, o)\n return vector.new(\n self.y * o.z - self.z * o.y,\n self.z * o.x - self.x * o.z,\n self.x * o.y - self.y * o.x\n )\n end,\n\n --- Get the length (also referred to as magnitude) of this vector.\n -- @tparam Vector self This vector.\n -- @treturn number The length of this vector.\n length = function(self)\n return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)\n end,\n\n --- Divide this vector by its length, producing with the same direction, but\n -- of length 1.\n --\n -- @tparam Vector self The vector to normalise\n -- @treturn Vector The normalised vector\n -- @usage v:normalize()\n normalize = function(self)\n return self:mul(1 / self:length())\n end,\n\n --- Construct a vector with each dimension rounded to the nearest value.\n --\n -- @tparam Vector self The vector to round\n -- @tparam[opt] number tolerance The tolerance that we should round to,\n -- defaulting to 1. For instance, a tolerance of 0.5 will round to the\n -- nearest 0.5.\n -- @treturn Vector The rounded vector.\n round = function(self, tolerance)\n tolerance = tolerance or 1.0\n return vector.new(\n math.floor((self.x + tolerance * 0.5) / tolerance) * tolerance,\n math.floor((self.y + tolerance * 0.5) / tolerance) * tolerance,\n math.floor((self.z + tolerance * 0.5) / tolerance) * tolerance\n )\n end,\n\n --- Convert this vector into a string, for pretty printing.\n --\n -- @tparam Vector self This vector.\n -- @treturn string This vector\'s string representation.\n -- @usage v:tostring()\n -- @usage tostring(v)\n tostring = function(self)\n return self.x .. "," .. self.y .. "," .. self.z\n end,\n\n --- Check for equality between two vectors.\n --\n -- @tparam Vector self The first vector to compare.\n -- @tparam Vector other The second vector to compare to.\n -- @treturn boolean Whether or not the vectors are equal.\n equals = function(self, other)\n return self.x == other.x and self.y == other.y and self.z == other.z\n end,\n}\n\nlocal vmetatable = {\n __index = vector,\n __add = vector.add,\n __sub = vector.sub,\n __mul = vector.mul,\n __div = vector.div,\n __unm = vector.unm,\n __tostring = vector.tostring,\n __eq = vector.equals,\n}\n\n--- Construct a new [`Vector`] with the given coordinates.\n--\n-- @tparam number x The X coordinate or direction of the vector.\n-- @tparam number y The Y coordinate or direction of the vector.\n-- @tparam number z The Z coordinate or direction of the vector.\n-- @treturn Vector The constructed vector.\nfunction new(x, y, z)\n return setmetatable({\n x = tonumber(x) or 0,\n y = tonumber(y) or 0,\n z = tonumber(z) or 0,\n }, vmetatable)\nend\n',"rom/apis/window.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[- A [terminal redirect][`term.Redirect`] occupying a smaller area of an\nexisting terminal. This allows for easy definition of spaces within the display\nthat can be written/drawn to, then later redrawn/repositioned/etc as need\nbe. The API itself contains only one function, [`window.create`], which returns\nthe windows themselves.\n\nWindows are considered terminal objects - as such, they have access to nearly\nall the commands in the term API (plus a few extras of their own, listed within\nsaid API) and are valid targets to redirect to.\n\nEach window has a "parent" terminal object, which can be the computer\'s own\ndisplay, a monitor, another window or even other, user-defined terminal\nobjects. Whenever a window is rendered to, the actual screen-writing is\nperformed via that parent (or, if that has one too, then that parent, and so\nforth). Bear in mind that the cursor of a window\'s parent will hence be moved\naround etc when writing a given child window.\n\nWindows retain a memory of everything rendered "through" them (hence acting as\ndisplay buffers), and if the parent\'s display is wiped, the window\'s content can\nbe easily redrawn later. A window may also be flagged as invisible, preventing\nany changes to it from being rendered until it\'s flagged as visible once more.\n\nA parent terminal object may have multiple children assigned to it, and windows\nmay overlap. For example, the Multishell system functions by assigning each tab\na window covering the screen, each using the starting terminal display as its\nparent, and only one of which is visible at a time.\n\n@module window\n@since 1.6\n]]\n\nlocal expect = dofile("rom/modules/main/cc/expect.lua").expect\n\nlocal tHex = {\n [colors.white] = "0",\n [colors.orange] = "1",\n [colors.magenta] = "2",\n [colors.lightBlue] = "3",\n [colors.yellow] = "4",\n [colors.lime] = "5",\n [colors.pink] = "6",\n [colors.gray] = "7",\n [colors.lightGray] = "8",\n [colors.cyan] = "9",\n [colors.purple] = "a",\n [colors.blue] = "b",\n [colors.brown] = "c",\n [colors.green] = "d",\n [colors.red] = "e",\n [colors.black] = "f",\n}\n\nlocal type = type\nlocal string_rep = string.rep\nlocal string_sub = string.sub\n\n--[[- Returns a terminal object that is a space within the specified parent\nterminal object. This can then be used (or even redirected to) in the same\nmanner as eg a wrapped monitor. Refer to [the term API][`term`] for a list of\nfunctions available to it.\n\n[`term`] itself may not be passed as the parent, though [`term.native`] is\nacceptable. Generally, [`term.current`] or a wrapped monitor will be most\nsuitable, though windows may even have other windows assigned as their\nparents.\n\n@tparam term.Redirect parent The parent terminal redirect to draw to.\n@tparam number nX The x coordinate this window is drawn at in the parent terminal\n@tparam number nY The y coordinate this window is drawn at in the parent terminal\n@tparam number nWidth The width of this window\n@tparam number nHeight The height of this window\n@tparam[opt] boolean bStartVisible Whether this window is visible by\ndefault. Defaults to `true`.\n@treturn Window The constructed window\n@since 1.6\n@usage Create a smaller window, fill it red and write some text to it.\n\n local my_window = window.create(term.current(), 1, 1, 20, 5)\n my_window.setBackgroundColour(colours.red)\n my_window.setTextColour(colours.white)\n my_window.clear()\n my_window.write("Testing my window!")\n\n@usage Create a smaller window and redirect to it.\n\n local my_window = window.create(term.current(), 1, 1, 25, 5)\n term.redirect(my_window)\n print("Writing some long text which will wrap around and show the bounds of this window.")\n\n]]\nfunction create(parent, nX, nY, nWidth, nHeight, bStartVisible)\n expect(1, parent, "table")\n expect(2, nX, "number")\n expect(3, nY, "number")\n expect(4, nWidth, "number")\n expect(5, nHeight, "number")\n expect(6, bStartVisible, "boolean", "nil")\n\n if parent == term then\n error("term is not a recommended window parent, try term.current() instead", 2)\n end\n\n local sEmptySpaceLine\n local tEmptyColorLines = {}\n local function createEmptyLines(nWidth)\n sEmptySpaceLine = string_rep(" ", nWidth)\n for n = 0, 15 do\n local nColor = 2 ^ n\n local sHex = tHex[nColor]\n tEmptyColorLines[nColor] = string_rep(sHex, nWidth)\n end\n end\n\n createEmptyLines(nWidth)\n\n -- Setup\n local bVisible = bStartVisible ~= false\n local nCursorX = 1\n local nCursorY = 1\n local bCursorBlink = false\n local nTextColor = colors.white\n local nBackgroundColor = colors.black\n local tLines = {}\n local tPalette = {}\n do\n local sEmptyText = sEmptySpaceLine\n local sEmptyTextColor = tEmptyColorLines[nTextColor]\n local sEmptyBackgroundColor = tEmptyColorLines[nBackgroundColor]\n for y = 1, nHeight do\n tLines[y] = { sEmptyText, sEmptyTextColor, sEmptyBackgroundColor }\n end\n\n for i = 0, 15 do\n local c = 2 ^ i\n tPalette[c] = { parent.getPaletteColour(c) }\n end\n end\n\n -- Helper functions\n local function updateCursorPos()\n if nCursorX >= 1 and nCursorY >= 1 and\n nCursorX <= nWidth and nCursorY <= nHeight then\n parent.setCursorPos(nX + nCursorX - 1, nY + nCursorY - 1)\n else\n parent.setCursorPos(0, 0)\n end\n end\n\n local function updateCursorBlink()\n parent.setCursorBlink(bCursorBlink)\n end\n\n local function updateCursorColor()\n parent.setTextColor(nTextColor)\n end\n\n local function redrawLine(n)\n local tLine = tLines[n]\n parent.setCursorPos(nX, nY + n - 1)\n parent.blit(tLine[1], tLine[2], tLine[3])\n end\n\n local function redraw()\n for n = 1, nHeight do\n redrawLine(n)\n end\n end\n\n local function updatePalette()\n for k, v in pairs(tPalette) do\n parent.setPaletteColour(k, v[1], v[2], v[3])\n end\n end\n\n local function internalBlit(sText, sTextColor, sBackgroundColor)\n local nStart = nCursorX\n local nEnd = nStart + #sText - 1\n if nCursorY >= 1 and nCursorY <= nHeight then\n if nStart <= nWidth and nEnd >= 1 then\n -- Modify line\n local tLine = tLines[nCursorY]\n if nStart == 1 and nEnd == nWidth then\n tLine[1] = sText\n tLine[2] = sTextColor\n tLine[3] = sBackgroundColor\n else\n local sClippedText, sClippedTextColor, sClippedBackgroundColor\n if nStart < 1 then\n local nClipStart = 1 - nStart + 1\n local nClipEnd = nWidth - nStart + 1\n sClippedText = string_sub(sText, nClipStart, nClipEnd)\n sClippedTextColor = string_sub(sTextColor, nClipStart, nClipEnd)\n sClippedBackgroundColor = string_sub(sBackgroundColor, nClipStart, nClipEnd)\n elseif nEnd > nWidth then\n local nClipEnd = nWidth - nStart + 1\n sClippedText = string_sub(sText, 1, nClipEnd)\n sClippedTextColor = string_sub(sTextColor, 1, nClipEnd)\n sClippedBackgroundColor = string_sub(sBackgroundColor, 1, nClipEnd)\n else\n sClippedText = sText\n sClippedTextColor = sTextColor\n sClippedBackgroundColor = sBackgroundColor\n end\n\n local sOldText = tLine[1]\n local sOldTextColor = tLine[2]\n local sOldBackgroundColor = tLine[3]\n local sNewText, sNewTextColor, sNewBackgroundColor\n if nStart > 1 then\n local nOldEnd = nStart - 1\n sNewText = string_sub(sOldText, 1, nOldEnd) .. sClippedText\n sNewTextColor = string_sub(sOldTextColor, 1, nOldEnd) .. sClippedTextColor\n sNewBackgroundColor = string_sub(sOldBackgroundColor, 1, nOldEnd) .. sClippedBackgroundColor\n else\n sNewText = sClippedText\n sNewTextColor = sClippedTextColor\n sNewBackgroundColor = sClippedBackgroundColor\n end\n if nEnd < nWidth then\n local nOldStart = nEnd + 1\n sNewText = sNewText .. string_sub(sOldText, nOldStart, nWidth)\n sNewTextColor = sNewTextColor .. string_sub(sOldTextColor, nOldStart, nWidth)\n sNewBackgroundColor = sNewBackgroundColor .. string_sub(sOldBackgroundColor, nOldStart, nWidth)\n end\n\n tLine[1] = sNewText\n tLine[2] = sNewTextColor\n tLine[3] = sNewBackgroundColor\n end\n\n -- Redraw line\n if bVisible then\n redrawLine(nCursorY)\n end\n end\n end\n\n -- Move and redraw cursor\n nCursorX = nEnd + 1\n if bVisible then\n updateCursorColor()\n updateCursorPos()\n end\n end\n\n --- The window object. Refer to the [module\'s documentation][`window`] for\n -- a full description.\n --\n -- @type Window\n -- @see term.Redirect\n local window = {}\n\n function window.write(sText)\n sText = tostring(sText)\n internalBlit(sText, string_rep(tHex[nTextColor], #sText), string_rep(tHex[nBackgroundColor], #sText))\n end\n\n function window.blit(sText, sTextColor, sBackgroundColor)\n if type(sText) ~= "string" then expect(1, sText, "string") end\n if type(sTextColor) ~= "string" then expect(2, sTextColor, "string") end\n if type(sBackgroundColor) ~= "string" then expect(3, sBackgroundColor, "string") end\n if #sTextColor ~= #sText or #sBackgroundColor ~= #sText then\n error("Arguments must be the same length", 2)\n end\n sTextColor = sTextColor:lower()\n sBackgroundColor = sBackgroundColor:lower()\n internalBlit(sText, sTextColor, sBackgroundColor)\n end\n\n function window.clear()\n local sEmptyText = sEmptySpaceLine\n local sEmptyTextColor = tEmptyColorLines[nTextColor]\n local sEmptyBackgroundColor = tEmptyColorLines[nBackgroundColor]\n for y = 1, nHeight do\n local line = tLines[y]\n line[1] = sEmptyText\n line[2] = sEmptyTextColor\n line[3] = sEmptyBackgroundColor\n end\n if bVisible then\n redraw()\n updateCursorColor()\n updateCursorPos()\n end\n end\n\n function window.clearLine()\n if nCursorY >= 1 and nCursorY <= nHeight then\n local line = tLines[nCursorY]\n line[1] = sEmptySpaceLine\n line[2] = tEmptyColorLines[nTextColor]\n line[3] = tEmptyColorLines[nBackgroundColor]\n if bVisible then\n redrawLine(nCursorY)\n updateCursorColor()\n updateCursorPos()\n end\n end\n end\n\n function window.getCursorPos()\n return nCursorX, nCursorY\n end\n\n function window.setCursorPos(x, y)\n if type(x) ~= "number" then expect(1, x, "number") end\n if type(y) ~= "number" then expect(2, y, "number") end\n nCursorX = math.floor(x)\n nCursorY = math.floor(y)\n if bVisible then\n updateCursorPos()\n end\n end\n\n function window.setCursorBlink(blink)\n if type(blink) ~= "boolean" then expect(1, blink, "boolean") end\n bCursorBlink = blink\n if bVisible then\n updateCursorBlink()\n end\n end\n\n function window.getCursorBlink()\n return bCursorBlink\n end\n\n local function isColor()\n return parent.isColor()\n end\n\n function window.isColor()\n return isColor()\n end\n\n function window.isColour()\n return isColor()\n end\n\n local function setTextColor(color)\n if type(color) ~= "number" then expect(1, color, "number") end\n if tHex[color] == nil then\n error("Invalid color (got " .. color .. ")" , 2)\n end\n\n nTextColor = color\n if bVisible then\n updateCursorColor()\n end\n end\n\n window.setTextColor = setTextColor\n window.setTextColour = setTextColor\n\n function window.setPaletteColour(colour, r, g, b)\n if type(colour) ~= "number" then expect(1, colour, "number") end\n\n if tHex[colour] == nil then\n error("Invalid color (got " .. colour .. ")" , 2)\n end\n\n local tCol\n if type(r) == "number" and g == nil and b == nil then\n tCol = { colours.unpackRGB(r) }\n tPalette[colour] = tCol\n else\n if type(r) ~= "number" then expect(2, r, "number") end\n if type(g) ~= "number" then expect(3, g, "number") end\n if type(b) ~= "number" then expect(4, b, "number") end\n\n tCol = tPalette[colour]\n tCol[1] = r\n tCol[2] = g\n tCol[3] = b\n end\n\n if bVisible then\n return parent.setPaletteColour(colour, tCol[1], tCol[2], tCol[3])\n end\n end\n\n window.setPaletteColor = window.setPaletteColour\n\n function window.getPaletteColour(colour)\n if type(colour) ~= "number" then expect(1, colour, "number") end\n if tHex[colour] == nil then\n error("Invalid color (got " .. colour .. ")" , 2)\n end\n local tCol = tPalette[colour]\n return tCol[1], tCol[2], tCol[3]\n end\n\n window.getPaletteColor = window.getPaletteColour\n\n local function setBackgroundColor(color)\n if type(color) ~= "number" then expect(1, color, "number") end\n if tHex[color] == nil then\n error("Invalid color (got " .. color .. ")", 2)\n end\n nBackgroundColor = color\n end\n\n window.setBackgroundColor = setBackgroundColor\n window.setBackgroundColour = setBackgroundColor\n\n function window.getSize()\n return nWidth, nHeight\n end\n\n function window.scroll(n)\n if type(n) ~= "number" then expect(1, n, "number") end\n if n ~= 0 then\n local tNewLines = {}\n local sEmptyText = sEmptySpaceLine\n local sEmptyTextColor = tEmptyColorLines[nTextColor]\n local sEmptyBackgroundColor = tEmptyColorLines[nBackgroundColor]\n for newY = 1, nHeight do\n local y = newY + n\n if y >= 1 and y <= nHeight then\n tNewLines[newY] = tLines[y]\n else\n tNewLines[newY] = { sEmptyText, sEmptyTextColor, sEmptyBackgroundColor }\n end\n end\n tLines = tNewLines\n if bVisible then\n redraw()\n updateCursorColor()\n updateCursorPos()\n end\n end\n end\n\n function window.getTextColor()\n return nTextColor\n end\n\n function window.getTextColour()\n return nTextColor\n end\n\n function window.getBackgroundColor()\n return nBackgroundColor\n end\n\n function window.getBackgroundColour()\n return nBackgroundColor\n end\n\n --- Get the buffered contents of a line in this window.\n --\n -- @tparam number y The y position of the line to get.\n -- @treturn string The textual content of this line.\n -- @treturn string The text colours of this line, suitable for use with [`term.blit`].\n -- @treturn string The background colours of this line, suitable for use with [`term.blit`].\n -- @throws If `y` is not between 1 and this window\'s height.\n -- @since 1.84.0\n function window.getLine(y)\n if type(y) ~= "number" then expect(1, y, "number") end\n\n if y < 1 or y > nHeight then\n error("Line is out of range.", 2)\n end\n\n local line = tLines[y]\n return line[1], line[2], line[3]\n end\n\n -- Other functions\n\n --- Set whether this window is visible. Invisible windows will not be drawn\n -- to the screen until they are made visible again.\n --\n -- Making an invisible window visible will immediately draw it.\n --\n -- @tparam boolean visible Whether this window is visible.\n function window.setVisible(visible)\n if type(visible) ~= "boolean" then expect(1, visible, "boolean") end\n if bVisible ~= visible then\n bVisible = visible\n if bVisible then\n window.redraw()\n end\n end\n end\n\n --- Get whether this window is visible. Invisible windows will not be\n -- drawn to the screen until they are made visible again.\n --\n -- @treturn boolean Whether this window is visible.\n -- @see Window:setVisible\n -- @since 1.94.0\n function window.isVisible()\n return bVisible\n end\n --- Draw this window. This does nothing if the window is not visible.\n --\n -- @see Window:setVisible\n function window.redraw()\n if bVisible then\n redraw()\n updatePalette()\n updateCursorBlink()\n updateCursorColor()\n updateCursorPos()\n end\n end\n\n --- Set the current terminal\'s cursor to where this window\'s cursor is. This\n -- does nothing if the window is not visible.\n function window.restoreCursor()\n if bVisible then\n updateCursorBlink()\n updateCursorColor()\n updateCursorPos()\n end\n end\n\n --- Get the position of the top left corner of this window.\n --\n -- @treturn number The x position of this window.\n -- @treturn number The y position of this window.\n function window.getPosition()\n return nX, nY\n end\n\n --- Reposition or resize the given window.\n --\n -- This function also accepts arguments to change the size of this window.\n -- It is recommended that you fire a `term_resize` event after changing a\n -- window\'s, to allow programs to adjust their sizing.\n --\n -- @tparam number new_x The new x position of this window.\n -- @tparam number new_y The new y position of this window.\n -- @tparam[opt] number new_width The new width of this window.\n -- @tparam number new_height The new height of this window.\n -- @tparam[opt] term.Redirect new_parent The new redirect object this\n -- window should draw to.\n -- @changed 1.85.0 Add `new_parent` parameter.\n function window.reposition(new_x, new_y, new_width, new_height, new_parent)\n if type(new_x) ~= "number" then expect(1, new_x, "number") end\n if type(new_y) ~= "number" then expect(2, new_y, "number") end\n if new_width ~= nil or new_height ~= nil then\n expect(3, new_width, "number")\n expect(4, new_height, "number")\n end\n if new_parent ~= nil and type(new_parent) ~= "table" then expect(5, new_parent, "table") end\n\n nX = new_x\n nY = new_y\n\n if new_parent then parent = new_parent end\n\n if new_width and new_height then\n local tNewLines = {}\n createEmptyLines(new_width)\n local sEmptyText = sEmptySpaceLine\n local sEmptyTextColor = tEmptyColorLines[nTextColor]\n local sEmptyBackgroundColor = tEmptyColorLines[nBackgroundColor]\n for y = 1, new_height do\n if y > nHeight then\n tNewLines[y] = { sEmptyText, sEmptyTextColor, sEmptyBackgroundColor }\n else\n local tOldLine = tLines[y]\n if new_width == nWidth then\n tNewLines[y] = tOldLine\n elseif new_width < nWidth then\n tNewLines[y] = {\n string_sub(tOldLine[1], 1, new_width),\n string_sub(tOldLine[2], 1, new_width),\n string_sub(tOldLine[3], 1, new_width),\n }\n else\n tNewLines[y] = {\n tOldLine[1] .. string_sub(sEmptyText, nWidth + 1, new_width),\n tOldLine[2] .. string_sub(sEmptyTextColor, nWidth + 1, new_width),\n tOldLine[3] .. string_sub(sEmptyBackgroundColor, nWidth + 1, new_width),\n }\n end\n end\n end\n nWidth = new_width\n nHeight = new_height\n tLines = tNewLines\n end\n if bVisible then\n window.redraw()\n end\n end\n\n if bVisible then\n window.redraw()\n end\n return window\nend\n',"rom/autorun/.ignoreme":'--[[\nAlright then, don\'t ignore me. This file is to ensure the existence of the "autorun" folder, files placed in this folder\nusing resource packs will always run when computers startup.\n]]\n',"rom/help/adventure.txt":'adventure is a text adventure game for CraftOS. To navigate around the world of adventure, type simple instructions to the interpreter, for example: "go north", "punch tree", "craft planks", "mine coal with pickaxe", "hit creeper with sword"\n',"rom/help/alias.txt":'alias assigns shell commands to run other programs.\n\nex:\n"alias dir ls" will make the "dir" command run the "ls" program\n"alias dir" will remove the alias set on "dir"\n"alias" will list all current aliases.\n',"rom/help/apis.txt":'apis lists the currently loaded APIs available to programs in CraftOS.\n\nType "help <api>" to see help for a specific api.\nCall os.loadAPI( path ) to load extra apis.\n',"rom/help/bg.txt":'bg is a program for Advanced Computers which opens a new tab in the background.\n\nex:\n"bg" will open a background tab running the shell\n"bg worm" will open a background tab running the "worm" program\n',"rom/help/bit.txt":"Functions in the bit manipulation API (NOTE: This API will be removed in a future version. Use bit32 instead):\nbit.bnot(n) -- bitwise not (~n)\nbit.band(m, n) -- bitwise and (m & n)\nbit.bor(m, n) -- bitwise or (m | n)\nbit.bxor(m, n) -- bitwise xor (m ^ n)\nbit.brshift(n, bits) -- right shift (n >> bits)\nbit.blshift(n, bits) -- left shift (n << bits)\n","rom/help/bundled.txt":'To set bundled outputs:\nc = colors.combine( colors.red, colors.blue )\nrs.setBundledOutput( "left", c )\n\nc = colors.combine( c, colors.green )\nrs.setBundledOutput( "left", c )\n\nc = colors.subtract( c, colors.blue )\nrs.setBundledOutput( "left", c )\n\nTo get bundled inputs:\nc = rs.getBundledInput( "right" )\nred = colors.test( c, colors.red )\n\nType "help colors" for the list of wire colors.\n',"rom/help/cd.txt":'cd changes the directory you\'re in.\n\nex:\n"cd rom" will move to "rom" folder.\n"cd .." will move up one folder.\n"cd /" will move to the root.\n',"rom/help/changelog.md":'# New features in CC: Tweaked 1.108.4\n\n* Rewrite `@LuaFunction` generation to use `MethodHandle`s instead of ASM.\n* Refactor `ComputerThread` to provide a cleaner interface.\n* Remove `disable_lua51_features` config option.\n* Update several translations (Sammy).\n\nSeveral bug fixes:\n* Fix monitor peripheral becoming "detached" after breaking and replacing a monitor.\n* Fix signs being empty when placed.\n* Fix several inconsistencies with mount error messages.\n\n# New features in CC: Tweaked 1.108.3\n\nSeveral bug fixes:\n* Fix disconnect when joining a dedicated server.\n\n# New features in CC: Tweaked 1.108.2\n\n* Add a tag for which blocks wired modems should ignore.\n\nSeveral bug fixes:\n* Fix monitors sometimes being warped after resizing.\n* Fix the skull recipes using the wrong UUID format.\n* Fix paint canvas not always being redrawn after a term resize.\n\n# New features in CC: Tweaked 1.108.1\n\nSeveral bug fixes:\n* Prevent no-opped players breaking or placing command computers.\n* Allow using `@LuaFunction`-annotated methods on classes defined in child classloaders.\n\n# New features in CC: Tweaked 1.108.0\n\n* Remove compression from terminal/monitor packets. Vanilla applies its own compression, so this ends up being less helpful than expected.\n* `/computercraft` command now supports permission mods.\n* Split some GUI textures into sprite sheets.\n* Support the `%g` character class in string pattern matching.\n\nSeveral bug fixes:\n* Fix crash when playing some modded records via a disk drive.\n* Fix race condition when computers attach or detach from a monitor.\n* Fix the "max websocket message" config option not being read.\n* `tostring` now correctly obeys `__name`.\n* Fix several inconsistencies with pattern matching character classes.\n\n# New features in CC: Tweaked 1.107.0\n\n* Add `disabled_generic_methods` config option to disable generic methods.\n* Add basic integration with EMI.\n* Enchanted turtle tools now render with a glint.\n* Update several translations (PatriikPlays, 1Turtle, Ale32bit).\n\nSeveral bug fixes:\n* Fix client config file being generated on a dedicated server.\n* Fix numbers ending in "f" or "d" being treated as avalid.\n* Fix `string.pack`\'s "z" specifier causing out-of-bounds errors.\n* Fix several issues with `turtle.dig`\'s custom actions (tilling, making paths).\n\n# New features in CC: Tweaked 1.106.1\n\nSeveral bug fixes:\n* Block the CGNAT range (100.64.0.0/10) by default.\n* Fix conflicts with other mods replacing reach distance.\n\n# New features in CC: Tweaked 1.106.0\n\n* Numerous documentation improvements (MCJack123, znepb, penguinencounter).\n* Port `fs.find` to Lua. This also allows using `?` as a wildcard.\n* Computers cursors now glow in the dark.\n* Allow changing turtle upgrades from the GUI.\n* Add option to serialize Unicode strings to JSON (MCJack123).\n* Small optimisations to the `window` API.\n* Turtle upgrades can now preserve NBT from upgrade item stack and when broken.\n* Add support for tool enchantments and durability via datapacks. This is disabled for the built-in tools.\n\nSeveral bug fixes:\n* Fix turtles rendering incorrectly when upside down.\n* Fix misplaced calls to IArguments.escapes.\n* Lua REPL no longer accepts `)(` as a valid expression.\n* Fix several inconsistencies with `require`/`package.path` in the Lua REPL (Wojbie).\n* Fix turtle being able to place water buckets outside its reach distance.\n* Fix private several IP address ranges not being blocked by the `$private` rule.\n* Improve permission checks in the `/computercraft` command.\n\n# New features in CC: Tweaked 1.105.0\n\n* Optimise JSON string parsing.\n* Add `colors.fromBlit` (Erb3).\n* Upload file size limit is now configurable (khankul).\n* Wired cables no longer have a distance limit.\n* Java methods now coerce values to strings consistently with Lua.\n* Add custom timeout support to the HTTP API.\n* Support custom proxies for HTTP requests (Lemmmy).\n* The `speaker` program now errors when playing HTML files.\n* `edit` now shows an error message when editing read-only files.\n* Update Ukranian translation (SirEdvin).\n\nSeveral bug fixes:\n* Allow GPS hosts to only be 1 block apart.\n* Fix "Turn On"/"Turn Off" buttons being inverted in the computer GUI (Erb3).\n* Fix arrow keys not working in the printout UI.\n* Several documentation fixes (zyxkad, Lupus590, Commandcracker).\n* Fix monitor renderer debug text always being visible on Forge.\n* Fix crash when another mod changes the LoggerContext.\n* Fix the `monitor_renderer` option not being present in Fabric config files.\n* Pasting on MacOS/OSX now uses Cmd+V rather than Ctrl+V.\n* Fix turtles placing blocks upside down when at y<0.\n\n# New features in CC: Tweaked 1.104.0\n\n* Update to Minecraft 1.19.4.\n* Turtles can now right click items "into" certain blocks (cauldrons and hives by default, configurable with the `computercraft:turtle_can_use` block tag).\n* Update Cobalt to 0.7:\n * `table` methods and `ipairs` now use metamethods.\n * Type errors now use the `__name` metatag.\n * Coroutines no longer run on multiple threads.\n * Timeout errors should be thrown more reliably.\n* `speaker` program now reports an error on common unsupported audio formats.\n* `multishell` now hides the implementation details of its terminal redirect from programs.\n* Use VBO monitor renderer by default.\n* Improve syntax errors when missing commas in tables, and on trailing commas in parameter lists.\n* Turtles can now hold flags.\n* Update several translations (Alessandro, chesiren, Erlend, RomanPlayer22).\n\nSeveral bug fixes:\n* `settings.load` now ignores malformed values created by editing the `.settings` file by hand.\n* Fix introduction dates on `os.cancelAlarm` and `os.cancelTimer` (MCJack123).\n* Fix the REPL syntax reporting crashing on valid parses.\n* Make writes to the ID file atomic.\n* Obey stack limits when transferring items with Fabric\'s APIs.\n* Ignore metatables in `textutils.serialize`.\n* Correctly recurse into NBT lists when computing the NBT hash (Lemmmy).\n* Fix advanced pocket computers rendering as greyscale.\n* Fix stack overflow when using `shell` as a hashbang program.\n* Fix websocket messages being empty when using a non-default compression settings.\n* Fix `gps.locate` returning `nan` when receiving a duplicate location (Wojbie).\n* Remove several thread safety issues inside Java-side argument parsing code.\n\n# New features in CC: Tweaked 1.103.1\n\nSeveral bug fixes:\n* Fix values not being printed in the REPL.\n* Fix `function f()` providing suboptimal parse errors in the REPL.\n\n# New features in CC: Tweaked 1.103.0\n\n* The shell now supports hashbangs (`#!`) (emmachase).\n* Error messages in `edit` are now displayed in red on advanced computers.\n* `turtle.getItemDetail` now always includes the `nbt` hash.\n* Improvements to the display of errors in the shell and REPL.\n* Turtles, pocket computers, and disks can be undyed by careful application (i.e. crafting) of a sponge.\n* Turtles can no longer be dyed/undyed by right clicking.\n\nSeveral bug fixes:\n* Several documentation improvements and fixes (ouroborus, LelouBil).\n* Fix rednet queueing the wrong message when sending a message to the current computer.\n* Fix the Lua VM crashing when a `__len` metamethod yields.\n* `pocket.{un,}equipBack` now correctly copies the stack when unequipping an upgrade.\n* Fix `key` events not being queued while pressing computer shortcuts.\n\n# New features in CC: Tweaked 1.102.2\n\nSeveral bug fixes:\n* Fix printouts crashing in item frames.\n* Fix disks not being assigned an ID when placed in a disk drive.\n\n# New features in CC: Tweaked 1.102.1\n\nSeveral bug fixes:\n* Fix crash on Fabric when refuelling with a non-fuel item (emmachase).\n* Fix crash when calling `pocket.equipBack()` with a wireless modem.\n* Fix turtles dropping their inventory when moving (emmachase).\n* Fix crash when inserting items into a full inventory (emmachase).\n* Simplify wired cable breaking code, fixing items sometimes not dropping.\n* Correctly handle double chests being treated as single chests under Fabric.\n* Fix `mouse_up` not being fired under Fabric.\n* Fix full-block Wired modems not connecting to adjacent cables when placed.\n* Hide the search tab from the `itemGroups` item details.\n* Fix speakers playing too loudly.\n* Change where turtles drop items from, reducing the chance that items clip through blocks.\n* Fix the `computer_threads` config option not applying under Fabric.\n* Fix stack overflow in logging code.\n\n# New features in CC: Tweaked 1.102.0\n\n* `fs.isReadOnly` now reads filesystem attributes (Lemmmy).\n* `IComputerAccess.executeMainThreadTask` no longer roundtrips values through Lua.\n* The turtle label now animates when the turtle moves.\n\nSeveral bug fixes:\n* Trim spaces from filesystem paths.\n* Correctly format 12AM/PM with `%I`.\n* Fix `import.lua` failing to upload a file.\n* Fix duplicated swing animations on high-ping servers (emmachase).\n* Fix several issues with sparse Lua tables (Shiranuit).\n\n# New features in CC: Tweaked 1.101.1\n\nSeveral bug fixes:\n* Improve validation of rednet messages (Ale32bit).\n* Fix `turtle.refuel()` always failing.\n\n# New features in CC: Tweaked 1.101.0\n\n* Improve Dutch translation (Quezler)\n* Better reporting of fatal computer timeouts in the server log.\n* Convert detail providers into a registry, allowing peripheral mods to read item/block details.\n* Redesign the metrics system. `/computercraft track` now allows computing aggregates (total, max, avg) on any metric, not just computer time.\n* File drag-and-drop now queues a `file_transfer` event on the computer. The built-in shell or the `import` program must now be running to upload files.\n* The `peripheral` now searches for remote peripherals using any peripheral with the `peripheral_hub` type, not just wired modems.\n* Add `include_hidden` option to `fs.complete`, which can be used to prevent hidden files showing up in autocomplete results. (IvoLeal72).\n* Add `shell.autocomplete_hidden` setting. (IvoLeal72)\n\nSeveral bug fixes:\n* Prevent `edit`\'s "Run" command scrolling the terminal output on smaller screens.\n* Remove some non-determinism in computing item\'s `nbt` hash.\n* Don\'t set the `Origin` header on outgoing websocket requests.\n\n# New features in CC: Tweaked 1.100.10\n\n* Mention WAV support in speaker help (MCJack123).\n* Add http programs to the path, even when http is not enabled.\n\nSeveral bug fixes:\n* Fix example in `textutils.pagedTabulate` docs (IvoLeal72).\n* Fix help program treating the terminal one line longer than it was.\n* Send block updates to client when turtle moves (roland-a).\n* Resolve several monitor issues when running Occulus shaders.\n\n# New features in CC: Tweaked 1.100.9\n\n* Add documentation for setting up GPS (Lupus590).\n* Add WAV support to the `speaker` program (MCJack123).\n* Expose item groups in `getItemDetail` (itisluiz).\n* Other fixes to documentation (Erb3, JohnnyIrvin).\n* Add Norwegian translation (Erb3).\n\nSeveral bug fixes:\n* Fix z-fighting on bold printout borders (toad-dev).\n* Fix `term.blit` failing on certain strings.\n* Fix `getItemLimit()` using the wrong slot (heap-underflow).\n* Increase size of monitor depth blocker.\n\n# New features in CC: Tweaked 1.100.8\n\nSeveral bug fixes:\n* Fix NPE within disk drive and printer code.\n\n# New features in CC: Tweaked 1.100.7\n\n* Fix failing to launch outside of a dev environment.\n\n\n# New features in CC: Tweaked 1.100.6\n\n* Various documentation improvements (MCJack123, FayneAldan).\n* Allow CC\'s blocks to be rotated when used in structure blocks (Seniorendi).\n* Several performance improvements to computer execution.\n* Add parse_empty_array option to textutils.unserialiseJSON (@ChickChicky).\n* Add an API to allow other mods to provide extra item/block details (Lemmmy).\n* All blocks with GUIs can now be "locked" (via a command or NBT editing tools) like vanilla inventories. Players can only interact with them with a specific named item.\n\nSeveral bug fixes:\n* Fix printouts being rendered with an offset in item frames (coolsa).\n* Reduce position latency when playing audio with a noisy pocket computer.\n* Fix total counts in /computercraft turn-on/shutdown commands.\n* Fix "Run" command not working in the editor when run from a subdirectory (Wojbie).\n* Pocket computers correctly preserve their on state.\n\n# New features in CC: Tweaked 1.100.5\n\n* Generic peripherals now use capabilities on the given side if one isn\'t provided on the internal side.\n* Improve performance of monitor rendering.\n\nSeveral bug fixes:\n* Various documentation fixes (bclindner, Hasaabitt)\n* Speaker sounds are now correctly positioned on the centre of the speaker block.\n\n# New features in CC: Tweaked 1.100.4\n\nSeveral bug fixes:\n* Fix the monitor watching blocking the main thread when chunks are slow to load.\n\n# New features in CC: Tweaked 1.100.3\n\nSeveral bug fixes:\n* Fix client disconnect when uploading large files.\n* Correctly handling empty computer ID file.\n* Fix the normal turtle recipe not being unlocked.\n* Remove turtle fake EntityType.\n\n# New features in CC: Tweaked 1.100.2\n\nSeveral bug fixes:\n* Fix wired modems swapping the modem/peripheral block state.\n* Remove debugging logging line from `turtle.attack`.\n\n# New features in CC: Tweaked 1.100.1\n\nSeveral bug fixes:\n* Fix `peripheral.hasType` not working with wired modems (Toad-Dev).\n* Fix crashes when noisy pocket computer are shutdown.\n\n# New features in CC: Tweaked 1.100.0\n\n* Speakers can now play arbitrary PCM audio.\n* Add support for encoding and decoding DFPWM streams, with the `cc.audio.dfpwm` module.\n* Wired modems now only render breaking progress for the part which is being broken.\n* Various documentation improvements.\n\nSeveral bug fixes:\n* Fix the "repeat" program not repeating broadcast rednet messages.\n* Fix the drag-and-drop upload functionality writing empty files.\n* Prevent turtles from pushing non-pushable entities.\n\n# New features in CC: Tweaked 1.99.1\n\n* Add package.searchpath to the cc.require API. (MCJack123)\n* Provide a more efficient way for the Java API to consume Lua tables in certain restricted cases.\n\nSeveral bug fixes:\n* Fix keys being "sticky" when opening the off-hand pocket computer GUI.\n* Correctly handle broken coroutine managers resuming Java code with a `nil` event.\n* Prevent computer buttons stealing focus from the terminal.\n* Fix a class cast exception when a monitor is malformed in ways I do not quite understand.\n\n# New features in CC: Tweaked 1.99.0\n\n* Pocket computers in their offhand will open without showing a terminal. You can look around and interact with the world, but your keyboard will be forwarded to the computer. (Wojbie, MagGen-hub).\n* Peripherals can now have multiple types. `peripheral.getType` now returns multiple values, and `peripheral.hasType` checks if a peripheral has a specific type.\n* Add several missing keys to the `keys` table. (ralphgod3)\n* Add feature introduction/changed version information to the documentation. (MCJack123)\n* Increase the file upload limit to 512KiB.\n* Rednet can now handle computer IDs larger than 65535. (Ale32bit)\n* Optimise deduplication of rednet messages (MCJack123)\n* Make `term.blit` colours case insensitive. (Ocawesome101)\n* Add a new `about` program for easier version identification. (MCJack123)\n* Optimise peripheral calls in `rednet.run`. (xAnavrins)\n* Add dimension parameter to `commands.getBlockInfo`.\n* Add `cc.pretty.pretty_print` helper function (Lupus590).\n* Add back JEI integration.\n* Turtle and pocket computer upgrades can now be added and modified with data packs.\n* Various translation updates (MORIMORI3017, Ale2Bit, mindy15963)\n\nAnd several bug fixes:\n* Fix various computer commands failing when OP level was 4.\n* Various documentation fixes. (xXTurnerLP, MCJack123)\n* Fix `textutils.serialize` not serialising infinity and nan values. (Wojbie)\n* Wired modems now correctly clean up mounts when a peripheral is detached.\n* Fix incorrect turtle and pocket computer upgrade recipes in the recipe book.\n* Fix speakers not playing sounds added via resource packs which are not registered in-game.\n* Fix speaker upgrades sending packets after the server has stopped.\n* Monitor sizing has been rewritten, hopefully making it more stable.\n* Peripherals are now invalidated when the computer ticks, rather than when the peripheral changes.\n* Fix printouts and pocket computers rendering at fullbright when in item frames.\n* All mod blocks now have an effective tool (pickaxe).\n\n# New features in CC: Tweaked 1.98.2\n\n* Add JP translation (MORIMORI0317)\n* Migrate several recipes to data generators.\n\nSeveral bug fixes:\n* Fix volume speaker sounds are played at.\n* Fix several rendering issues when holding pocket computers and printouts in hand.\n* Ensure wired modems and cables join the wired network on chunk load.\n* Fix stack overflow when using wired networks.\n\n# New features in CC: Tweaked 1.98.1\n\nSeveral bug fixes:\n* Fix monitors not correctly resizing when placed.\n* Update Russian translation (DrHesperus).\n\n# New features in CC: Tweaked 1.98.0\n* Add motd for file uploading.\n* Add config options to limit total bandwidth used by the HTTP API.\n\nAnd several bug fixes:\n* Fix `settings.define` not accepting a nil second argument (SkyTheCodeMaster).\n* Various documentation fixes (Angalexik, emiliskiskis, SkyTheCodeMaster).\n* Fix selected slot indicator not appearing in turtle interface.\n* Fix crash when printers are placed as part of world generation.\n* Fix crash when breaking a speaker on a multiplayer world.\n* Add a missing type check for `http.checkURL`.\n* Prevent `parallel.*` from hanging when no arguments are given.\n* Prevent issue in rednet when the message ID is NaN.\n* Fix `help` program crashing when terminal changes width.\n* Ensure monitors are well-formed when placed, preventing graphical glitches when using Carry On or Quark.\n* Accept several more extensions in the websocket client.\n* Prevent `wget` crashing when given an invalid URL and no filename.\n* Correctly wrap string within `textutils.slowWrite`.\n\n# New features in CC: Tweaked 1.97.0\n\n* Update several translations (Anavrins, Jummit, Naheulf).\n* Add button to view a computer\'s folder to `/computercraft dump`.\n* Allow cleaning dyed turtles in a cauldron.\n* Add scale subcommand to `monitor` program (MCJack123).\n* Add option to make `textutils.serialize` not write an indent (magiczocker10).\n* Allow comparing vectors using `==` (fatboychummy).\n* Improve HTTP error messages for SSL failures.\n* Allow `craft` program to craft unlimited items (fatboychummy).\n* Impose some limits on various command queues.\n* Add buttons to shutdown and terminate to computer GUIs.\n* Add program subcompletion to several programs (Wojbie).\n* Update the `help` program to accept and (partially) highlight markdown files.\n* Remove config option for the debug API.\n* Allow setting the subprotocol header for websockets.\n* Add basic JMX monitoring on dedicated servers.\n* Add support for MoreRed bundled.\n* Allow uploading files by dropping them onto a computer.\n\nAnd several bug fixes:\n* Fix NPE when using a treasure disk when no treasure disks are available.\n* Prevent command computers discarding command output when certain game rules are off.\n* Fix turtles not updating peripherals when upgrades are unequipped (Ronan-H).\n* Fix computers not shutting down on fatal errors within the Lua VM.\n* Speakers now correctly stop playing when broken, and sound follows noisy turtles and pocket computers.\n* Update the `wget` to be more resiliant in the face of user-errors.\n* Fix exiting `paint` typing "e" in the shell.\n* Fix coloured pocket computers using the wrong texture.\n* Correctly render the transparent background on pocket/normal computers.\n* Don\'t apply CraftTweaker actions twice on single-player worlds.\n\n# New features in CC: Tweaked 1.96.0\n\n* Use lightGrey for folders within the "list" program.\n* Add `getItemLimit` to inventory peripherals.\n* Expose the generic peripheral system to the public API.\n* Add cc.expect.range (Lupus590).\n* Allow calling cc.expect directly (MCJack123).\n* Numerous improvements to documentation.\n\nAnd several bug fixes:\n* Fix paintutils.drawLine incorrectly sorting coordinates (lilyzeiset).\n* Improve JEI\'s handling of turtle/pocket upgrade recipes.\n* Correctly handle sparse arrays in cc.pretty.\n* Fix crashes when a turtle places a monitor (baeuric).\n* Fix very large resource files being considered empty.\n* Allow turtles to use compostors.\n* Fix dupe bug when colouring turtles.\n\n# New features in CC: Tweaked 1.95.3\n\nSeveral bug fixes:\n* Correctly serialise sparse arrays into JSON (livegamer999)\n* Fix hasAudio/playAudio failing on record discs.\n* Fix rs.getBundledInput returning the output instead (SkyTheCodeMaster)\n* Programs run via edit are now a little better behaved (Wojbie)\n* Add User-Agent to a websocket\'s headers.\n\n# New features in CC: Tweaked 1.95.2\n\n* Add `isReadOnly` to `fs.attributes` (Lupus590)\n* Many more programs now support numpad enter (Wojbie)\n\nSeveral bug fixes:\n* Fix some commands failing to parse on dedicated servers.\n* Fix all disk recipes appearing to produce a white disk in JEI/recipe book.\n* Hopefully improve edit\'s behaviour with AltGr on some European keyboards.\n* Prevent files being usable after their mount was removed.\n* Fix the `id` program crashing on non-disk items (Wojbie).\n* Preserve registration order of turtle/pocket upgrades when displaying in JEI.\n\n# New features in CC: Tweaked 1.95.1\n\nSeveral bug fixes:\n* Command computers now drop items again.\n* Restore crafting of disks with dyes.\n* Fix CraftTweaker integrations for damageable items.\n* Catch reflection errors in the generic peripheral system, resolving crashes with Botania.\n\n# New features in CC: Tweaked 1.95.0\n\n* Optimise the paint program\'s initial render.\n* Several documentation improvements (Gibbo3771, MCJack123).\n* `fs.combine` now accepts multiple arguments.\n* Add a setting (`bios.strict_globals`) to error when accidentally declaring a global. (Lupus590).\n* Add an improved help viewer which allows scrolling up and down (MCJack123).\n* Add `cc.strings` module, with utilities for wrapping text (Lupus590).\n* The `clear` program now allows resetting the palette too (Luca0208).\n\nAnd several bug fixes:\n* Fix memory leak in generic peripherals.\n* Fix crash when a turtle is broken while being ticked.\n* `textutils.*tabulate` now accepts strings _or_ numbers.\n* We now deny _all_ local IPs, using the magic `$private` host. Previously the IPv6 loopback interface was not blocked.\n* Fix crash when rendering monitors if the block has not yet been synced. You will need to regenerate the config file to apply this change.\n* `read` now supports numpad enter (TheWireLord)\n* Correctly handle HTTP redirects to URLs containing escape characters.\n* Fix integer overflow in `os.epoch`.\n* Allow using pickaxes (and other items) for turtle upgrades which have mod-specific NBT.\n* Fix duplicate turtle/pocket upgrade recipes appearing in JEI.\n\n# New features in CC: Tweaked 1.94.0\n\n* Add getter for window visibility (devomaa)\n* Generic peripherals are no longer experimental, and on by default.\n* Use term.blit to draw boxes in paintutils (Lemmmy).\n\nAnd several bug fixes:\n* Fix turtles not getting advancements when turtles are on.\n* Draw in-hand pocket computers with the correct transparent flags enabled.\n* Several bug fixes to SNBT parsing.\n* Fix several programs using their original name instead of aliases in usage hints (Lupus590).\n\n# New features in CC: Tweaked 1.93.1\n\n* Various documentation improvements (Lemmmy).\n* Fix TBO monitor renderer on some older graphics cards (Lemmmy).\n\n# New features in CC: Tweaked 1.93.0\n\n* Update Swedish translations (Granddave).\n* Printers use item tags to check dyes.\n* HTTP rules may now be targeted for a specific port.\n* Don\'t propagate adjacent redstone signals through computers.\n\nAnd several bug fixes:\n* Fix NPEs when turtles interact with containers.\n\n# New features in CC: Tweaked 1.92.0\n\n* Bump Cobalt version:\n * Add support for the __pairs metamethod.\n * string.format now uses the __tostring metamethod.\n* Add date-specific MOTDs (MCJack123).\n\nAnd several bug fixes:\n* Correctly handle tabs within textutils.unserailizeJSON.\n* Fix sheep not dropping items when sheared by turtles.\n\n# New features in CC: Tweaked 1.91.1\n\n* Fix crash when turtles interact with an entity.\n\n# New features in CC: Tweaked 1.91.0\n\n* [Generic peripherals] Expose NBT hashes of items to inventory methods.\n* Bump Cobalt version:\n * Optimise handling of string concatenation.\n * Add string.{pack,unpack,packsize} (MCJack123)\n* Update to 1.16.2\n\nAnd several bug fixes:\n* Escape non-ASCII characters in JSON strings (neumond)\n* Make field names in fs.attributes more consistent (abby)\n* Fix textutils.formatTime correctly handle 12 AM (R93950X)\n* Fix turtles placing buckets multiple times.\n\n# New features in CC: Tweaked 1.90.3\n\n* Fix the selected slot indicator missing from the turtle GUI.\n* Ensure we load/save computer data from the world directory, rather than a global one.\n\n# New features in CC: Tweaked 1.90.2\n\n* Fix generic peripherals not being registered outside a dev environment.\n* Fix `turtle.attack()` failing.\n* Correctly set styles for the output of `/computercraft` commands.\n\n# New features in CC: Tweaked 1.90.1\n\n* Update to Forge 32.0.69\n\n# New features in CC: Tweaked 1.90.0\n\n* Add cc.image.nft module, for working with nft files. (JakobDev)\n* [experimental] Provide a generic peripheral for any tile entity without an existing one. We currently provide methods for working with inventories, fluid tanks and energy storage. This is disabled by default, and must be turned on in the config.\n* Add configuration to control the sizes of monitors and terminals.\n* Add configuration to control maximum render distance of monitors.\n* Allow getting "detailed" information about an item, using `turtle.getItemDetail(slot, true)`. This will contain the same information that the generic peripheral supplies.\n\nAnd several bug fixes:\n* Add back config for allowing interacting with command computers.\n* Fix write method missing from printers.\n* Fix dupe bug when killing an entity with a turtle.\n* Correctly supply port in the Host header (neumond).\n* Fix `turtle.craft` failing when missing an argument.\n* Fix deadlock when mistakenly "watching" an unloaded chunk.\n* Fix full path of files being leaked in some errors.\n\n# New features in CC: Tweaked 1.89.1\n\n* Fix crashes when rendering monitors of varying sizes.\n\n# New features in CC: Tweaked 1.89.0\n\n* Compress monitor data, reducing network traffic by a significant amount.\n* Allow limiting the bandwidth monitor updates use.\n* Several optimisations to monitor rendering (@Lignum).\n* Expose block and item tags to turtle.inspect and turtle.getItemDetail.\n\nAnd several bug fixes:\n* Fix settings.load failing on defined settings.\n* Fix name of the `ejectDisk` peripheral method.\n\n# New features in CC: Tweaked 1.88.1\n\n* Fix error on objects with too many methods.\n\n# New features in CC: Tweaked 1.88.0\n\n* Computers and turtles now preserve their ID when broken.\n* Add `peripheral.getName` - returns the name of a wrapped peripheral.\n* Reduce network overhead of monitors and terminals.\n* Add a TBO backend for monitors, with a significant performance boost.\n* The Lua REPL warns when declaring locals (lupus590, exerro)\n* Add config to allow using command computers in survival.\n* Add fs.isDriveRoot - checks if a path is the root of a drive.\n* `cc.pretty` can now display a function\'s arguments and where it was defined. The Lua REPL will show arguments by default.\n* Move the shell\'s `require`/`package` implementation to a separate `cc.require` module.\n* Move treasure programs into a separate external data pack.\n\nAnd several bug fixes:\n* Fix io.lines not accepting arguments.\n* Fix settings.load using an unknown global (MCJack123).\n* Prevent computers scanning peripherals twice.\n\n# New features in CC: Tweaked 1.87.1\n\n* Fix blocks not dropping items in survival.\n\n# New features in CC: Tweaked 1.87.0\n\n* Add documentation to many Lua functions. This is published online at https://tweaked.cc/.\n* Replace to pretty-printer in the Lua REPL. It now supports displaying functions and recursive tables. This printer is may be used within your own code through the `cc.pretty` module.\n* Add `fs.getCapacity`. A complement to `fs.getFreeSpace`, this returns the capacity of the supplied drive.\n* Add `fs.getAttributes`. This provides file size and type, as well as creation and modification time.\n* Update Cobalt version. This backports several features from Lua 5.2 and 5.3:\n - The `__len` metamethod may now be used by tables.\n - Add `\\z`, hexadecimal (`\\x00`) and unicode (`\\u0000`) string escape codes.\n - Add `utf8` lib.\n - Mirror Lua\'s behaviour of tail calls more closely. Native functions are no longer tail called, and tail calls are displayed in the stack trace.\n - `table.unpack` now uses `__len` and `__index` metamethods.\n - Parser errors now include the token where the error occurred.\n* Add `textutils.unserializeJSON`. This can be used to decode standard JSON and stringified-NBT.\n* The `settings` API now allows "defining" settings. This allows settings to specify a default value and description.\n* Enable the motd on non-pocket computers.\n* Allow using the menu with the mouse in edit and paint (JakobDev).\n* Add Danish and Korean translations (ChristianLW, mindy15963)\n* Fire `mouse_up` events in the monitor program.\n* Allow specifying a timeout to `websocket.receive`.\n* Increase the maximum limit for websocket messages.\n* Optimise capacity checking of computer/disk folders.\n\nAnd several bug fixes:\n* Fix turtle texture being incorrectly oriented (magiczocker10).\n* Prevent copying folders into themselves.\n* Normalise file paths within shell.setDir (JakobDev)\n* Fix turtles treating waterlogged blocks as water.\n* Register an entity renderer for the turtle\'s fake player.\n\n# New features in CC: Tweaked 1.86.2\n\n* Fix peripheral.getMethods returning an empty table.\n* Update to Minecraft 1.15.2. This is currently alpha-quality and so is missing missing features and may be unstable.\n\n# New features in CC: Tweaked 1.86.1\n\n* Add a help message to the Lua REPL\'s exit function.\n* Add more MOTD messages. (osmarks)\n* GPS requests are now made anonymously (osmarks)\n* Minor memory usage improvements to Cobalt VM.\n\nAnd several bug fixes:\n* Fix error when calling `write` with a number.\n* Add missing assertion to `io.write`.\n* Fix incorrect coordinates in `mouse_scroll` events.\n\n# New features in CC: Tweaked 1.86.0\n\n* Add PATCH and TRACE HTTP methods. (jaredallard)\n* Add more MOTD messages. (JakobDev)\n* Allow removing and adding turtle upgrades via CraftTweaker.\n\nAnd several bug fixes:\n* Fix crash when interacting with Wearable Backpacks.\n\n# New features in CC: Tweaked 1.85.2\n\n* Fix crashes when using the mouse with advanced computers.\n\n# New features in CC: Tweaked 1.85.1\n\n* Add basic mouse support to `read`\n\nAnd several bug fixes:\n* Fix turtles not having breaking particles.\n* Correct rendering of monitors when underwater.\n* Adjust the position from where turtle performs actions, correcting the behaviour of some interactions.\n* Fix several crashes when the turtle performs some action.\n\n# New features in CC: Tweaked 1.85.0\n\n* Window.reposition now allows changing the redirect buffer\n* Add cc.completion and cc.shell.completion modules\n* command.exec also returns the number of affected objects, when exposed by the game.\n\nAnd several bug fixes:\n* Change how turtle mining drops are handled, improving compatibility with some mods.\n* Fix several GUI desyncs after a turtle moves.\n* Fix os.day/os.time using the incorrect world time.\n* Prevent wired modems dropping incorrectly.\n* Fix mouse events not firing within the computer GUI.\n\n# New features in CC: Tweaked 1.84.1\n\n* Update to latest Forge\n\n# New features in CC: Tweaked 1.84.0\n\n* Improve validation in rename, copy and delete programs\n* Add window.getLine - the inverse of blit\n* turtle.refuel no longer consumes more fuel than needed\n* Add "cc.expect" module, for improved argument type checks\n* Mount the ROM from all mod jars, not just CC\'s\n\nAnd several bug fixes:\n* Ensure file error messages use the absolute correct path\n* Fix NPE when closing a file multiple times.\n* Do not load chunks when calling writeDescription.\n* Fix the signature of loadfile\n* Fix turtles harvesting blocks multiple times\n* Improve thread-safety of various peripherals\n* Prevent printed pages having massive/malformed titles\n\n# New features in CC: Tweaked 1.83.1\n\n* Add several new MOTD messages (JakobDev)\n\nAnd several bug fixes:\n* Fix type check in `rednet.lookup`\n* Error if turtle and pocket computer programs are run on the wrong system (JakobDev)\n* Do not discard varargs after a nil.\n\n# New features in CC: Tweaked 1.83.0\n\n* Add Chinese translation (XuyuEre)\n* Small performance optimisations for packet sending.\n* Provide an `arg` table to programs fun from the shell, similar to PUC Lua.\n* Add `os.date`, and handle passing datetime tables to `os.time`, making them largely compatible with PUC Lua.\n* `rm` and `mkdir` accept multiple arguments (hydraz, JakobDev).\n* Rework rendering of in-hand pocket computers.\n* Prevent rendering of a bounding box on a monitor\'s screen.\n* Refactor Lua-side type checking code into a single method. Also include the function name in error messages.\n\nAnd several bug fixes:\n* Fix incorrect computation of server-tick budget.\n* Fix list-based config options not reloading.\n* Ensure `require` is usable within the Lua REPL.\n\n# New features in CC: Tweaked 1.82.3\n\n* Make computers\' redstone input handling consistent with repeaters. Redstone inputs parallel to the computer will now be picked up.\n\nAnd several bug fixes:\n* Fix `turtle.compare*()` crashing the server.\n* Fix Cobalt leaking threads when coroutines blocked on Java methods are discarded.\n* Fix `rawset` allowing nan keys\n* Fix several out-of-bounds exceptions when handling malformed patterns.\n\n# New features in CC: Tweaked 1.82.2\n\n* Don\'t tie `turtle.refuel`/the `refuel` script\'s limits to item stack sizes\n\nAnd several bug fixes:\n* Fix changes to Project:Red inputs not being detected.\n* Convert non-modem peripherals to multiparts too, fixing crash with Proportional Destruction Particles\n* Remove a couple of over-eager error messages\n* Fix wired modems not correctly saving their attached peripherals\n\n# New features in CC: Tweaked 1.82.1\n\n* Make redstone updates identical to vanilla behaviour\n* Update German translation\n\n# New features in CC: Tweaked 1.82.0\n\n* Warn when `pastebin put` potentially triggers spam protection (Lemmmy)\n* Display HTTP errors on pastebin requests (Lemmmy)\n* Attach peripherals on the main thread, rather than deferring to the computer thread.\n* Computers may now be preemptively interrupted if they run for too long. This reduces the risk of malicious or badly written programs making other computers unusable.\n* Reduce overhead of running with a higher number of computer threads.\n* Set the initial multishell tab when starting the computer. This fixes the issue where you would not see any content until the first yield.\n* Allow running `pastebin get|url` with the URL instead (e.g. `pastebin run https://pastebin.com/LYAxmSby`).\n* Make `os.time`/`os.day` case insensitive.\n* Add translations for several languages: Brazilian Portuguese (zardyh), Swedish (nothjarnan), Italian (Ale32bit), French(absolument), German (Wilma456), Spanish (daelvn)\n* Improve JEI integration for turtle/pocket computer upgrades. You can now see recipes and usages of any upgrade or upgrade combination.\n* Associate turtle/pocket computer upgrades with the mod which registered them. For instance, a "Sensing Turtle" will now be labelled as belonging to Plethora.\n* Fire `key_up` and `mouse_up` events when closing the GUI.\n* Allow limiting the amount of server time computers can consume.\n* Add several new events for turtle refuelling and item inspection. Should allow for greater flexibility in add on mods in the future.\n* `rednet.send` returns if the message was sent. Restores behaviour present before CC 1.6 (Luca0208)\n* Add MCMP integration for wireless and ender modems.\n* Make turtle crafting more consistent with vanilla behaviour.\n* `commands.getBlockInfo(s)` now also includes NBT.\n* Turtles will no longer reset their label when clicked with an unnamed name tag.\n\nAnd several bug fixes:\n* Update Cobalt (fixes `load` not unwind the stack)\n* Fix `commands.collapseArgs` appending a trailing space.\n* Fix leaking file descriptors when closing (see [this JVM bug!](https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8220477))\n* Fix NPE on some invalid URLs\n* Fix pocket computer API working outside of the player inventory\n* Fix printing not updating the output display state.\n\n# New features in CC: Tweaked 1.81.1\n\n* Fix colour.*RGB using 8-bit values, rather than 0-1 floats.\n\n# New features in CC: Tweaked 1.81.0\n\n* Handle connection errors on websockets (Devilholk)\n* Make `require` a little more consistent with PUC Lua, passing the required name to modules and improving error messages.\n* Track how long each turtle action takes within the profiling tools\n* Bump Cobalt version\n * Coroutines are no longer backed by threads, reducing overhead of coroutines.\n * Maximum stack depth is much larger (2^16 rather than 2^8)\n * Stack is no longer unwound when an unhandled error occurs, meaning `debug.traceback` can be used on dead coroutines.\n* Reduce jar size by reducing how many extra files we bundle.\n* Add `term.nativePaletteColo(u)r` (Lignum)\n* Split `colours.rgb8` into `colours.packRGB` and `colours.unpackRGB` (Lignum)\n* Printers now only accept paper and ink, rather than any item\n* Allow scrolling through the multishell tab bar, when lots of programs are running. (Wilma456)\n\nAnd several bug fixes:\n* Fix modems not being advanced when they should be\n* Fix direction of some peripheral blocks not being set\n* Strip `\\r` from `.readLine` on binary handles.\n* Websockets handle pings correctly\n* Fix turtle peripherals becoming desynced on chunk unload.\n* `/computercraft` table are now truncated correctly.\n\n# New features in CC: Tweaked 1.80pr1.14\n\n* Allow seeking within ROM files.\n* Fix not being able to craft upgraded turtles or pocket computers when Astral Sorcery was installed.\n* Make several tile entities (modems, cables, and monitors) non-ticking, substantially reducing their overhead,\n\nAnd several bug fixes:\n* Fix cables not rendering the breaking steps\n* Try to prevent `/computercraft_copy` showing up in auto-complete.\n* Fix several memory leaks and other issues with ROM mounts.\n\n# New features in CC: Tweaked 1.80pr1.13\n\n* `websocket_message` and `.receive` now return whether a message was binary or not.\n* `websocket_close` events may contain a status code and reason the socket was closed.\n* Enable the `debug` library by default.\n* Clean up configuration files, moving various properties into sub-categories.\n* Rewrite the HTTP API to use Netty.\n* HTTP requests may now redirect from http to https if the server requests it.\n* Add config options to limit various parts of the HTTP API:\n * Restrict the number of active http requests and websockets.\n * Limit the size of HTTP requests and responses.\n * Introduce a configurable timeout\n* `.getResponseCode` also returns the status text associated with that status code.\n\nAnd several bug fixes:\n* Fix being unable to create resource mounts from individual files.\n* Sync computer state using TE data instead.\n* Fix `.read` always consuming a multiple of 8192 bytes for binary handles.\n\n# New features in CC: Tweaked 1.80pr1.12\n\n* Using longs inside `.seek` rather than 32 bit integers. This allows you to seek in very large files.\n* Move the `/computer` command into the main `/computercraft` command\n* Allow copying peripheral names from a wired modem\'s attach/detach chat message.\n\nAnd several bug fixes\n* Fix `InventoryUtil` ignoring the stack limit when extracting items\n* Fix computers not receiving redstone inputs sent through another block.\n* Fix JEI responding to key-presses when within a computer or turtle\'s inventory.\n\n# New features in CC: Tweaked 1.80pr1.11\n\n* Rename all tile entities to have the correct `computercraft:` prefix.\n* Fix files not being truncated when opened for a write.\n* `.read*` methods no longer fail on malformed unicode. Malformed input is replaced with a fake character.\n* Fix numerous issues with wireless modems being attached to wired ones.\n* Prevent deadlocks within the wireless modem code.\n* Create coroutines using a thread pool, rather than creating a new thread each time. Should make short-lived coroutines (such as iterators) much more performance friendly.\n* Create all CC threads under appropriately named thread groups.\n\n# New features in CC: Tweaked 1.80pr1.10\n\nThis is just a minor bugfix release to solve some issues with the filesystem rewrite\n* Fix computers not loading if resource packs are enabled\n* Fix stdin not being recognised as a usable input\n* Return an unsigned byte rather than a signed one for no-args `.read()`\n\n# New features in CC: Tweaked 1.80pr1.9\n\n* Add German translation (Vexatos)\n* Add `.getCursorBlink` to monitors and terminals.\n* Allow sending binary messages with websockets.\n* Extend `fs` and `io` APIs\n * `io` should now be largely compatible with PUC Lua\'s implementation (`:read("n")` is not currently supported).\n * Binary readable file handles now support `.readLine`\n * Binary file handles now support `.seek(whence: string[, position:number])`, taking the same arguments as PUC Lua\'s method.\n\nAnd several bug fixes:\n* Fix `repeat` program crashing when malformed rednet packets are received (gollark/osmarks)\n* Reduce risk of deadlock when calling peripheral methods.\n* Fix speakers being unable to play sounds.\n\n# New features in CC: Tweaked 1.80pr1.8\n\n* Bump Cobalt version\n * Default to using little endian in string.dump\n * Remove propagation of debug hooks to child coroutines\n * Allow passing functions to `debug.getlocal`, al-la Lua 5.2\n* Add Charset support for bundled cables\n* `/computercraft` commands are more generous in allowing computer selectors to fail.\n* Remove bytecode loading disabling from bios.lua.\n\nAnd several bug fixes:\n* Fix stack overflow when using `turtle.place` with a full inventory\n* Fix in-hand printout rendering causing visual glitches.\n\n# New features in CC: Tweaked 1.80pr1.7\n\n * Add `.getNameLocal` to wired modems: provides the name that computer is exposed as on the network. This is mostly useful for working with Plethora\'s transfer locations, though could have other purposes.\n * Change turtle block breaking to closer conform to how players break blocks.\n * Rewrite rendering of printed pages, allowing them to be held in hand, and placed in item frames.\n\nAnd several bug fixes:\n * Improve formatting of `/computercraft` when run by a non-player.\n * Fix pocket computer terminals not updating when being held.\n * Fix a couple of minor blemishes in the GUI textures.\n * Fix sign text not always being set when placed.\n * Cache turtle fakeplayer, hopefully proving some minor performance improvements.\n\n# New features in CC: Tweaked 1.80pr1.6\n\n* Allow network cables to work with compact machines.\n* A large number of improvements to the `/computercraft` command, including:\n * Ensure the tables are correctly aligned\n * Remove the output of the previous invocation of that command when posting to chat.\n * `/computercraft track` is now per-user, instead of global.\n * We now track additional fields, such as the number of peripheral calls, http requests, etc... You can specify these as an optional argument to `/computercraft track dump` to see them.\n* `wget` automatically determines the filename (Luca0208)\n* Allow using alternative HTTP request methods (`DELETE`, `PUT`, etc...)\n* Enable Gzip compression for websockets.\n* Fix monitors not rendering when optifine shaders are enabled. There are still issues (they are tinted orange during the night), but it is an improvement.\n\nAnd several bug fixes:\n* Fix `.isDiskPresent()` always returning true.\n* Fix peripherals showing up on wired networks when they shouldn\'t be.\n* Fix `turtle.place()` crashing the server in some esoteric conditions.\n* Remove upper bound on the number of characters than can be read with `.read(n: number)`.\n* Fix various typos in `keys.lua` (hugeblank)\n\n# New features in CC: Tweaked 1.80pr1.5\n\n* Several additional fixes to monitors, solving several crashes and graphical glitches.\n* Add recipes to upgrade computers, turtles and pocket computers.\n\n# New features in CC: Tweaked 1.80pr1.4\n\n* Verify the action can be completed in `copy`, `rename` and `mkdir` commands.\n* Add `/rom/modules` so the package path.\n* Add `read` to normal file handles - allowing reading a given number of characters.\n* Various minor bug fixes.\n* Ensure ComputerCraft peripherals are thread-safe. This fixes multiple Lua errors and crashes with modems monitors.\n* Add `/computercraft track` command, for monitoring how long computers execute for.\n* Add ore dictionary support for recipes.\n* Track which player owns a turtle. This allows turtles to play nicely with various claim/grief prevention systems.\n* Add config option to disable various turtle actions.\n* Add an API for extending wired networks.\n* Add full-block wired modems.\n* Several minor bug fixes.\n\n# New features in CC: Tweaked 1.80pr1.3\n\n* Add `/computercraft` command, providing various diagnostic tools.\n* Make `http.websocket` synchronous and add `http.websocketAsync`.\n* Restore binary compatibility for `ILuaAPI`.\n\n# New features in CC: Tweaked 1.80pr1.2\n\n* Fix `term.getTextScale()` not working across multiple monitors.\n* Fix computer state not being synced to client when turning on/off.\n* Provide an API for registering custom APIs.\n* Render turtles called "Dinnerbone" or "Grumm" upside*down.\n* Fix `getCollisionBoundingBox` not using all AABBs.\n* **Experimental:** Add map-like rendering for pocket computers.\n\n# New features in CC: Tweaked 1.80pr1.1\n\n* Large numbers of bug fixes, stabilisation and hardening.\n* Replace LuaJ with Cobalt.\n* Allow running multiple computers at the same time.\n* Add config option to enable Lua\'s debug API.\n* Add websocket support to HTTP library.\n* Add `/computer` command, allowing one to queue events on command computers.\n* Fix JEI\'s handling of various ComputerCraft items.\n* Make wired cables act more like multiparts.\n* Add turtle and pocket recipes to recipe book.\n* Flash pocket computer\'s light when playing a note.\n\n# New Features in ComputerCraft 1.80pr1:\n\n* Update to Minecraft 1.12.2\n* Large number of bug fixes and stabilisation.\n* Allow loading bios.lua files from resource packs.\n* Fix texture artefacts when rendering monitors.\n* Improve HTTP whitelist functionality and add an optional blacklist.\n* Add support for completing Lua\'s self calls (`foo:bar()`).\n* Add binary mode to HTTP.\n* Use file extensions for ROM files.\n* Automatically add `.lua` when editing files, and handle running them in the shell.\n* Add require to the shell environment.\n* Allow startup to be a directory.\n* Add speaker peripheral and corresponding turtle and pocket upgrades.\n* Add pocket computer upgrades.\n* Allow turtles and pocket computers to be dyed any colour.\n* Allow computer and monitors to configure their palette. Also allow normal computer/monitors to use any colour converting it to greyscale.\n* Add extensible pocket computer upgrade system, including ender modem upgrade.\n* Add config option to limit the number of open files on a computer.\n* Monitors glow in the dark.\n* http_failure event includes the HTTP handle if available.\n* HTTP responses include the response headers.\n\n# New Features in ComputerCraft 1.79:\n\n* Ported ComputerCraftEdu to Minecraft 1.8.9\n* Fixed a handful of bugs in ComputerCraft\n\n# New Features in ComputerCraft 1.77:\n\n* Ported to Minecraft 1.8.9\n* Added `settings` API\n* Added `set` and `wget` programs\n* Added settings to disable multishell, startup scripts, and tab completion on a per-computer basis. The default values for these settings can be customised in ComputerCraft.cfg\n* All Computer and Turtle items except Command Computers can now be mounted in Disk Drives\n\n# New Features in ComputerCraft 1.76:\n\n* Ported to Minecraft 1.8\n* Added Ender Modems for cross-dimensional communication\n* Fixed handling of 8-bit characters. All the characters in the ISO 8859-1 codepage can now be displayed\n* Added some extra graphical characters in the unused character positions, including a suite of characters for Teletext style drawing\n* Added support for the new commands in Minecraft 1.8 to the Command Computer\n* The return values of `turtle.inspect()` and `commands.getBlockInfo()` now include blockstate information\n* Added `commands.getBlockInfos()` function for Command Computers\n* Added new `peripherals` program\n* Replaced the `_CC_VERSION` and `_MC_VERSION` constants with a new `_HOST` constant\n* Shortened the length of time that "Ctrl+T", "Ctrl+S" and "Ctrl+R" must be held down for to terminate, shutdown and reboot the computer\n* `textutils.serialiseJSON()` now takes an optional parameter allowing it to produce JSON text with unquoted object keys. This is used by all autogenerated methods in the `commands` api except for "title" and "tellraw"\n* Fixed many bugs\n\n# New Features in ComputerCraft 1.75:\n\n* Fixed monitors sometimes rendering without part of their text.\n* Fixed a regression in the `bit` API.\n\n# New Features in ComputerCraft 1.74:\n\n* Added tab completion to `edit`, `lua` and the shell.\n* Added `textutils.complete()`, `fs.complete()`, `shell.complete()`, `shell.setCompletionFunction()` and `help.complete()`.\n* Added tab completion options to `read()`.\n* Added `key_up` and `mouse_up` events.\n* Non-advanced terminals now accept both grey colours.\n* Added `term.getTextColour()`, `term.getBackgroundColour()` and `term.blit()`.\n* Improved the performance of text rendering on Advanced Computers.\n* Added a "Run" button to the edit program on Advanced Computers.\n* Turtles can now push players and entities (configurable).\n* Turtles now respect server spawn protection (configurable).\n* Added a turtle permissions API for mod authors.\n* Implemented a subset of the Lua 5.2 API so programs can be written against it now, ahead of a future Lua version upgrade.\n* Added a config option to disable parts of the Lua 5.1 API which will be removed when a future Lua version upgrade happens.\n* Command Computers can no longer be broken by survival players.\n* Fixed the "pick block" key not working on ComputerCraft items in creative mode.\n* Fixed the `edit` program being hard to use on certain European keyboards.\n* Added `_CC_VERSION` and `_MC_VERSION` constants.\n\n# New Features in ComputerCraft 1.73:\n\n* The `exec` program, `commands.exec()` and all related Command Computer functions now return the console output of the command.\n* Fixed two multiplayer crash bugs.\n\n# New Features in ComputerCraft 1.7:\n\n* Added Command Computers\n* Added new API: `commands`\n* Added new programs: `commands`, `exec`\n* Added `textutils.serializeJSON()`\n* Added `ILuaContext.executeMainThreadTask()` for peripheral developers\n* Disk Drives and Printers can now be renamed with Anvils\n* Fixed various bugs, crashes and exploits\n* Fixed problems with HD texture packs\n* Documented the new features in the in-game help\n\n# New Features in ComputerCraft 1.65:\n\n* Fixed a multiplayer-only crash with `turtle.place()`\n* Fixed some problems with `http.post()`\n* Fixed `fs.getDrive()` returning incorrect results on remote peripherals\n\n# New Features in ComputerCraft 1.64:\n\n* Ported to Minecraft 1.7.10\n* New turtle functions: `turtle.inspect()`, `turtle.inspectUp()`, `turtle.inspectDown()`, `turtle.getItemDetail()`\n* Lots of bug and crash fixes, a huge stability improvement over previous versions\n\n# New Features in ComputerCraft 1.63:\n\n* Turtles can now be painted with dyes, and cleaned with water buckets\n* Added a new game: Redirection - ComputerCraft Edition\n* Turtle label nameplates now only show when the Turtle is moused-over\n* The HTTP API is now enabled by default, and can be configured with a whitelist of permitted domains\n* `http.get()` and `http.post()` now accept parameters to control the request headers\n* New fs function: `fs.getDir( path )`\n* Fixed some bugs\n\n# New Features in ComputerCraft 1.62:\n\n* Added IRC-style commands to the `chat` program\n* Fixed some bugs and crashes\n\n# New Features in ComputerCraft 1.6:\n\n* Added Pocket Computers\n* Added a multi-tasking system for Advanced Computers and Turtles\n* Turtles can now swap out their tools and peripherals at runtime\n* Turtles can now carry two tools or peripherals at once in any combination\n* Turtles and Computers can now be labelled using Name Tags and Anvils\n* Added a configurable fuel limit for Turtles\n* Added hostnames, protocols and long distance routing to the rednet API\n* Added a peer-to-peer chat program to demonstrate new rednet capabilities\n* Added a new game, only on Pocket Computers: "falling" by GopherATL\n* File system commands in the shell now accept wildcard arguments\n* The shell now accepts long arguments in quotes\n* Terminal redirection now no longer uses a stack-based system. Instead: `term.current()` gets the current terminal object and `term.redirect()` replaces it. `term.restore()` has been removed.\n* Added a new Windowing API for addressing sub-areas of the terminal\n* New programs: `fg`, `bg`, `multishell`, `chat`, `repeat`, `redstone`, `equip`, `unequip`\n* Improved programs: `copy`, `move`, `delete`, `rename`, `paint`, `shell`\n* Removed programs: `redset`, `redprobe`, `redpulse`\n* New APIs: `window`, `multishell`\n* New turtle functions: `turtle.equipLeft()` and `turtle.equipRight()`\n* New peripheral functions: `peripheral.find( [type] )`\n* New rednet functions: `rednet.host( protocol, hostname )`, `rednet.unhost( protocol )`, `rednet.locate( protocol, [hostname] )`\n* New fs function: `fs.find( wildcard )`\n* New shell functions: `shell.openTab()`, `shell.switchTab( [number] )`\n* New event `term_resize` fired when the size of a terminal changes\n* Improved rednet functions: `rednet.send()`, `rednet.broadcast()` and `rednet.receive()`now take optional protocol parameters\n* `turtle.craft(0)` and `turtle.refuel(0)` now return true if there is a valid recipe or fuel item, but do not craft of refuel anything\n* `turtle.suck( [limit] )` can now be used to limit the number of items picked up\n* Users of `turtle.dig()` and `turtle.attack()` can now specify which side of the turtle to look for a tool to use (by default, both will be considered)\n* `textutils.serialise( text )` now produces human-readable output\n* Refactored most of the codebase and fixed many old bugs and instabilities, turtles should never ever lose their content now\n* Fixed the `turtle_inventory` event firing when it shouldn\'t have\n* Added error messages to many more turtle functions after they return false\n* Documented all new programs and API changes in the `help` system\n\n# New Features in ComputerCraft 1.58:\n\n* Fixed a long standing bug where turtles could lose their identify if they travel too far away\n* Fixed use of deprecated code, ensuring mod compatibility with the latest versions of Minecraft Forge, and world compatibility with future versions of Minecraft\n\n# New Features in ComputerCraft 1.57:\n\n* Ported to Minecraft 1.6.4\n* Added two new Treasure Disks: Conway\'s Game of Life by vilsol and Protector by fredthead\n* Fixed a very nasty item duplication bug\n\n# New Features in ComputerCraft 1.56:\n\n* Added Treasure Disks: Floppy Disks in dungeons which contain interesting community made programs. Find them all!\n* All turtle functions now return additional error messages when they fail.\n* Resource Packs with Lua Programs can now be edited when extracted to a folder, for easier editing.\n\n# New Features in ComputerCraft 1.55:\n\n* Ported to Minecraft 1.6.2\n* Added Advanced Turtles\n* Added `turtle_inventory` event. Fires when any change is made to the inventory of a turtle\n* Added missing functions `io.close`, `io.flush`, `io.input`, `io.lines`, `io.output`\n* Tweaked the screen colours used by Advanced Computers, Monitors and Turtles\n* Added new features for Peripheral authors\n* Lua programs can now be included in Resource Packs\n\n# New Features in ComputerCraft 1.52:\n\n* Ported to Minecraft 1.5.1\n\n# New Features in ComputerCraft 1.51:\n\n* Ported to Minecraft 1.5\n* Added Wired Modems\n* Added Networking Cables\n* Made Wireless Modems more expensive to craft\n* New redstone API functions: `getAnalogInput()`, `setAnalogOutput()`, `getAnalogOutput()`\n* Peripherals can now be controlled remotely over wired networks. New peripheral API function: `getNames()`\n* New event: `monitor_resize` when the size of a monitor changes\n* Except for labelled computers and turtles, ComputerCraft blocks no longer drop items in creative mode\n* The pick block function works in creative mode now works for all ComputerCraft blocks\n* All blocks and items now use the IDs numbers assigned by FTB by default\n* Fixed turtles sometimes placing blocks with incorrect orientations\n* Fixed Wireless modems being able to send messages to themselves\n* Fixed `turtle.attack()` having a very short range\n* Various bugfixes\n\n# New Features in ComputerCraft 1.5:\n\n* Redesigned Wireless Modems; they can now send and receive on multiple channels, independent of the computer ID. To use these features, interface with modem peripherals directly. The rednet API still functions as before\n* Floppy Disks can now be dyed with multiple dyes, just like armour\n* The `excavate` program now retains fuel in it\'s inventory, so can run unattended\n* `turtle.place()` now tries all possible block orientations before failing\n* `turtle.refuel(0)` returns true if a fuel item is selected\n* `turtle.craft(0)` returns true if the inventory is a valid recipe\n* The in-game help system now has documentation for all the peripherals and their methods, including the new modem functionality\n* A romantic surprise\n\n# New Features in ComputerCraft 1.48:\n\n* Ported to Minecraft 1.4.6\n* Advanced Monitors now emit a `monitor_touch` event when right clicked\n* Advanced Monitors are now cheaper to craft\n* Turtles now get slightly less fuel from items\n* Computers can now interact with Command Blocks (if enabled in ComputerCraft.cfg)\n* New API function: `os.day()`\n* A christmas surprise\n\n# New Features in ComputerCraft 1.45:\n\n* Added Advanced Computers\n* Added Advanced Monitors\n* New program: paint by nitrogenfingers\n* New API: `paintutils`\n* New term functions: `term.setBackgroundColor`, `term.setTextColor`, `term.isColor`\n* New turtle function: `turtle.transferTo`\n\n# New Features in ComputerCraft 1.43:\n\n* Added Printed Pages\n* Added Printed Books\n* Fixed incompatibility with Forge 275 and above\n* Labelled Turtles now keep their fuel when broken\n\n# New Features in ComputerCraft 1.42:\n\n* Ported to Minecraft 1.3.2\n* Added Printers\n* Floppy Disks can be dyed different colours\n* Wireless Crafty Turtles can now be crafted\n* New textures\n* New forge config file\n* Bug fixes\n\n# New Features in ComputerCraft 1.4:\n\n* Ported to Forge Mod Loader. ComputerCraft can now be ran directly from the .zip without extraction\n* Added Farming Turtles\n* Added Felling Turtles\n* Added Digging Turtles\n* Added Melee Turtles\n* Added Crafty Turtles\n* Added 14 new Turtle Combinations accessible by combining the turtle upgrades above\n* Labelled computers and turtles can now be crafted into turtles or other turtle types without losing their ID, label and data\n* Added a "Turtle Upgrade API" for mod developers to create their own tools and peripherals for turtles\n* Turtles can now attack entities with `turtle.attack()`, and collect their dropped items\n* Turtles can now use `turtle.place()` with any item the player can, and can interact with entities\n* Turtles can now craft items with `turtle.craft()`\n* Turtles can now place items into inventories with `turtle.drop()`\n* Changed the behaviour of `turtle.place()` and `turtle.drop()` to only consider the currently selected slot\n* Turtles can now pick up items from the ground, or from inventories, with `turtle.suck()`\n* Turtles can now compare items in their inventories\n* Turtles can place signs with text on them with `turtle.place( [signText] )`\n* Turtles now optionally require fuel items to move, and can refuel themselves\n* The size of the the turtle inventory has been increased to 16\n* The size of the turtle screen has been increased\n* New turtle functions: `turtle.compareTo( [slotNum] )`, `turtle.craft()`, `turtle.attack()`, `turtle.attackUp()`, `turtle.attackDown()`, `turtle.dropUp()`, `turtle.dropDown()`, `turtle.getFuelLevel()`, `turtle.refuel()`\n* New disk function: disk.getID()\n* New turtle programs: `craft`, `refuel`\n* `excavate` program now much smarter: Will return items to a chest when full, attack mobs, and refuel itself automatically\n* New API: `keys`\n* Added optional Floppy Disk and Hard Drive space limits for computers and turtles\n* New `fs` function: `fs.getFreeSpace( path )`, also `fs.getDrive()` works again\n* The send and receive range of wireless modems now increases with altitude, allowing long range networking from high-altitude computers (great for GPS networks)\n* `http.request()` now supports https:// URLs\n* Right clicking a Disk Drive with a Floppy Disk or a Record when sneaking will insert the item into the Disk Drive automatically\n* The default size of the computer screen has been increased\n* Several stability and security fixes. LuaJ can now no longer leave dangling threads when a computer is unloaded, turtles can no longer be destroyed by tree leaves or walking off the edge of the loaded map. Computers no longer crash when used with RedPower frames.\n\n# New Features in ComputerCraft 1.31:\n\n* Ported to Minecraft 1.2.3\n* Added Monitors (thanks to Cloudy)\n* Updated LuaJ to a newer, less memory hungry version\n* `rednet_message` event now has a third parameter, "distance", to support position triangulation.\n* New programs: `gps`, `monitor`, `pastebin`.\n* Added a secret program. Use with large monitors!\n* New apis: `gps`, `vector`\n* New turtle functions: `turtle.compare()`, `turtle.compareUp()`, `turtle.compareDown()`, `turtle.drop( quantity )`\n* New `http` functions: `http.post()`.\n* New `term` functions: `term.redirect()`, `term.restore()`\n* New `textutils` functions: `textutils.urlEncode()`\n* New `rednet` functions: `rednet.isOpen()`\n* New config options: modem_range, modem_rangeDuringStorm\n* Bug fixes, program tweaks, and help updates\n\n# New Features in ComputerCraft 1.3:\n\n* Ported to Minecraft Forge\n* Added Turtles\n* Added Wireless Modems\n* Added Mining Turtles\n* Added Wireless Turtles\n* Added Wireless Mining Turtles\n* Computers and Disk Drives no longer get destroyed by water.\n* Computers and Turtles can now be labelled with the label program, and labelled devices keep their state when destroyed.\n* Computers/Turtles can connect to adjacent devices, and turn them on and off\n* User programs now give line numbers in their error messages\n* New APIs: `turtle`, `peripheral`\n* New programs for turtles: tunnel, excavate, go, turn, dance\n* New os functions: `os.getComputerLabel()`, `os.setComputerLabel()`\n* Added "filter" parameter to `os.pullEvent()`\n* New shell function: `shell.getCurrentProgram()`\n* New textutils functions: `textutils.serialize()`, `textutils.unserialize()`, `textutils.tabulate()`, `textutils.pagedTabulate()`, `textutils.slowWrite()`\n* New io file function: `file:lines()`\n* New fs function: `fs.getSize()`\n* Disk Drives can now play records from other mods\n* Bug fixes, program tweaks, and help updates\n\n# New Features in ComputerCraft 1.2:\n\n* Added Disk Drives and Floppy Disks\n* Added Ctrl+T shortcut to terminate the current program (hold)\n* Added Ctrl+S shortcut to shutdown the computer (hold)\n* Added Ctrl+R shortcut to reboot the computer (hold)\n* New Programs: `alias`, `apis`, `copy`, `delete`, `dj`, `drive`, `eject`, `id`, `label`, `list`, `move`, `reboot`, `redset`, `rename`, `time`, `worm`.\n* New APIs: `bit`, `colours`, `disk`, `help`, `rednet`, `parallel`, `textutils`.\n* New color functions: `colors.combine()`, `colors.subtract()`, `colors.test()`\n* New fs functions: `fs.getName()`, new modes for `fs.open()`\n* New os functions: `os.loadAPI()`, `os.unloadAPI()`, `os.clock()`, `os.time()`, `os.setAlarm()`, `os.reboot()`, `os.queueEvent()`\n* New redstone function: `redstone.getSides()`\n* New shell functions: `shell.setPath()`, `shell.programs()`, `shell.resolveProgram()`, `shell.setAlias()`\n* Lots of updates to the help pages\n* Bug fixes\n\n# New Features in ComputerCraft 1.1:\n\n* Added Multiplayer support throughout.\n* Added connectivity with RedPower bundled cables\n* Added HTTP api, enabled via the mod config, to allow computers to access the real world internet\n* Added command history to the shell.\n* Programs which spin in an infinite loop without yielding will no longer freeze minecraft\n* Help updates and bug fixes\n\n# New Features in ComputerCraft 1.0:\n\n* First Release!\n',"rom/help/chat.txt":'Surf the rednet superhighway with "chat", the networked chat program for CraftOS! Host chatrooms and invite your friends! Requires a Wired or Wireless Modem on each computer. When running chat, type "/help" to see a list of available commands.\n\nex:\n"chat host forgecraft" will create a chatroom with the name "forgecraft"\n"chat join forgecraft direwolf20" will connect to the chatroom with the name "forgecraft", using the nickname "direwolf20"\n',"rom/help/clear.txt":'clear clears the screen and/or resets the palette.\nex:\n"clear" clears the screen, but keeps the palette.\n"clear screen" does the same as "clear"\n"clear palette" resets the palette, but doesn\'t clear the screen\n"clear all" clears the screen and resets the palette\n',"rom/help/colors.txt":"Functions in the colors api\n(used for redstone.setBundledOutput):\ncolors.combine( color1, color2, color3, ... )\ncolors.subtract( colors, color1, color2, ... )\ncolors.test( colors, color )\ncolors.rgb8( r, g, b )\n\nColor constants in the colors api, in ascending bit order:\ncolors.white, colors.orange, colors.magenta, colors.lightBlue, colors.yellow, colors.lime, colors.pink, colors.gray, colors.lightGray, colors.cyan, colors.purple, colors.blue, colors.brown, colors.green, colors.red, colors.black.\n","rom/help/colours.txt":"Functions in the colours api\n(used for redstone.setBundledOutput):\ncolours.combine( colour1, colour2, colour3, ...)\ncolours.subtract( colours, colour1, colour2, ...)\ncolours.test( colours, colour )\ncolours.rgb8( r, g, b )\n\nColour constants in the colours api, in ascending bit order:\ncolours.white, colours.orange, colours.magenta, colours.lightBlue, colours.yellow, colours.lime, colours.pink, colours.grey, colours.lightGrey, colours.cyan, colours.purple, colours.blue, colours.brown, colours.green, colours.red, colours.black.\n","rom/help/commands.txt":'On a Command Computer, "commands" will list all the commands available for use. Use "exec" to execute them.\nType "help commandsapi" for help using commands in lua programs.\n',"rom/help/commandsapi.txt":'Functions in the commands API:\ncommands.exec( command )\ncommands.execAsync( command )\ncommands.list()\ncommands.getBlockPosition()\ncommands.getBlockInfo( x, y, z )\ncommands.getBlockInfos( minx, miny, minz, maxx, maxy, maxz )\n\nThe commands API can also be used to invoke commands directly, like so:\ncommands.say( "Hello World" )\ncommands.give( "dan200", "minecraft:diamond", 64 )\nThis works with any command. Use "commands.async" instead of "commands" to execute asynchronously.\n\nThe commands API is only available on Command Computers.\nVisit https://minecraft.wiki/w/Commands for documentation on all commands.\n',"rom/help/copy.txt":'cp copies a file or directory from one location to another.\n\nex:\n"cp rom myrom" copies "rom" to "myrom".\n"cp rom mystuff/rom" copies "rom" to "mystuff/rom".\n"cp disk/* disk2" copies the contents of one disk to another\n',"rom/help/coroutine.txt":"coroutine is a standard Lua5.1 API.\nRefer to http://www.lua.org/manual/5.1/ for more information.\n","rom/help/craft.txt":'craft is a program for Crafty Turtles. Craft will craft a stack of items using the current inventory.\n\nex:\n"craft all" will craft as many items as possible\n"craft 5" will craft at most 5 times\n',"rom/help/credits.md":'ComputerCraft was created by Daniel "dan200" Ratcliffe, with additional code by Aaron "Cloudy" Mills.\nThanks to nitrogenfingers, GopherATL and RamiLego for program contributions.\nThanks to Mojang, the Forge team, and the MCP team.\nUses LuaJ from http://luaj.sourceforge.net/\n\nThe ComputerCraft 1.76 update was sponsored by MinecraftU and Deep Space.\nVisit http://www.minecraftu.org and http://www.deepspace.me/space-cadets to find out more.\n\nJoin the ComputerCraft community online at https://computercraft.cc\nFollow @DanTwoHundred on Twitter!\n\nTo help contribute to CC: Tweaked, browse the source code at https://github.com/cc-tweaked/cc-tweaked.\n\n# GitHub\nNumerous people have contributed to CC: Tweaked over the years:\n\n${gitContributors}\n\nThank you to everyone who has contributed\n\n# Software Licenses\nCC: Tweaked would not be possible without the work of other open source libraries. Their licenses are included below:\n\n## Apache 2.0\nCC: Tweaked contains code from the following Apache 2.0 licensed libraries:\n\n - Netty (https://github.com/netty/netty)\n\nApache License\nVersion 2.0, January 2004\nhttp://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.\n\n"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.\n\n"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.\n\n"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.\n\n"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.\n\n"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.\n\n"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).\n\n"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.\n\n"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."\n\n"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:\n\n (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and\n\n (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.\n\n You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\n## GNU Lesser General Public License 3.0\nCC: Tweaked contains code from the following LGPL 3.0 licensed libraries:\n\n - NightConfig (https://github.com/TheElectronWill/night-config/tree/master)\n\nGNU LESSER GENERAL PUBLIC LICENSE\nVersion 3, 29 June 2007\n\nCopyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n\nEveryone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.\n\nThis version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.\n\n0. Additional Definitions.\n\nAs used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License.\n\n"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.\n\nAn "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.\n\nA "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version".\n\nThe "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.\n\nThe "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.\n\n1. Exception to Section 3 of the GNU GPL.\nYou may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.\n\n2. Conveying Modified Versions.\nIf you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:\n\n a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or\n\n b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.\n\n3. Object Code Incorporating Material from Library Header Files.\nThe object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:\n\n a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.\n\n b) Accompany the object code with a copy of the GNU GPL and this license document.\n\n4. Combined Works.\nYou may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:\n\n a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.\n\n b) Accompany the Combined Work with a copy of the GNU GPL and this license document.\n\n c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.\n\n d) Do one of the following:\n\n 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.\n\n 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user\'s computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.\n\n e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)\n\n5. Combined Libraries.\nYou may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:\n\n a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.\n\n b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.\n\n6. Revised Versions of the GNU Lesser General Public License.\nThe Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.\n\nEach version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.\n\nIf the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall\napply, that proxy\'s public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.\n\nGNU GENERAL PUBLIC LICENSE\nVersion 3, 29 June 2007\n\nCopyright \xa9 2007 Free Software Foundation, Inc. <http://fsf.org/>\n\nEveryone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.\n\nPreamble\n\nThe GNU General Public License is a free, copyleft license for software and other kinds of works.\n\nThe licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.\n\nWhen we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.\n\nTo protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.\n\nFor example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.\n\nDevelopers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.\n\nFor the developers\' and authors\' protection, the GPL clearly explains that there is no warranty for this free software. For both users\' and authors\' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.\n\nSome devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users\' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.\n\nFinally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.\n\nThe precise terms and conditions for copying, distribution and modification follow.\n\nTERMS AND CONDITIONS\n\n0. Definitions.\n\n"This License" refers to version 3 of the GNU General Public License.\n\n"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.\n\n"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.\n\nTo "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.\n\nA "covered work" means either the unmodified Program or a work based on the Program.\n\nTo "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.\n\nTo "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.\n\nAn interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.\n\n1. Source Code.\nThe "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.\n\nA "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.\n\nThe "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.\n\nThe "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work\'s System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.\n\nThe Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.\n\nThe Corresponding Source for a work in source code form is that same work.\n\n2. Basic Permissions.\nAll rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.\n\nYou may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.\n\nConveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.\n\n3. Protecting Users\' Legal Rights From Anti-Circumvention Law.\nNo covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.\n\nWhen you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work\'s users, your or third parties\' legal rights to forbid circumvention of technological measures.\n\n4. Conveying Verbatim Copies.\nYou may convey verbatim copies of the Program\'s source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.\n\nYou may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.\n\n5. Conveying Modified Source Versions.\nYou may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:\n\n a) The work must carry prominent notices stating that you modified it, and giving a relevant date.\n\n b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".\n\n c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.\n\n d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.\n\nA compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation\'s users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.\n\n6. Conveying Non-Source Forms.\nYou may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:\n\n a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.\n\n b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.\n\n c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.\n\n d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.\n\n e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.\n\nA separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.\n\nA "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.\n\n"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.\n\nIf you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).\n\nThe requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.\n\nCorresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.\n\n7. Additional Terms.\n"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.\n\nWhen you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.\n\nNotwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:\n\n a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or\n\n b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or\n\n c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or\n\n d) Limiting the use for publicity purposes of names of licensors or authors of the material; or\n\n e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or\n\n f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.\n\nAll other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.\n\nIf you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.\n\nAdditional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.\n\n8. Termination.\nYou may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).\n\nHowever, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.\n\nMoreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.\n\nTermination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.\n\n9. Acceptance Not Required for Having Copies.\nYou are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.\n\n10. Automatic Licensing of Downstream Recipients.\nEach time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.\n\nAn "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party\'s predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.\n\nYou may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.\n\n11. Patents.\nA "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor\'s "contributor version".\n\nA contributor\'s "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.\n\nEach contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor\'s essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.\n\nIn the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.\n\nIf you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient\'s use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.\n\nIf, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.\n\nA patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.\n\nNothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.\n\n12. No Surrender of Others\' Freedom.\nIf conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.\n\n13. Use with the GNU Affero General Public License.\nNotwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.\n\n14. Revised Versions of this License.\nThe Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.\n\nEach version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.\n\nIf the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy\'s public statement of acceptance of a version permanently authorizes you to choose that version for the Program.\n\nLater license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.\n\n15. Disclaimer of Warranty.\nTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n16. Limitation of Liability.\nIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n\n17. Interpretation of Sections 15 and 16.\nIf the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.\n\nEND OF TERMS AND CONDITIONS\n\n## Cobalt (https://github.com/SquidDev/Cobalt)\nThe MIT License (MIT)\n\nOriginal Source: Copyright (c) 2009-2011 Luaj.org. All rights reserved.\nModifications: Copyright (c) 2015-2020 SquidDev\n\nPermission 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:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE 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.\n\n## double-conversion (https://github.com/google/double-conversion/)\nCopyright 2006-2012 the V8 project authors. All rights reserved.\nJava Port Copyright 2021 sir-maniac. All Rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n* Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n',"rom/help/dance.txt":"dance is a program for Turtles. Turtles love to get funky.\n","rom/help/delete.txt":'rm deletes a file or a directory and its contents.\n\nex:\n"rm foo" will delete the file foo.\n"rm disk/*" will delete the contents of a disk.\n',"rom/help/disk.txt":'Functions in the disk API. These functions are for interacting with disk drives:\ndisk.isPresent( drive )\ndisk.setLabel( drive, label )\ndisk.getLabel( drive )\ndisk.hasData( drive )\ndisk.getMountPath( drive )\ndisk.hasAudio( drive )\ndisk.getAudioTitle( drive )\ndisk.playAudio( drive )\ndisk.stopAudio( )\ndisk.eject( drive )\ndisk.getID( drive )\n\nEvents fired by the disk API:\n"disk" when a disk or other item is inserted into a disk drive. Argument is the name of the drive\n"disk_eject" when a disk is removed from a disk drive. Argument is the name of the drive\nType "help events" to learn about the event system.\n',"rom/help/dj.txt":'dj plays Music Discs from disk drives attached to the computer.\n\nex:\n"dj" or "dj play" plays a random disc.\n"dj play left" plays the disc in the drive on the left of the computer.\n"dj stop" stops the current disc.\n',"rom/help/drive.txt":'drive tells you which disk drive the current or specified directory is located in.\n\nex:\n"drive" tell you the disk drive of the current directory.\n"drive foo" tells you the disk drive of the subdirectory "foo"\n',"rom/help/drives.txt":'The Disk Drive is a peripheral device available for CraftOS. Type "help peripheral" to learn about using the Peripheral API to connect with peripherals. When a Disk Drive is connected, peripheral.getType() will return "drive".\n\nMethods exposed by the Disk Drive:\nisDiskPresent()\ngetDiskLabel()\nsetDiskLabel( label )\nhasData()\ngetMountPath()\nhasAudio()\ngetAudioTitle()\nplayAudio()\nstopAudio()\nejectDisk()\ngetDiskID()\n\nEvents fired by the Disk Drive:\n"disk" when a disk or other item is inserted into the drive. Argument is the name of the drive.\n"disk_eject" when a disk is removed from a drive. Argument is the name of the drive.\nType "help events" to learn about the event system.\n',"rom/help/earth.txt":"Mostly harmless.\n","rom/help/edit.txt":'edit is a text editor for creating or modifying programs or text files. After creating a program with edit, type its filename in the shell to run it. You can open any of the builtin programs with edit to learn how to program.\n\nex:\n"edit hello" opens a file called "hello" for editing.\n',"rom/help/eject.txt":'eject ejects the contents of an attached disk drive.\n\nex:\n"eject left" ejects the contents of the disk drive to the left of the computer.\n',"rom/help/equip.txt":'equip is a program for Turtles and Pocket Computer. equip will equip an item from the Turtle\'s inventory for use as a tool of peripheral. On a Pocket Computer you don\'t need to write a side.\n\nex:\n"equip 5 left" will equip the item from slot 5 of the turtle onto the left side of the turtle\n"equip" on a Pocket Computer will equip the first item from your inventory.\n',"rom/help/events.txt":'The function os.pullEvent() will yield the program until a system event occurs. The first return value is the event name, followed by any arguments.\n\nSome events which can occur are:\n"char" when text is typed on the keyboard. Argument is the character typed.\n"key" when a key is pressed on the keyboard. Arguments are the keycode and whether the key is a repeat. Compare the keycode to the values in keys API to see which key was pressed.\n"key_up" when a key is released on the keyboard. Argument is the numerical keycode. Compare to the values in keys API to see which key was released.\n"paste" when text is pasted from the users keyboard. Argument is the line of text pasted.\n\nEvents only on advanced computers:\n"mouse_click" when a user clicks the mouse. Arguments are button, xPos, yPos.\n"mouse_drag" when a user moves the mouse when held. Arguments are button, xPos, yPos.\n"mouse_up" when a user releases the mouse button. Arguments are button, xPos, yPos.\n"mouse_scroll" when a user uses the scrollwheel on the mouse. Arguments are direction, xPos, yPos.\n\nOther APIs and peripherals will emit their own events. See their respective help pages for details.\n',"rom/help/excavate.txt":'excavate is a program for Mining Turtles. When excavate is run, the turtle will mine a rectangular shaft into the ground, collecting blocks as it goes, and return to the surface once bedrock is hit.\n\nex:\n"excavate 3" will mine a 3x3 shaft.\n',"rom/help/exec.txt":'On a Command Computer, "exec" will execute a command as if entered on a command block. Use "commands" to list all the available commands.\n\nex:\n"exec say Hello World"\n"exec setblock ~0 ~1 ~0 minecraft:dirt"\n\nType "help commandsapi" for help using commands in lua programs.\n',"rom/help/exit.txt":"exit will exit the current shell.\n","rom/help/falling.txt":'"From Russia with Fun" comes a fun, new, suspiciously-familiar falling block game for CraftOS. Only on Pocket Computers!\n',"rom/help/fg.txt":'fg is a program for Advanced Computers which opens a new tab in the foreground.\n\nex:\n"fg" will open a foreground tab running the shell\n"fg worm" will open a foreground tab running the "worm" program\n',"rom/help/fs.txt":'Functions in the Filesystem API:\nfs.list( path )\nfs.find( wildcard )\nfs.exists( path )\nfs.isDir( path )\nfs.isReadOnly( path )\nfs.getDir( path )\nfs.getName( path )\nfs.getSize( path )\nfs.getDrive( path )\nfs.getFreeSpace( path )\nfs.makeDir( path )\nfs.move( path, path )\nfs.copy( path, path )\nfs.delete( path )\nfs.combine( path, localpath )\nfs.open( path, mode )\nfs.complete( path, location )\nAvailable fs.open() modes are "r", "w", "a", "rb", "wb" and "ab".\n\nFunctions on files opened with mode "r":\nreadLine()\nreadAll()\nclose()\nread( number )\n\nFunctions on files opened with mode "w" or "a":\nwrite( string )\nwriteLine( string )\nflush()\nclose()\n\nFunctions on files opened with mode "rb":\nread()\nclose()\n\nFunctions on files opened with mode "wb" or "ab":\nwrite( byte )\nflush()\nclose()\n',"rom/help/go.txt":'go is a program for Turtles, used to control the turtle without programming. It accepts one or more commands as a direction followed by a distance.\n\nex:\n"go forward" moves the turtle 1 space forward.\n"go forward 3" moves the turtle 3 spaces forward.\n"go forward 3 up left 2" moves the turtle 3 spaces forward, 1 spaces up, then left 180 degrees.\n',"rom/help/gps.txt":'gps can be used to host a GPS server, or to determine a position using trilateration.\nType "help gpsapi" for help using GPS functions in lua programs.\n\nex:\n"gps locate" will connect to nearby GPS servers, and try to determine the position of the computer or turtle.\n"gps host" will try to determine the position, and host a GPS server if successful.\n"gps host 10 20 30" will host a GPS server, using the manually entered position 10,20,30.\n\nTake care when manually entering host positions. If the positions entered into multiple GPS hosts\nare not consistent, the results of locate calls will be incorrect.\n',"rom/help/gpsapi.txt":"Functions in the GPS API:\ngps.locate( timeout )\n\nThe locate function will send a signal to nearby gps servers, and wait for responses before the timeout. If it receives enough responses to determine this computers position then x, y and z co-ordinates will be returned, otherwise it will return nil. If GPS hosts do not have their positions configured correctly, results will be inaccurate.\n","rom/help/hello.txt":'hello prints the text "Hello World!" to the screen.\n',"rom/help/help.txt":'help is the help tool you\'re currently using.\nType "help index" to see all help topics.\nType "help" to see the help intro.\nType "help helpapi" for information on the help Lua API.\n',"rom/help/helpapi.txt":"Functions in the help API:\nhelp.setPath( path )\nhelp.lookup( topic )\nhelp.topics()\nhelp.completeTopic( topic )\n","rom/help/http.txt":'Functions in the HTTP API:\nhttp.checkURL( url )\nhttp.checkURLAsync( url )\nhttp.request( url, [postData], [headers] )\nhttp.get( url, [headers] )\nhttp.post( url, postData, [headers] )\n\nThe HTTP API may be disabled in ComputerCraft.cfg\nA period of time after a http.request() call is made, a "http_success" or "http_failure" event will be raised. Arguments are the url and a file handle if successful. Arguments are nil, an error message, and (optionally) a file handle if the request failed. http.get() and http.post() block until this event fires instead.\n',"rom/help/id.txt":'id prints the unique identifier of this computer, or a Disk in an attached Disk Drive.\n\nex:\n"id" will print this Computers ID and label\n"id left" will print the ID and label of the disk in the Disk Drive on the left\n',"rom/help/intro.txt":'Welcome to CraftOS!\nType "programs" to see the programs you can run.\nType "help <program>" to see help for a specific program.\nType "help programming" to learn about programming.\nType "help whatsnew" to find out about new features.\nType "help credits" to learn who made all this.\nType "help index" to see all help topics.\n',"rom/help/io.txt":"io is a standard Lua5.1 API, reimplemented for CraftOS. Not all the features are available.\nRefer to http://www.lua.org/manual/5.1/ for more information.\n","rom/help/keys.txt":'The keys API contains constants for all the key codes that can be returned by the "key" event:\n\nExample usage:\nlocal sEvent, nKey = os.pullEvent()\nif sEvent == "key" and nKey == keys.enter then\n -- Do something\nend\n\nSee https://www.minecraft.wiki/w/Key_codes, or the source code, for a complete reference.\n',"rom/help/label.txt":'label gets or sets the label of the Computer, or of Floppy Disks in attached disk drives.\n\nex:\n"label get" prints the label of the computer.\n"label get left" prints the label of the disk in the left drive.\n"label set "My Computer"" set the label of the computer to "My Computer".\n"label set left "My Programs"" - sets the label of the disk in the left drive to "My Programs".\n"label clear" clears the label of the computer.\n"label clear left" clears the label of the disk in the left drive.\n',"rom/help/list.txt":'ls will list all the directories and files in the current location. Use "type" to find out if an item is a file or a directory.\n',"rom/help/lua.txt":"lua is an interactive prompt for the lua programming language. It's a useful tool for learning the language.\n","rom/help/math.txt":"math is a standard Lua5.1 API.\nRefer to http://www.lua.org/manual/5.1/ for more information.\n","rom/help/mkdir.txt":'mkdir creates a directory in the current location.\n\nex:\n"mkdir foo" creates a directory named "foo".\n"mkdir ../foo" creates a directory named "foo" in the directory above the current directory.\n',"rom/help/modems.txt":'Wired and Wireless Modems are peripheral devices available for CraftOS. Type "help peripheral" to learn about using the Peripheral API to connect with peripherals. When a Modem is connected, peripheral.getType() will return "modem".\n\nMethods exposed by Modems:\nopen( channel )\nisOpen( channel )\nclose( channel )\ncloseAll()\ntransmit( channel, replyChannel, message )\nisWireless()\n\nEvents fired by Modems:\n"modem_message" when a message is received on an open channel. Arguments are name, channel, replyChannel, message, distance\n',"rom/help/monitor.txt":'monitor will connect to an attached Monitor peripheral, and run a program on its display.\nType "help monitors" for help using monitors as peripherals in lua programs.\n\nex:\n"monitor left hello" will run the "hello" program on the monitor to the left of the computer.\n"monitor top edit foo" will run the edit program on the top monitor, editing the file "foo".\n',"rom/help/monitors.txt":'The Monitor is a peripheral device available for CraftOS. Type "help peripheral" to learn about using the Peripheral API to connect with peripherals. When a Monitor is connected, peripheral.getType() will return "monitor". A wrapped monitor can be used with term.redirect() to send all terminal output to the monitor.\n\nMethods exposed by the Monitor:\nwrite( text )\nblit( text, textColor, backgroundColor )\nclear()\nclearLine()\ngetCursorPos()\nsetCursorPos( x, y )\nsetCursorBlink( blink )\nisColor()\nsetTextColor( color )\nsetBackgroundColor( color )\ngetTextColor()\ngetBackgroundColor()\ngetSize()\nscroll( n )\nsetPaletteColor( color, r, g, b )\ngetPaletteColor( color )\n\nEvents fired by the Monitor:\n"monitor_touch" when an Advanced Monitor is touched by the player. Arguments are name, x, y\n"monitor_resize" when the size of a Monitor changes. Argument is the name of the monitor.\n',"rom/help/move.txt":'mv moves a file or directory from one location to another.\n\nex:\n"mv foo bar" renames the file "foo" to "bar".\n"mv foo bar/foo" moves the file "foo" to a folder called "bar".\n"mv disk/* disk2" moves the contents of one disk to another\n',"rom/help/multishell.txt":'multishell is the toplevel program on Advanced Computers which manages background tabs.\nType "help shellapi" for information about the shell lua api.\n',"rom/help/os.txt":'Functions in the os (Operating System) API:\nos.version()\nos.getComputerID()\nos.getComputerLabel()\nos.setComputerLabel()\nos.run( environment, programpath, arguments )\nos.loadAPI( path )\nos.unloadAPI( name )\nos.pullEvent( [filter] )\nos.queueEvent( event, arguments )\nos.clock()\nos.startTimer( timeout )\nos.cancelTimer( token )\nos.sleep( timeout )\nos.time( [source] )\nos.day( [source] )\nos.epoch( [source] )\nos.setAlarm( time )\nos.cancelAlarm( token )\nos.shutdown()\nos.reboot()\n\nEvents emitted by the os API:\n"timer" when a timeout started by os.startTimer() completes. Argument is the token returned by os.startTimer().\n"alarm" when a time passed to os.setAlarm() is reached. Argument is the token returned by os.setAlarm().\nType "help events" to learn about the event system.\n',"rom/help/paint.txt":'paint is a program for creating images on Advanced Computers. Select colors from the color pallette on the right, and click on the canvas to draw. Press Ctrl to access the menu and save your pictures.\n\nex:\n"edit mario" opens an image called "mario" for editing.\n',"rom/help/paintutils.txt":"Functions in the Paint Utilities API:\npaintutils.drawPixel( x, y, colour )\npaintutils.drawLine( startX, startY, endX, endY, colour )\npaintutils.drawBox( startX, startY, endX, endY, colour )\npaintutils.drawFilledBox( startX, startY, endX, endY, colour )\npaintutils.loadImage( path )\npaintutils.drawImage( image, x, y )\n","rom/help/parallel.txt":"Functions in the Parallel API:\nparallel.waitForAny( function1, function2, ... )\nparallel.waitForAll( function1, function2, ... )\nThese methods provide an easy way to run multiple lua functions simultaneously.\n","rom/help/pastebin.txt":'pastebin is a program for uploading files to and downloading files from pastebin.com. This is useful for sharing programs with other players.\nThe HTTP API must be enabled in ComputerCraft.cfg to use this program.\n\nex:\n"pastebin put foo" will upload the file "foo" to pastebin.com, and print the URL.\n"pastebin get xq5gc7LB foo" will download the file from the URL http://pastebin.com/xq5gc7LB, and save it as "foo".\n"pastebin run CxaWmPrX" will download the file from the URL http://pastebin.com/CxaWmPrX, and immediately run it.\n',"rom/help/peripheral.txt":'The peripheral API is for interacting with external peripheral devices. Type "help peripherals" to learn about the peripherals available.\n\nFunctions in the peripheral API:\nperipheral.getNames()\nperipheral.isPresent( name )\nperipheral.getName( peripheral )\nperipheral.getType( name )\nperipheral.getMethods( name )\nperipheral.call( name, methodName, param1, param2, etc )\nperipheral.wrap( name )\nperipheral.find( type, [fnFilter] )\n\nEvents fired by the peripheral API:\n"peripheral" when a new peripheral is attached. Argument is the name.\n"peripheral_detach" when a peripheral is removed. Argument is the name.\nType "help events" to learn about the event system.\n',"rom/help/peripherals.txt":'The "peripherals" program will list all of the peripheral devices accessible from this computer.\nPeripherals are external devices which CraftOS Computers and Turtles can interact with using the peripheral API.\nType "help peripheral" to learn about using the peripheral API.\nType "help drives" to learn about using Disk Drives.\nType "help modems" to learn about using Modems.\nType "help monitors" to learn about using Monitors.\nType "help printers" to learn about using Printers.\n',"rom/help/pocket.txt":"pocket is an API available on pocket computers, which allows modifying its upgrades.\nFunctions in the pocket API:\npocket.equipBack()\npocket.unequipBack()\n\nWhen equipping upgrades, it will search your inventory for a suitable upgrade, starting in the selected slot. If one cannot be found then it will check your offhand.\n","rom/help/printers.txt":'The Printer is a peripheral device available for CraftOS. Type "help peripheral" to learn about using the Peripheral API to connect with peripherals. When a Printer is connected, peripheral.getType() will return "printer".\n\nMethods exposed by the Printer:\ngetInkLevel()\ngetPaperLevel()\nnewPage()\nsetPageTitle( title )\ngetPageSize()\nsetCursorPos( x, y )\ngetCursorPos()\nwrite( text )\nendPage()\n',"rom/help/programming.txt":'To learn the lua programming language, visit http://lua-users.org/wiki/TutorialDirectory.\n\nTo experiment with lua in CraftOS, run the "lua" program and start typing code.\nTo create programs, use "edit" to create files, then type their names in the shell to run them. If you name a program "startup" and place it in the root or on a disk drive, it will run automatically when the computer starts.\n\nTo terminate a program stuck in a loop, hold Ctrl+T for 1 second.\nTo quickly shutdown a computer, hold Ctrl+S for 1 second.\nTo quickly reboot a computer, hold Ctrl+R for 1 second.\n\nTo learn about the programming APIs available, type "apis" or "help apis".\nIf you get stuck, visit the forums at http://www.computercraft.info/ for advice and tutorials.\n',"rom/help/programs.txt":"programs lists all the programs on the rom of the computer.\n","rom/help/reboot.txt":"reboot will turn the computer off and on again.\nYou can also hold Ctrl+R at any time to quickly reboot.\n","rom/help/redirection.txt":"Redirection ComputerCraft Edition is the CraftOS version of a fun new puzzle game by Dan200, the author of ComputerCraft.\nPlay it on any Advanced Computer, then visit http://www.redirectiongame.com to play the full game!\n","rom/help/rednet.txt":'The rednet API provides a simple computer networking model using modems.\n\nFunctions in the rednet API:\nrednet.open( side )\nrednet.close( [side] )\nrednet.isOpen( [side] )\nrednet.send( receiverID, message, [protocol] ) -- Send to a specific computer\nrednet.broadcast( message, [protocol] ) -- Send to all computers\nrednet.receive( [protocol], [timeout] ) -- Returns: senderID, message, protocol\nrednet.host( protocol, hostname )\nrednet.unhost( protocol )\nrednet.lookup( protocol, [hostname] ) -- Returns: ID\n\nEvents fired by the rednet API:\n"rednet_message" when a message is received. Arguments are senderID, message, protocol\nType "help events" to learn about the event system.\n\nRednet is not the only way to use modems for networking. Interfacing with the modem directly using the peripheral API and listening for the "modem_message" event allows for lower level control, at the expense of powerful high level networking features.\n',"rom/help/redstone.txt":'The redstone program can be used to get, set or pulse redstone inputs and outputs from the computer.\n\nex:\n"redstone probe" will list all the redstone inputs to the computer\n"redstone set left true" turns on the left redstone output.\n"redstone set right blue false" turns off the blue wire in the bundled cable on the right redstone output.\n"redstone pulse front 10 1" emits 10 one second redstone pulses on the front redstone output.\n\nType "help redstoneapi" or "help rs" for information on the redstone Lua API.\n',"rom/help/redstoneapi.txt":'Functions in the Redstone API:\nredstone.getSides( )\nredstone.getInput( side )\nredstone.setOutput( side, boolean )\nredstone.getOutput( side )\nredstone.getAnalogInput( side )\nredstone.setAnalogOutput( side, number )\nredstone.getAnalogOutput( side )\n\nFunctions in the Redstone API for working with bundled cables:\nredstone.getBundledInput( side )\nredstone.testBundledInput( side, color )\nredstone.setBundledOutput( side, colors )\nredstone.getBundledOutput( side )\nType "help bundled" for usage examples.\n\nEvents emitted by the redstone API:\n"redstone", when the state of any redstone input changes. Use getInput() or getBundledInput() to inspect the changes\nType "help events" to learn about the event system.\n',"rom/help/refuel.txt":'refuel is a program for Turtles. Refuel will consume items from the inventory as fuel for turtle.\n\nex:\n"refuel" will refuel with at most one fuel item\n"refuel 10" will refuel with at most 10 fuel items\n"refuel all" will refuel with as many fuel items as possible\n',"rom/help/rename.txt":'rename renames a file or directory.\n\nex:\n"rename foo bar" renames the file "foo" to "bar".\n',"rom/help/repeat.txt":'repeat is a program for repeating rednet messages across long distances. To use, connect 2 or more modems to a computer and run the "repeat" program; from then on, any rednet message sent from any computer in wireless range or connected by networking cable to either of the modems will be repeated to those on the other side.\n',"rom/help/rs.txt":'Functions in the Redstone API:\nrs.getSides( )\nrs.getInput( side )\nrs.setOutput( side, boolean )\nrs.getOutput( side )\nrs.getAnalogInput( side )\nrs.setAnalogOutput( side, number )\nrs.getAnalogOutput( side )\n\nFunctions in the Redstone API for working with RedPower bundled cables:\nrs.getBundledInput( side )\nrs.testBundledInput( side, color )\nrs.setBundledOutput( side, colors )\nrs.getBundledOutput( side )\nType "help bundled" for usage examples.\n\nEvents emitted by the redstone API:\n"redstone", when the state of any redstone input changes. Use getInput() or getBundledInput() to inspect the changes\nType "help events" to learn about the event system.\n',"rom/help/set.txt":'The set program can be used to inspect and change system settings.\n\nUsage:\n"set" will print all the system settings and their values\n"set foo" will print the value of the system setting "foo"\n"set foo bar" will set the value of the system setting "foo" to "bar"\n',"rom/help/settings.txt":"Functions in the Settings API:\nsettings.get( name, [default] )\nsettings.set( name, value )\nsettings.unset( name )\nsettings.load( path )\nsettings.save( path )\nsettings.clear()\nsettings.getNames()\n\nDefault Settings:\nshell.autocomplete - enables auto-completion in the Shell.\nlua.autocomplete - enables auto-completion in the Lua program.\nedit.autocomplete - enables auto-completion in the Edit program.\nedit.default_extension - sets the default file extension for files created with the Edit program\npaint.default_extension - sets the default file extension for files created with the Paint program\nbios.use_multishell - enables Multishell on Advanced Computers, Turtles, Pocket Computers and Command Computers.\nshell.allow_disk_startup - if a Disk Drive with a Disk inside that has a 'startup' script is attached to a computer, this setting allows to automatically run that script when the computer starts.\nshell.allow_startup - if there is a 'startup' script in a computer's root, this setting allow to automatically run that script when the computer runs.\nlist.show_hidden - determines, whether the List program will list hidden files or not.\n","rom/help/shell.txt":'shell is the toplevel program which interprets commands and runs program.\nType "help shellapi" for information about the shell lua api.\n',"rom/help/shellapi.txt":"Functions in the Shell API:\nshell.exit()\nshell.dir()\nshell.setDir( path )\nshell.path()\nshell.setPath( path )\nshell.resolve( localpath )\nshell.resolveProgram( name )\nshell.aliases()\nshell.setAlias( alias, command )\nshell.clearAlias( alias )\nshell.programs()\nshell.run( program, arguments )\nshell.getRunningProgram()\nshell.complete( line )\nshell.completeProgram( program )\nshell.setCompletionFunction( program, fnComplete )\nshell.openTab( program, arguments ) (Advanced Computer required)\nshell.switchTab( n ) (Advanced Computer required)\n","rom/help/shutdown.txt":"shutdown will turn off the computer.\n","rom/help/speaker.md":'The speaker program plays audio files using speakers attached to this computer.\n\nIt supports audio files in a limited number of formats:\n* DFPWM: You can convert music to DFPWM with external tools like https://music.madefor.cc.\n* WAV: WAV files must be 8-bit PCM or DFPWM, with exactly one channel and a sample rate of 48kHz.\n\n## Examples:\n* `speaker play example.dfpwm left` plays the "example.dfpwm" audio file using the speaker on the left of the computer.\n* `speaker stop` stops any currently playing audio.\n',"rom/help/speakers.txt":'The Speaker is a peripheral device available for CraftOS. Type "help peripheral" to learn about using the Peripheral API to connect with peripherals. When a Speaker is connected, peripheral.getType() will return "speaker".\n\nMethods exposed by the Speaker:\nplaySound( sResourceName, nVolume, nPitch )\nplayNote( sInstrumentName, nVolume, nPitch )\n\nResource name is the same as used by the /playsound command, such as "minecraft:entity.cow.ambient".\nInstruments are as follows: "harp", "bass", "snare", "hat", and "basedrum" with the addition of "flute", "bell", "chime", and "guitar" in Minecraft versions 1.12 and above.\nTicks is the amount of times a noteblock has been tuned (right clicked).\n',"rom/help/string.txt":"string is a standard Lua5.1 API.\nRefer to http://www.lua.org/manual/5.1/ for more information.\n","rom/help/table.txt":"table is a standard Lua5.1 API.\nRefer to http://www.lua.org/manual/5.1/ for more information.\n","rom/help/term.txt":'Functions in the Terminal API:\nterm.write( text )\nterm.blit( text, textColor, backgroundColor )\nterm.clear()\nterm.clearLine()\nterm.getCursorPos()\nterm.setCursorPos( x, y )\nterm.setCursorBlink( blink )\nterm.isColor()\nterm.setTextColor( color )\nterm.setBackgroundColor( color )\nterm.getTextColor()\nterm.getBackgroundColor()\nterm.getSize()\nterm.scroll( n )\nterm.redirect( object )\nterm.current()\nterm.setPaletteColor( color, r, g, b )\nterm.getPaletteColor( color )\n\nEvents emitted by the terminals:\n"term_resize", when the size of a terminal changes. This can happen in multitasking environments, or when the terminal out is being redirected by the "monitor" program.\n',"rom/help/textutils.txt":"Functions in the Text Utilities API:\ntextutils.slowPrint( text )\ntextutils.tabulate( table, table2, ... )\ntextutils.pagedTabulate( table, table2, ... )\ntextutils.formatTime( time, bTwentyFourHour )\ntextutils.serialize( table )\ntextutils.unserialize( string )\ntextutils.serializeJSON( table, [useNBTStyle] )\ntextutils.urlEncode( string )\ntextutils.complete( string, table )\n","rom/help/time.txt":"time prints the current time of day.\n","rom/help/tunnel.txt":'tunnel is a program for Mining Turtles. Tunnel will mine a 3x2 tunnel of the depth specified.\n\nex:\n"tunnel 20" will tunnel a tunnel 20 blocks long.\n',"rom/help/turn.txt":'turn is a program for Turtles, used to turn the turtle around without programming. It accepts one or more commands as a direction and a number of turns. The "go" program can also be used for turning.\n\nex:\n"turn left" turns the turtle 90 degrees left.\n"turn right 2" turns the turtle 180 degrees right.\n"turn left 2 right" turns left 180 degrees, then right 90 degrees.\n',"rom/help/turtle.txt":'turtle is an api available on Turtles, which controls their movement.\nFunctions in the Turtle API:\nturtle.forward()\nturtle.back()\nturtle.up()\nturtle.down()\nturtle.turnLeft()\nturtle.turnRight()\nturtle.select( slotNum )\nturtle.getSelectedSlot()\nturtle.getItemCount( [slotNum] )\nturtle.getItemSpace( [slotNum] )\nturtle.getItemDetail( [slotNum] )\nturtle.equipLeft()\nturtle.equipRight()\nturtle.dig( [toolSide] )\nturtle.digUp( [toolSide] )\nturtle.digDown( [toolSide] )\nturtle.place()\nturtle.placeUp()\nturtle.placeDown()\nturtle.attack( [toolSide] )\nturtle.attackUp( [toolSide] )\nturtle.attackDown( [toolSide] )\nturtle.detect()\nturtle.detectUp()\nturtle.detectDown()\nturtle.compare()\nturtle.compareUp()\nturtle.compareDown()\nturtle.inspect()\nturtle.inspectUp()\nturtle.inspectDown()\nturtle.compareTo( slotNum )\nturtle.transferTo( slotNum, [quantity] )\nturtle.drop( [quantity] )\nturtle.dropUp( [quantity] )\nturtle.dropDown( [quantity] )\nturtle.suck( [quantity] )\nturtle.suckUp( [quantity] )\nturtle.suckDown( [quantity] )\nturtle.getFuelLevel()\nturtle.getFuelLimit()\nturtle.refuel( [quantity] )\nturtle.craft( [quantity] ) (requires Crafty Turtle)\n\nEvents fired by the Turtle API:\n"turtle_inventory" when any of the items in the inventory are changed. Use comparison operations to inspect the changes.\n',"rom/help/type.txt":'type determines the type of a file or directory. Prints "file", "directory" or "does not exist".\n',"rom/help/unequip.txt":'unequip is a program for Turtles and Pocket Computers. unequip will remove tools of peripherals from the specified side of the turtle. On a Pocket Computer you don\'t need to write a side.\n\nex:\n"unequip left" will remove the item on the left side of the turtle\n"unequip" on a Pocket Computer will remove the item from the Pocket Computer\n',"rom/help/vector.txt":"Functions in the 3D Vector Math API:\nvector.new( x,y,z )\n\nVectors returned by vector.new() have the following fields and methods:\nvector.x\nvector.y\nvector.z\nvector:add( vector )\nvector:sub( vector )\nvector:mul( number )\nvector:dot( vector )\nvector:cross( vector )\nvector:length()\nvector:normalize()\nvector:round()\nvector:tostring()\nThe +, - and * operators can also be used on vectors.\n","rom/help/wget.txt":'wget is a program for downloading files from the internet. This is useful for downloading programs created by other players.\nIf no filename is specified wget will try to determine the filename from the URL by stripping any anchors, parameters and trailing slashes and then taking everything remaining after the last slash.\nThe HTTP API must be enabled in ComputerCraft.cfg to use this program.\nex:\n"wget http://pastebin.com/raw/CxaWmPrX test" will download the file from the URL http://pastebin.com/raw/CxaWmPrX, and save it as "test".\n"wget http://example.org/test.lua/?foo=bar#qzu" will download the file from the URL http://example.org/test.lua/?foo=bar#qzu and save it as "test.lua"\n"wget http://example.org/" will download the file from the URL http://example.org and save it as "example.org"\n"wget run http://pastebin.com/raw/CxaWmPrX" will download the file from the URL http://pastebin.com/raw/CxaWmPrX and run it immediately.\n',"rom/help/whatsnew.md":'New features in CC: Tweaked 1.108.4\n\n* Rewrite `@LuaFunction` generation to use `MethodHandle`s instead of ASM.\n* Refactor `ComputerThread` to provide a cleaner interface.\n* Remove `disable_lua51_features` config option.\n* Update several translations (Sammy).\n\nSeveral bug fixes:\n* Fix monitor peripheral becoming "detached" after breaking and replacing a monitor.\n* Fix signs being empty when placed.\n* Fix several inconsistencies with mount error messages.\n\nType "help changelog" to see the full version history.\n',"rom/help/window.txt":"Functions in the window API:\nwindow.create( parent, x, y, width, height, visible )\n\nWindows created with the window API have the following methods:\nwrite( text )\nblit( text, textColor, backgroundColor )\nclear()\nclearLine()\ngetCursorPos()\nsetCursorPos( x, y )\nsetCursorBlink( blink )\nisColor()\nsetTextColor( color )\nsetBackgroundColor( color )\ngetTextColor()\ngetBackgroundColor()\ngetSize()\nscroll( n )\nsetVisible( bVisible )\nredraw()\nrestoreCursor()\ngetPosition()\nreposition( x, y, width, height )\ngetPaletteColor( color )\nsetPaletteColor( color, r, g, b )\ngetLine()\n","rom/help/workbench.txt":'Workbenches are peripheral devices found on Crafty Turtles running CraftOS. Type "help peripheral" to learn about using the Peripheral API to connect with peripherals. When a workbench is attached to a turtle, peripheral.getType() will return "workbench".\n\nMethods exposed by Workbenches:\ncraft( channel )\n',"rom/help/worm.txt":'You\'ve played it in the arcades, now experience the high-octane thrills of the hit game "WORM!" on your home computer! Only on CraftOS!\n',"rom/modules/command/.ignoreme":'--[[\nAlright then, don\'t ignore me. This file is to ensure the existence of the "modules/command" folder.\nYou can use this folder to add modules who can be loaded with require() to your Resourcepack.\n]]\n',"rom/modules/main/.ignoreme":'--[[\nAlright then, don\'t ignore me. This file is to ensure the existence of the "modules/main" folder.\nYou can use this folder to add modules who can be loaded with require() to your Resourcepack.\n]]\n',"rom/modules/main/cc/audio/dfpwm.lua":'-- SPDX-FileCopyrightText: 2021 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\n--[[-\nConvert between streams of DFPWM audio data and a list of amplitudes.\n\nDFPWM (Dynamic Filter Pulse Width Modulation) is an audio codec designed by GreaseMonkey. It\'s a relatively compact\nformat compared to raw PCM data, only using 1 bit per sample, but is simple enough to simple enough to encode and decode\nin real time.\n\nTypically DFPWM audio is read from [the filesystem][`fs.BinaryReadHandle`] or a [a web request][`http.Response`] as a\nstring, and converted a format suitable for [`speaker.playAudio`].\n\n## Encoding and decoding files\nThis modules exposes two key functions, [`make_decoder`] and [`make_encoder`], which construct a new decoder or encoder.\nThe returned encoder/decoder is itself a function, which converts between the two kinds of data.\n\nThese encoders and decoders have lots of hidden state, so you should be careful to use the same encoder or decoder for\na specific audio stream. Typically you will want to create a decoder for each stream of audio you read, and an encoder\nfor each one you write.\n\n## Converting audio to DFPWM\nDFPWM is not a popular file format and so standard audio processing tools will not have an option to export to it.\nInstead, you can convert audio files online using [music.madefor.cc], the [LionRay Wav Converter][LionRay] Java\napplication or development builds of [FFmpeg].\n\n[music.madefor.cc]: https://music.madefor.cc/ "DFPWM audio converter for Computronics and CC: Tweaked"\n[LionRay]: https://github.com/gamax92/LionRay/ "LionRay Wav Converter "\n[FFmpeg]: https://ffmpeg.org "FFmpeg command-line audio manipulation library"\n\n@see guide!speaker_audio Gives a more general introduction to audio processing and the speaker.\n@see speaker.playAudio To play the decoded audio data.\n@since 1.100.0\n@usage Reads "data/example.dfpwm" in chunks, decodes them and then doubles the speed of the audio. The resulting audio\nis then re-encoded and saved to "speedy.dfpwm". This processed audio can then be played with the `speaker` program.\n\n```lua\nlocal dfpwm = require("cc.audio.dfpwm")\n\nlocal encoder = dfpwm.make_encoder()\nlocal decoder = dfpwm.make_decoder()\n\nlocal out = fs.open("speedy.dfpwm", "wb")\nfor input in io.lines("data/example.dfpwm", 16 * 1024 * 2) do\n local decoded = decoder(input)\n local output = {}\n\n -- Read two samples at once and take the average.\n for i = 1, #decoded, 2 do\n local value_1, value_2 = decoded[i], decoded[i + 1]\n output[(i + 1) / 2] = (value_1 + value_2) / 2\n end\n\n out.write(encoder(output))\n\n sleep(0) -- This program takes a while to run, so we need to make sure we yield.\nend\nout.close()\n```\n]]\n\nlocal expect = require "cc.expect".expect\n\nlocal char, byte, floor, band, rshift = string.char, string.byte, math.floor, bit32.band, bit32.arshift\n\nlocal PREC = 10\nlocal PREC_POW = 2 ^ PREC\nlocal PREC_POW_HALF = 2 ^ (PREC - 1)\nlocal STRENGTH_MIN = 2 ^ (PREC - 8 + 1)\n\nlocal function make_predictor()\n local charge, strength, previous_bit = 0, 0, false\n\n return function(current_bit)\n local target = current_bit and 127 or -128\n\n local next_charge = charge + floor((strength * (target - charge) + PREC_POW_HALF) / PREC_POW)\n if next_charge == charge and next_charge ~= target then\n next_charge = next_charge + (current_bit and 1 or -1)\n end\n\n local z = current_bit == previous_bit and PREC_POW - 1 or 0\n local next_strength = strength\n if next_strength ~= z then next_strength = next_strength + (current_bit == previous_bit and 1 or -1) end\n if next_strength < STRENGTH_MIN then next_strength = STRENGTH_MIN end\n\n charge, strength, previous_bit = next_charge, next_strength, current_bit\n return charge\n end\nend\n\n--[[- Create a new encoder for converting PCM audio data into DFPWM.\n\nThe returned encoder is itself a function. This function accepts a table of amplitude data between -128 and 127 and\nreturns the encoded DFPWM data.\n\n> [Reusing encoders][!WARNING]\n> Encoders have lots of internal state which tracks the state of the current stream. If you reuse an encoder for multiple\n> streams, or use different encoders for the same stream, the resulting audio may not sound correct.\n\n@treturn function(pcm: { number... }):string The encoder function\n@see encode A helper function for encoding an entire file of audio at once.\n]]\nlocal function make_encoder()\n local predictor = make_predictor()\n local previous_charge = 0\n\n return function(input)\n expect(1, input, "table")\n\n local output, output_n = {}, 0\n for i = 1, #input, 8 do\n local this_byte = 0\n for j = 0, 7 do\n local inp_charge = floor(input[i + j] or 0)\n if inp_charge > 127 or inp_charge < -128 then\n error(("Amplitude at position %d was %d, but should be between -128 and 127"):format(i + j, inp_charge), 2)\n end\n\n local current_bit = inp_charge > previous_charge or (inp_charge == previous_charge and inp_charge == 127)\n this_byte = floor(this_byte / 2) + (current_bit and 128 or 0)\n\n previous_charge = predictor(current_bit)\n end\n\n output_n = output_n + 1\n output[output_n] = char(this_byte)\n end\n\n return table.concat(output, "", 1, output_n)\n end\nend\n\n--[[- Create a new decoder for converting DFPWM into PCM audio data.\n\nThe returned decoder is itself a function. This function accepts a string and returns a table of amplitudes, each value\nbetween -128 and 127.\n\n> [Reusing decoders][!WARNING]\n> Decoders have lots of internal state which tracks the state of the current stream. If you reuse an decoder for\n> multiple streams, or use different decoders for the same stream, the resulting audio may not sound correct.\n\n@treturn function(dfpwm: string):{ number... } The encoder function\n@see decode A helper function for decoding an entire file of audio at once.\n\n@usage Reads "data/example.dfpwm" in blocks of 16KiB (the speaker can accept a maximum of 128\xd71024 samples), decodes\nthem and then plays them through the speaker.\n\n```lua {data-peripheral=speaker}\nlocal dfpwm = require "cc.audio.dfpwm"\nlocal speaker = peripheral.find("speaker")\n\nlocal decoder = dfpwm.make_decoder()\nfor input in io.lines("data/example.dfpwm", 16 * 1024) do\n local decoded = decoder(input)\n while not speaker.playAudio(decoded) do\n os.pullEvent("speaker_audio_empty")\n end\nend\n```\n]]\nlocal function make_decoder()\n local predictor = make_predictor()\n local low_pass_charge = 0\n local previous_charge, previous_bit = 0, false\n\n return function (input)\n expect(1, input, "string")\n\n local output, output_n = {}, 0\n for i = 1, #input do\n local input_byte = byte(input, i)\n for _ = 1, 8 do\n local current_bit = band(input_byte, 1) ~= 0\n local charge = predictor(current_bit)\n\n local antijerk = charge\n if current_bit ~= previous_bit then\n antijerk = floor((charge + previous_charge + 1) / 2)\n end\n\n previous_charge, previous_bit = charge, current_bit\n\n low_pass_charge = low_pass_charge + floor(((antijerk - low_pass_charge) * 140 + 0x80) / 256)\n\n output_n = output_n + 1\n output[output_n] = low_pass_charge\n\n input_byte = rshift(input_byte, 1)\n end\n end\n\n return output\n end\nend\n\n--[[- A convenience function for decoding a complete file of audio at once.\n\nThis should only be used for short files. For larger files, one should read the file in chunks and process it using\n[`make_decoder`].\n\n@tparam string input The DFPWM data to convert.\n@treturn { number... } The produced amplitude data.\n@see make_decoder\n]]\nlocal function decode(input)\n expect(1, input, "string")\n return make_decoder()(input)\nend\n\n--[[- A convenience function for encoding a complete file of audio at once.\n\nThis should only be used for complete pieces of audio. If you are writing writing multiple chunks to the same place,\nyou should use an encoder returned by [`make_encoder`] instead.\n\n@tparam { number... } input The table of amplitude data.\n@treturn string The encoded DFPWM data.\n@see make_encoder\n]]\nlocal function encode(input)\n expect(1, input, "table")\n return make_encoder()(input)\nend\n\nreturn {\n make_encoder = make_encoder,\n encode = encode,\n\n make_decoder = make_decoder,\n decode = decode,\n}\n',"rom/modules/main/cc/completion.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--- A collection of helper methods for working with input completion, such\n-- as that require by [`_G.read`].\n--\n-- @module cc.completion\n-- @see cc.shell.completion For additional helpers to use with\n-- [`shell.setCompletionFunction`].\n-- @since 1.85.0\n\nlocal expect = require "cc.expect".expect\n\nlocal function choice_impl(text, choices, add_space)\n local results = {}\n for n = 1, #choices do\n local option = choices[n]\n if #option + (add_space and 1 or 0) > #text and option:sub(1, #text) == text then\n local result = option:sub(#text + 1)\n if add_space then\n table.insert(results, result .. " ")\n else\n table.insert(results, result)\n end\n end\n end\n return results\nend\n\n--- Complete from a choice of one or more strings.\n--\n-- @tparam string text The input string to complete.\n-- @tparam { string... } choices The list of choices to complete from.\n-- @tparam[opt] boolean add_space Whether to add a space after the completed item.\n-- @treturn { string... } A list of suffixes of matching strings.\n-- @usage Call [`_G.read`], completing the names of various animals.\n--\n-- local completion = require "cc.completion"\n-- local animals = { "dog", "cat", "lion", "unicorn" }\n-- read(nil, nil, function(text) return completion.choice(text, animals) end)\nlocal function choice(text, choices, add_space)\n expect(1, text, "string")\n expect(2, choices, "table")\n expect(3, add_space, "boolean", "nil")\n return choice_impl(text, choices, add_space)\nend\n\n--- Complete the name of a currently attached peripheral.\n--\n-- @tparam string text The input string to complete.\n-- @tparam[opt] boolean add_space Whether to add a space after the completed name.\n-- @treturn { string... } A list of suffixes of matching peripherals.\n-- @usage\n-- local completion = require "cc.completion"\n-- read(nil, nil, completion.peripheral)\nlocal function peripheral_(text, add_space)\n expect(1, text, "string")\n expect(2, add_space, "boolean", "nil")\n return choice_impl(text, peripheral.getNames(), add_space)\nend\n\nlocal sides = redstone.getSides()\n\n--- Complete the side of a computer.\n--\n-- @tparam string text The input string to complete.\n-- @tparam[opt] boolean add_space Whether to add a space after the completed side.\n-- @treturn { string... } A list of suffixes of matching sides.\n-- @usage\n-- local completion = require "cc.completion"\n-- read(nil, nil, completion.side)\nlocal function side(text, add_space)\n expect(1, text, "string")\n expect(2, add_space, "boolean", "nil")\n return choice_impl(text, sides, add_space)\nend\n\n--- Complete a [setting][`settings`].\n--\n-- @tparam string text The input string to complete.\n-- @tparam[opt] boolean add_space Whether to add a space after the completed settings.\n-- @treturn { string... } A list of suffixes of matching settings.\n-- @usage\n-- local completion = require "cc.completion"\n-- read(nil, nil, completion.setting)\nlocal function setting(text, add_space)\n expect(1, text, "string")\n expect(2, add_space, "boolean", "nil")\n return choice_impl(text, settings.getNames(), add_space)\nend\n\nlocal command_list\n\n--- Complete the name of a Minecraft [command][`commands`].\n--\n-- @tparam string text The input string to complete.\n-- @tparam[opt] boolean add_space Whether to add a space after the completed command.\n-- @treturn { string... } A list of suffixes of matching commands.\n-- @usage\n-- local completion = require "cc.completion"\n-- read(nil, nil, completion.command)\nlocal function command(text, add_space)\n expect(1, text, "string")\n expect(2, add_space, "boolean", "nil")\n if command_list == nil then\n command_list = commands and commands.list() or {}\n end\n\n return choice_impl(text, command_list, add_space)\nend\n\nreturn {\n choice = choice,\n peripheral = peripheral_,\n side = side,\n setting = setting,\n command = command,\n}\n',"rom/modules/main/cc/expect.lua":'-- SPDX-FileCopyrightText: 2019 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\n--[[- The [`cc.expect`] library provides helper functions for verifying that\nfunction arguments are well-formed and of the correct type.\n\n@module cc.expect\n@since 1.84.0\n@changed 1.96.0 The module can now be called directly as a function, which wraps around `expect.expect`.\n@usage Define a basic function and check it has the correct arguments.\n\n local expect = require "cc.expect"\n local expect, field = expect.expect, expect.field\n\n local function add_person(name, info)\n expect(1, name, "string")\n expect(2, info, "table", "nil")\n\n if info then\n print("Got age=", field(info, "age", "number"))\n print("Got gender=", field(info, "gender", "string", "nil"))\n end\n end\n\n add_person("Anastazja") -- `info\' is optional\n add_person("Kion", { age = 23 }) -- `gender\' is optional\n add_person("Caoimhin", { age = 23, gender = true }) -- error!\n]]\n\nlocal native_select, native_type = select, type\n\nlocal function get_type_names(...)\n local types = table.pack(...)\n for i = types.n, 1, -1 do\n if types[i] == "nil" then table.remove(types, i) end\n end\n\n if #types <= 1 then\n return tostring(...)\n else\n return table.concat(types, ", ", 1, #types - 1) .. " or " .. types[#types]\n end\nend\n\n\nlocal function get_display_type(value, t)\n -- Lua is somewhat inconsistent in whether it obeys __name just for values which\n -- have a per-instance metatable (so tables/userdata) or for everything. We follow\n -- Cobalt and only read the metatable for tables/userdata.\n if t ~= "table" and t ~= "userdata" then return t end\n\n local metatable = debug.getmetatable(value)\n if not metatable then return t end\n\n local name = rawget(metatable, "__name")\n if type(name) == "string" then return name else return t end\nend\n\n--- Expect an argument to have a specific type.\n--\n-- @tparam number index The 1-based argument index.\n-- @param value The argument\'s value.\n-- @tparam string ... The allowed types of the argument.\n-- @return The given `value`.\n-- @throws If the value is not one of the allowed types.\nlocal function expect(index, value, ...)\n local t = native_type(value)\n for i = 1, native_select("#", ...) do\n if t == native_select(i, ...) then return value end\n end\n\n -- If we can determine the function name with a high level of confidence, try to include it.\n local name\n local ok, info = pcall(debug.getinfo, 3, "nS")\n if ok and info.name and info.name ~= "" and info.what ~= "C" then name = info.name end\n\n t = get_display_type(value, t)\n\n local type_names = get_type_names(...)\n if name then\n error(("bad argument #%d to \'%s\' (%s expected, got %s)"):format(index, name, type_names, t), 3)\n else\n error(("bad argument #%d (%s expected, got %s)"):format(index, type_names, t), 3)\n end\nend\n\n--- Expect an field to have a specific type.\n--\n-- @tparam table tbl The table to index.\n-- @tparam string index The field name to check.\n-- @tparam string ... The allowed types of the argument.\n-- @return The contents of the given field.\n-- @throws If the field is not one of the allowed types.\nlocal function field(tbl, index, ...)\n expect(1, tbl, "table")\n expect(2, index, "string")\n\n local value = tbl[index]\n local t = native_type(value)\n for i = 1, native_select("#", ...) do\n if t == native_select(i, ...) then return value end\n end\n\n t = get_display_type(value, t)\n\n if value == nil then\n error(("field \'%s\' missing from table"):format(index), 3)\n else\n error(("bad field \'%s\' (%s expected, got %s)"):format(index, get_type_names(...), t), 3)\n end\nend\n\nlocal function is_nan(num)\n return num ~= num\nend\n\n--- Expect a number to be within a specific range.\n--\n-- @tparam number num The value to check.\n-- @tparam number min The minimum value, if nil then `-math.huge` is used.\n-- @tparam number max The maximum value, if nil then `math.huge` is used.\n-- @return The given `value`.\n-- @throws If the value is outside of the allowed range.\n-- @since 1.96.0\nlocal function range(num, min, max)\n expect(1, num, "number")\n min = expect(2, min, "number", "nil") or -math.huge\n max = expect(3, max, "number", "nil") or math.huge\n if min > max then\n error("min must be less than or equal to max)", 2)\n end\n\n if is_nan(num) or num < min or num > max then\n error(("number outside of range (expected %s to be within %s and %s)"):format(num, min, max), 3)\n end\n\n return num\nend\n\nreturn setmetatable({\n expect = expect,\n field = field,\n range = range,\n}, { __call = function(_, ...) return expect(...) end })\n',"rom/modules/main/cc/image/nft.lua":'-- SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\n--- Read and draw nft ("Nitrogen Fingers Text") images.\n--\n-- nft ("Nitrogen Fingers Text") is a file format for drawing basic images.\n-- Unlike the images that [`paintutils.parseImage`] uses, nft supports coloured\n-- text as well as simple coloured pixels.\n--\n-- @module cc.image.nft\n-- @since 1.90.0\n-- @usage Load an image from `example.nft` and draw it.\n--\n-- local nft = require "cc.image.nft"\n-- local image = assert(nft.load("data/example.nft"))\n-- nft.draw(image, term.getCursorPos())\n\nlocal expect = require "cc.expect".expect\n\n--- Parse an nft image from a string.\n--\n-- @tparam string image The image contents.\n-- @return table The parsed image.\nlocal function parse(image)\n expect(1, image, "string")\n\n local result = {}\n local line = 1\n local foreground = "0"\n local background = "f"\n\n local i, len = 1, #image\n while i <= len do\n local c = image:sub(i, i)\n if c == "\\31" and i < len then\n i = i + 1\n foreground = image:sub(i, i)\n elseif c == "\\30" and i < len then\n i = i + 1\n background = image:sub(i, i)\n elseif c == "\\n" then\n if result[line] == nil then\n result[line] = { text = "", foreground = "", background = "" }\n end\n\n line = line + 1\n foreground, background = "0", "f"\n else\n local next = image:find("[\\n\\30\\31]", i) or #image + 1\n local seg_len = next - i\n\n local this_line = result[line]\n if this_line == nil then\n this_line = { foreground = "", background = "", text = "" }\n result[line] = this_line\n end\n\n this_line.text = this_line.text .. image:sub(i, next - 1)\n this_line.foreground = this_line.foreground .. foreground:rep(seg_len)\n this_line.background = this_line.background .. background:rep(seg_len)\n\n i = next - 1\n end\n\n i = i + 1\n end\n return result\nend\n\n--- Load an nft image from a file.\n--\n-- @tparam string path The file to load.\n-- @treturn[1] table The parsed image.\n-- @treturn[2] nil If the file does not exist or could not be loaded.\n-- @treturn[2] string An error message explaining why the file could not be\n-- loaded.\nlocal function load(path)\n expect(1, path, "string")\n local file, err = io.open(path, "r")\n if not file then return nil, err end\n\n local result = file:read("*a")\n file:close()\n return parse(result)\nend\n\n--- Draw an nft image to the screen.\n--\n-- @tparam table image An image, as returned from [`load`] or [`parse`].\n-- @tparam number xPos The x position to start drawing at.\n-- @tparam number xPos The y position to start drawing at.\n-- @tparam[opt] term.Redirect target The terminal redirect to draw to. Defaults to the\n-- current terminal.\nlocal function draw(image, xPos, yPos, target)\n expect(1, image, "table")\n expect(2, xPos, "number")\n expect(3, yPos, "number")\n expect(4, target, "table", "nil")\n\n if not target then target = term end\n\n for y, line in ipairs(image) do\n target.setCursorPos(xPos, yPos + y - 1)\n target.blit(line.text, line.foreground, line.background)\n end\nend\n\nreturn {\n parse = parse,\n load = load,\n draw = draw,\n}\n',"rom/modules/main/cc/internal/error_printer.lua":'-- SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\n--[[- A pretty-printer for Lua errors.\n\n> [!DANGER]\n> This is an internal module and SHOULD NOT be used in your own code. It may\n> be removed or changed at any time.\n\nThis consumes a list of messages and "annotations" and displays the error to the\nterminal.\n\n@see cc.internal.syntax.errors For errors produced by the parser.\n@local\n]]\n\nlocal pretty = require "cc.pretty"\nlocal expect = require "cc.expect"\nlocal expect, field = expect.expect, expect.field\nlocal wrap = require "cc.strings".wrap\n\n--- Write a message to the screen.\n-- @tparam cc.pretty.Doc|string msg The message to write.\nlocal function display(msg)\n if type(msg) == "table" then pretty.print(msg) else print(msg) end\nend\n\n-- Write a message to the screen, aligning to the current cursor position.\n-- @tparam cc.pretty.Doc|string msg The message to write.\nlocal function display_here(msg, preamble)\n expect(1, msg, "string", "table")\n local x = term.getCursorPos()\n local width, height = term.getSize()\n width = width - x + 1\n\n local function newline()\n local _, y = term.getCursorPos()\n if y >= height then\n term.scroll(1)\n else\n y = y + 1\n end\n\n preamble(y)\n term.setCursorPos(x, y)\n end\n\n if type(msg) == "string" then\n local lines = wrap(msg, width)\n term.write(lines[1])\n for i = 2, #lines do\n newline()\n term.write(lines[i])\n end\n else\n local def_colour = term.getTextColour()\n local function display_impl(doc)\n expect(1, doc, "table")\n local kind = doc.tag\n if kind == "nil" then return\n elseif kind == "text" then\n -- TODO: cc.strings.wrap doesn\'t support a leading indent. We should\n -- fix that!\n -- Might also be nice to add a wrap_iter, which returns an iterator over\n -- start_pos, end_pos instead.\n\n if doc.colour then term.setTextColour(doc.colour) end\n local x1 = term.getCursorPos()\n\n local lines = wrap((" "):rep(x1 - x) .. doc.text, width)\n term.write(lines[1]:sub(x1 - x + 1))\n for i = 2, #lines do\n newline()\n term.write(lines[i])\n end\n\n if doc.colour then term.setTextColour(def_colour) end\n elseif kind == "concat" then\n for i = 1, doc.n do display_impl(doc[i]) end\n else\n error("Unknown doc " .. kind)\n end\n end\n display_impl(msg)\n end\n print()\nend\n\n--- A list of colours we can use for error messages.\nlocal error_colours = { colours.red, colours.green, colours.magenta, colours.orange }\n\n--- The accent line used to denote a block of code.\nlocal code_accent = pretty.text("\\x95", colours.cyan)\n\n--[[-\n@tparam { get_pos = function, get_line = function } context\n The context where the error was reported. This effectively acts as a view\n over the underlying source, exposing the following functions:\n - `get_pos`: Get the line and column of an opaque position.\n - `get_line`: Get the source code for an opaque position.\n@tparam table message The message to display, as produced by [`cc.internal.syntax.errors`].\n]]\nreturn function(context, message)\n expect(1, context, "table")\n expect(2, message, "table")\n field(context, "get_pos", "function")\n field(context, "get_line", "function")\n\n if #message == 0 then error("Message is empty", 2) end\n\n local error_colour = 1\n local width = term.getSize()\n\n for msg_idx = 1, #message do\n if msg_idx > 1 then print() end\n\n local msg = message[msg_idx]\n if type(msg) == "table" and msg.tag == "annotate" then\n local line, col = context.get_pos(msg.start_pos)\n local end_line, end_col = context.get_pos(msg.end_pos)\n local contents = context.get_line(msg.start_pos)\n\n -- Pick a starting column. We pick the left-most position which fits\n -- in one of the following:\n -- - 10 characters after the start column.\n -- - 5 characters after the end column.\n -- - The end of the line.\n if line ~= end_line then end_col = #contents end\n local start_col = math.max(1, math.min(col + 10, end_col + 5, #contents + 1) - width + 1)\n\n -- Pick a colour for this annotation.\n local colour = colours.toBlit(error_colours[error_colour])\n error_colour = (error_colour % #error_colours) + 1\n\n -- Print the line number and snippet of code. We display french\n -- quotes on either side of the string if it is truncated.\n local str_start, str_end = start_col, start_col + width - 2\n local prefix, suffix = "", ""\n if start_col > 1 then\n str_start = str_start + 1\n prefix = pretty.text("\\xab", colours.grey)\n end\n if str_end < #contents then\n str_end = str_end - 1\n suffix = pretty.text("\\xbb", colours.grey)\n end\n\n pretty.print(code_accent .. pretty.text("Line " .. line, colours.cyan))\n pretty.print(code_accent .. prefix .. pretty.text(contents:sub(str_start, str_end), colours.lightGrey) .. suffix)\n\n -- Print a line highlighting the region of text.\n local _, y = term.getCursorPos()\n pretty.write(code_accent)\n\n local indicator_end = end_col\n if end_col > str_end then indicator_end = str_end end\n\n local indicator_len = indicator_end - col + 1\n term.setCursorPos(col - start_col + 2, y)\n term.blit(("\\x83"):rep(indicator_len), colour:rep(indicator_len), ("f"):rep(indicator_len))\n print()\n\n -- And then print the annotation\'s message, if present.\n if msg.msg ~= "" then\n term.blit("\\x95", colour, "f")\n display_here(msg.msg, function(y)\n term.setCursorPos(1, y)\n term.blit("\\x95", colour, "f")\n end)\n end\n else\n display(msg)\n end\n end\nend\n',"rom/modules/main/cc/internal/exception.lua":'-- SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\n--[[- Internal tools for working with errors.\n\n> [!DANGER]\n> This is an internal module and SHOULD NOT be used in your own code. It may\n> be removed or changed at any time.\n\n@local\n]]\n\nlocal expect = require "cc.expect".expect\nlocal error_printer = require "cc.internal.error_printer"\n\nlocal function find_frame(thread, file, line)\n -- Scan the first 16 frames for something interesting.\n for offset = 0, 15 do\n local frame = debug.getinfo(thread, offset, "Sl")\n if not frame then break end\n\n if frame.short_src == file and frame.what ~= "C" and frame.currentline == line then\n return frame\n end\n end\nend\n\n--[[- Attempt to call the provided function `func` with the provided arguments.\n\n@tparam function func The function to call.\n@param ... Arguments to this function.\n\n@treturn[1] true If the function ran successfully.\n @return[1] ... The return values of the function.\n\n@treturn[2] false If the function failed.\n@return[2] The error message\n@treturn[2] coroutine The thread where the error occurred.\n]]\nlocal function try(func, ...)\n expect(1, func, "function")\n\n local co = coroutine.create(func)\n local result = table.pack(coroutine.resume(co, ...))\n\n while coroutine.status(co) ~= "dead" do\n local event = table.pack(os.pullEventRaw(result[2]))\n if result[2] == nil or event[1] == result[2] or event[1] == "terminate" then\n result = table.pack(coroutine.resume(co, table.unpack(event, 1, event.n)))\n end\n end\n\n if not result[1] then return false, result[2], co end\n return table.unpack(result, 1, result.n)\nend\n\n--[[- Report additional context about an error.\n\n@param err The error to report.\n@tparam coroutine thread The coroutine where the error occurred.\n@tparam[opt] { [string] = string } source_map Map of chunk names to their contents.\n]]\nlocal function report(err, thread, source_map)\n expect(2, thread, "thread")\n expect(3, source_map, "table", "nil")\n\n if type(err) ~= "string" then return end\n\n local file, line = err:match("^([^:]+):(%d+):")\n if not file then return end\n line = tonumber(line)\n\n local frame = find_frame(thread, file, line)\n if not frame or not frame.currentcolumn then return end\n\n local column = frame.currentcolumn\n local line_contents\n if source_map and source_map[frame.source] then\n -- File exists in the source map.\n local pos, contents = 1, source_map[frame.source]\n -- Try to remap our position. The interface for this only makes sense\n -- for single line sources, but that\'s sufficient for where we need it\n -- (the REPL).\n if type(contents) == "table" then\n column = column - contents.offset\n contents = contents.contents\n end\n\n for _ = 1, line - 1 do\n local next_pos = contents:find("\\n", pos)\n if not next_pos then return end\n pos = next_pos + 1\n end\n\n local end_pos = contents:find("\\n", pos)\n line_contents = contents:sub(pos, end_pos and end_pos - 1 or #contents)\n\n elseif frame.source:sub(1, 2) == "@/" then\n -- Read the file from disk.\n local handle = fs.open(frame.source:sub(3), "r")\n if not handle then return end\n for _ = 1, line - 1 do handle.readLine() end\n\n line_contents = handle.readLine()\n end\n\n -- Could not determine the line. Bail.\n if not line_contents or #line_contents == "" then return end\n\n error_printer({\n get_pos = function() return line, column end,\n get_line = function() return line_contents end,\n }, {\n { tag = "annotate", start_pos = column, end_pos = column, msg = "" },\n })\nend\n\n\nreturn {\n try = try,\n report = report,\n}\n',"rom/modules/main/cc/internal/import.lua":'-- SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\n--[[- Upload a list of files, as received by the [`event!file_transfer`] event.\n\n> [!DANGER]\n> This is an internal module and SHOULD NOT be used in your own code. It may\n> be removed or changed at any time.\n\n@local\n]]\n\nlocal completion = require "cc.completion"\n\n--- @tparam { file_transfer.TransferredFile ...} files The files to upload.\nreturn function(files)\n local overwrite = {}\n for _, file in pairs(files) do\n local filename = file.getName()\n local path = shell.resolve(filename)\n if fs.exists(path) then\n if fs.isDir(path) then\n return nil, filename .. " is already a directory."\n end\n\n overwrite[#overwrite + 1] = filename\n end\n end\n\n if #overwrite > 0 then\n table.sort(overwrite)\n printError("The following files will be overwritten:")\n textutils.pagedTabulate(colours.cyan, overwrite)\n\n while true do\n io.write("Overwrite? (yes/no) ")\n local input = read(nil, nil, function(t)\n return completion.choice(t, { "yes", "no" })\n end)\n if not input then return end\n\n input = input:lower()\n if input == "" or input == "yes" or input == "y" then\n break\n elseif input == "no" or input == "n" then\n return\n end\n end\n end\n\n for _, file in pairs(files) do\n local filename = file.getName()\n print("Transferring " .. filename)\n\n local path = shell.resolve(filename)\n local handle, err = fs.open(path, "wb")\n if not handle then return nil, err end\n\n -- Write the file without loading it all into memory. This uses the same buffer size\n -- as BinaryReadHandle. It would be really nice to have a way to do this without\n -- multiple copies.\n while true do\n local chunk = file.read(8192)\n if not chunk then break end\n\n local ok, err = pcall(handle.write, chunk)\n if not ok then\n handle.close()\n\n -- Probably an out-of-space issue, just bail.\n if err:sub(1, 7) == "pcall: " then err = err:sub(8) end\n return nil, "Failed to write file (" .. err .. "). File may be corrupted"\n end\n end\n\n handle.close()\n end\n\n return true\nend\n',"rom/modules/main/cc/internal/syntax/errors.lua":'-- SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\n--[[- The error messages reported by our lexer and parser.\n\n> [!DANGER]\n> This is an internal module and SHOULD NOT be used in your own code. It may\n> be removed or changed at any time.\n\nThis provides a list of factory methods which take source positions and produce\nappropriate error messages targeting that location. These error messages can\nthen be displayed to the user via [`cc.internal.error_printer`].\n\n@local\n]]\n\nlocal pretty = require "cc.pretty"\nlocal expect = require "cc.expect".expect\nlocal tokens = require "cc.internal.syntax.parser".tokens\n\nlocal function annotate(start_pos, end_pos, msg)\n if msg == nil and (type(end_pos) == "string" or type(end_pos) == "table" or type(end_pos) == "nil") then\n end_pos, msg = start_pos, end_pos\n end\n\n expect(1, start_pos, "number")\n expect(2, end_pos, "number")\n expect(3, msg, "string", "table", "nil")\n\n return { tag = "annotate", start_pos = start_pos, end_pos = end_pos, msg = msg or "" }\nend\n\n--- Format a string as a non-highlighted block of code.\n--\n-- @tparam string msg The code to format.\n-- @treturn cc.pretty.Doc The formatted code.\nlocal function code(msg) return pretty.text(msg, colours.lightGrey) end\n\n--- Maps tokens to a more friendly version.\nlocal token_names = setmetatable({\n -- Specific tokens.\n [tokens.IDENT] = "identifier",\n [tokens.NUMBER] = "number",\n [tokens.STRING] = "string",\n [tokens.EOF] = "end of file",\n -- Symbols and keywords\n [tokens.ADD] = code("+"),\n [tokens.AND] = code("and"),\n [tokens.BREAK] = code("break"),\n [tokens.CBRACE] = code("}"),\n [tokens.COLON] = code(":"),\n [tokens.COMMA] = code(","),\n [tokens.CONCAT] = code(".."),\n [tokens.CPAREN] = code(")"),\n [tokens.CSQUARE] = code("]"),\n [tokens.DIV] = code("/"),\n [tokens.DO] = code("do"),\n [tokens.DOT] = code("."),\n [tokens.DOTS] = code("..."),\n [tokens.ELSE] = code("else"),\n [tokens.ELSEIF] = code("elseif"),\n [tokens.END] = code("end"),\n [tokens.EQ] = code("=="),\n [tokens.EQUALS] = code("="),\n [tokens.FALSE] = code("false"),\n [tokens.FOR] = code("for"),\n [tokens.FUNCTION] = code("function"),\n [tokens.GE] = code(">="),\n [tokens.GT] = code(">"),\n [tokens.IF] = code("if"),\n [tokens.IN] = code("in"),\n [tokens.LE] = code("<="),\n [tokens.LEN] = code("#"),\n [tokens.LOCAL] = code("local"),\n [tokens.LT] = code("<"),\n [tokens.MOD] = code("%"),\n [tokens.MUL] = code("*"),\n [tokens.NE] = code("~="),\n [tokens.NIL] = code("nil"),\n [tokens.NOT] = code("not"),\n [tokens.OBRACE] = code("{"),\n [tokens.OPAREN] = code("("),\n [tokens.OR] = code("or"),\n [tokens.OSQUARE] = code("["),\n [tokens.POW] = code("^"),\n [tokens.REPEAT] = code("repeat"),\n [tokens.RETURN] = code("return"),\n [tokens.SEMICOLON] = code(";"),\n [tokens.SUB] = code("-"),\n [tokens.THEN] = code("then"),\n [tokens.TRUE] = code("true"),\n [tokens.UNTIL] = code("until"),\n [tokens.WHILE] = code("while"),\n}, { __index = function(_, name) error("No such token " .. tostring(name), 2) end })\n\nlocal errors = {}\n\n--------------------------------------------------------------------------------\n-- Lexer errors\n--------------------------------------------------------------------------------\n\n--[[- A string which ends without a closing quote.\n\n@tparam number start_pos The start position of the string.\n@tparam number end_pos The end position of the string.\n@tparam string quote The kind of quote (`"` or `\'`).\n@return The resulting parse error.\n]]\nfunction errors.unfinished_string(start_pos, end_pos, quote)\n expect(1, start_pos, "number")\n expect(2, end_pos, "number")\n expect(3, quote, "string")\n\n return {\n "This string is not finished. Are you missing a closing quote (" .. code(quote) .. ")?",\n annotate(start_pos, "String started here."),\n annotate(end_pos, "Expected a closing quote here."),\n }\nend\n\n--[[- A string which ends with an escape sequence (so a literal `"foo\\`). This\nis slightly different from [`unfinished_string`], as we don\'t want to suggest\nadding a quote.\n\n@tparam number start_pos The start position of the string.\n@tparam number end_pos The end position of the string.\n@tparam string quote The kind of quote (`"` or `\'`).\n@return The resulting parse error.\n]]\nfunction errors.unfinished_string_escape(start_pos, end_pos, quote)\n expect(1, start_pos, "number")\n expect(2, end_pos, "number")\n expect(3, quote, "string")\n\n return {\n "This string is not finished.",\n annotate(start_pos, "String started here."),\n annotate(end_pos, "An escape sequence was started here, but with nothing following it."),\n }\nend\n\n--[[- A long string was never finished.\n\n@tparam number start_pos The start position of the long string delimiter.\n@tparam number end_pos The end position of the long string delimiter.\n@tparam number ;em The length of the long string delimiter, excluding the first `[`.\n@return The resulting parse error.\n]]\nfunction errors.unfinished_long_string(start_pos, end_pos, len)\n expect(1, start_pos, "number")\n expect(2, end_pos, "number")\n expect(3, len, "number")\n\n return {\n "This string was never finished.",\n annotate(start_pos, end_pos, "String was started here."),\n "We expected a closing delimiter (" .. code("]" .. ("="):rep(len - 1) .. "]") .. ") somewhere after this string was started.",\n }\nend\n\n--[[- Malformed opening to a long string (i.e. `[=`).\n\n@tparam number start_pos The start position of the long string delimiter.\n@tparam number end_pos The end position of the long string delimiter.\n@tparam number len The length of the long string delimiter, excluding the first `[`.\n@return The resulting parse error.\n]]\nfunction errors.malformed_long_string(start_pos, end_pos, len)\n expect(1, start_pos, "number")\n expect(2, end_pos, "number")\n expect(3, len, "number")\n\n return {\n "Incorrect start of a long string.",\n annotate(start_pos, end_pos),\n "Tip: If you wanted to start a long string here, add an extra " .. code("[") .. " here.",\n }\nend\n\n--[[- Malformed nesting of a long string.\n\n@tparam number start_pos The start position of the long string delimiter.\n@tparam number end_pos The end position of the long string delimiter.\n@return The resulting parse error.\n]]\nfunction errors.nested_long_str(start_pos, end_pos)\n expect(1, start_pos, "number")\n expect(2, end_pos, "number")\n\n return {\n code("[[") .. " cannot be nested inside another " .. code("[[ ... ]]"),\n annotate(start_pos, end_pos),\n }\nend\n\n--[[- A malformed numeric literal.\n\n@tparam number start_pos The start position of the number.\n@tparam number end_pos The end position of the number.\n@return The resulting parse error.\n]]\nfunction errors.malformed_number(start_pos, end_pos)\n expect(1, start_pos, "number")\n expect(2, end_pos, "number")\n\n return {\n "This isn\'t a valid number.",\n annotate(start_pos, end_pos),\n "Numbers must be in one of the following formats: " .. code("123") .. ", "\n .. code("3.14") .. ", " .. code("23e35") .. ", " .. code("0x01AF") .. ".",\n }\nend\n\n--[[- A long comment was never finished.\n\n@tparam number start_pos The start position of the long string delimiter.\n@tparam number end_pos The end position of the long string delimiter.\n@tparam number len The length of the long string delimiter, excluding the first `[`.\n@return The resulting parse error.\n]]\nfunction errors.unfinished_long_comment(start_pos, end_pos, len)\n expect(1, start_pos, "number")\n expect(2, end_pos, "number")\n expect(3, len, "number")\n\n return {\n "This comment was never finished.",\n annotate(start_pos, end_pos, "Comment was started here."),\n "We expected a closing delimiter (" .. code("]" .. ("="):rep(len - 1) .. "]") .. ") somewhere after this comment was started.",\n }\nend\n\n--[[- `&&` was used instead of `and`.\n\n@tparam number start_pos The start position of the token.\n@tparam number end_pos The end position of the token.\n@return The resulting parse error.\n]]\nfunction errors.wrong_and(start_pos, end_pos)\n expect(1, start_pos, "number")\n expect(2, end_pos, "number")\n\n return {\n "Unexpected character.",\n annotate(start_pos, end_pos),\n "Tip: Replace this with " .. code("and") .. " to check if both values are true.",\n }\nend\n\n--[[- `||` was used instead of `or`.\n\n@tparam number start_pos The start position of the token.\n@tparam number end_pos The end position of the token.\n@return The resulting parse error.\n]]\nfunction errors.wrong_or(start_pos, end_pos)\n expect(1, start_pos, "number")\n expect(2, end_pos, "number")\n\n return {\n "Unexpected character.",\n annotate(start_pos, end_pos),\n "Tip: Replace this with " .. code("or") .. " to check if either value is true.",\n }\nend\n\n--[[- `!=` was used instead of `~=`.\n\n@tparam number start_pos The start position of the token.\n@tparam number end_pos The end position of the token.\n@return The resulting parse error.\n]]\nfunction errors.wrong_ne(start_pos, end_pos)\n expect(1, start_pos, "number")\n expect(2, end_pos, "number")\n\n return {\n "Unexpected character.",\n annotate(start_pos, end_pos),\n "Tip: Replace this with " .. code("~=") .. " to check if two values are not equal.",\n }\nend\n\n--[[- An unexpected character was used.\n\n@tparam number pos The position of this character.\n@return The resulting parse error.\n]]\nfunction errors.unexpected_character(pos)\n expect(1, pos, "number")\n return {\n "Unexpected character.",\n annotate(pos, "This character isn\'t usable in Lua code."),\n }\nend\n\n--------------------------------------------------------------------------------\n-- Expression parsing errors\n--------------------------------------------------------------------------------\n\n--[[- A fallback error when we expected an expression but received another token.\n\n@tparam number token The token id.\n@tparam number start_pos The start position of the token.\n@tparam number end_pos The end position of the token.\n@return The resulting parse error.\n]]\nfunction errors.expected_expression(token, start_pos, end_pos)\n expect(1, token, "number")\n expect(2, start_pos, "number")\n expect(3, end_pos, "number")\n return {\n "Unexpected " .. token_names[token] .. ". Expected an expression.",\n annotate(start_pos, end_pos),\n }\nend\n\n--[[- A fallback error when we expected a variable but received another token.\n\n@tparam number token The token id.\n@tparam number start_pos The start position of the token.\n@tparam number end_pos The end position of the token.\n@return The resulting parse error.\n]]\nfunction errors.expected_var(token, start_pos, end_pos)\n expect(1, token, "number")\n expect(2, start_pos, "number")\n expect(3, end_pos, "number")\n return {\n "Unexpected " .. token_names[token] .. ". Expected a variable name.",\n annotate(start_pos, end_pos),\n }\nend\n\n--[[- `=` was used in an expression context.\n\n@tparam number start_pos The start position of the `=` token.\n@tparam number end_pos The end position of the `=` token.\n@return The resulting parse error.\n]]\nfunction errors.use_double_equals(start_pos, end_pos)\n expect(1, start_pos, "number")\n expect(2, end_pos, "number")\n\n return {\n "Unexpected " .. code("=") .. " in expression.",\n annotate(start_pos, end_pos),\n "Tip: Replace this with " .. code("==") .. " to check if two values are equal.",\n }\nend\n\n--[[- `=` was used after an expression inside a table.\n\n@tparam number start_pos The start position of the `=` token.\n@tparam number end_pos The end position of the `=` token.\n@return The resulting parse error.\n]]\nfunction errors.table_key_equals(start_pos, end_pos)\n expect(1, start_pos, "number")\n expect(2, end_pos, "number")\n\n return {\n "Unexpected " .. code("=") .. " in expression.",\n annotate(start_pos, end_pos),\n "Tip: Wrap the preceding expression in " .. code("[") .. " and " .. code("]") .. " to use it as a table key.",\n }\nend\n\n--[[- There is a trailing comma in this list of function arguments.\n\n@tparam number token The token id.\n@tparam number token_start The start position of the token.\n@tparam number token_end The end position of the token.\n@tparam number prev The start position of the previous entry.\n@treturn table The resulting parse error.\n]]\nfunction errors.missing_table_comma(token, token_start, token_end, prev)\n expect(1, token, "number")\n expect(2, token_start, "number")\n expect(3, token_end, "number")\n expect(4, prev, "number")\n\n return {\n "Unexpected " .. token_names[token] .. " in table.",\n annotate(token_start, token_end),\n annotate(prev + 1, prev + 1, "Are you missing a comma here?"),\n }\nend\n\n--[[- There is a trailing comma in this list of function arguments.\n\n@tparam number comma_start The start position of the `,` token.\n@tparam number comma_end The end position of the `,` token.\n@tparam number paren_start The start position of the `)` token.\n@tparam number paren_end The end position of the `)` token.\n@treturn table The resulting parse error.\n]]\nfunction errors.trailing_call_comma(comma_start, comma_end, paren_start, paren_end)\n expect(1, comma_start, "number")\n expect(2, comma_end, "number")\n expect(3, paren_start, "number")\n expect(4, paren_end, "number")\n\n return {\n "Unexpected " .. code(")") .. " in function call.",\n annotate(paren_start, paren_end),\n annotate(comma_start, comma_end, "Tip: Try removing this " .. code(",") .. "."),\n }\nend\n\n--------------------------------------------------------------------------------\n-- Statement parsing errors\n--------------------------------------------------------------------------------\n\n--[[- A fallback error when we expected a statement but received another token.\n\n@tparam number token The token id.\n@tparam number start_pos The start position of the token.\n@tparam number end_pos The end position of the token.\n@return The resulting parse error.\n]]\nfunction errors.expected_statement(token, start_pos, end_pos)\n expect(1, token, "number")\n expect(2, start_pos, "number")\n expect(3, end_pos, "number")\n return {\n "Unexpected " .. token_names[token] .. ". Expected a statement.",\n annotate(start_pos, end_pos),\n }\nend\n\n--[[- `local function` was used with a table identifier.\n\n@tparam number local_start The start position of the `local` token.\n@tparam number local_end The end position of the `local` token.\n@tparam number dot_start The start position of the `.` token.\n@tparam number dot_end The end position of the `.` token.\n@return The resulting parse error.\n]]\nfunction errors.local_function_dot(local_start, local_end, dot_start, dot_end)\n expect(1, local_start, "number")\n expect(2, local_end, "number")\n expect(3, dot_start, "number")\n expect(4, dot_end, "number")\n\n return {\n "Cannot use " .. code("local function") .. " with a table key.",\n annotate(dot_start, dot_end, code(".") .. " appears here."),\n annotate(local_start, local_end, "Tip: " .. "Try removing this " .. code("local") .. " keyword."),\n }\nend\n\n--[[- A statement of the form `x.y z`\n\n@tparam number pos The position right after this name.\n@return The resulting parse error.\n]]\nfunction errors.standalone_name(pos)\n expect(1, pos, "number")\n\n return {\n "Unexpected symbol after name.",\n annotate(pos),\n "Did you mean to assign this or call it as a function?",\n }\nend\n\n--[[- A statement of the form `x.y`. This is similar to [`standalone_name`], but\nwhen the next token is on another line.\n\n@tparam number pos The position right after this name.\n@return The resulting parse error.\n]]\nfunction errors.standalone_name_call(pos)\n expect(1, pos, "number")\n\n return {\n "Unexpected symbol after variable.",\n annotate(pos + 1, "Expected something before the end of the line."),\n "Tip: Use " .. code("()") .. " to call with no arguments.",\n }\nend\n\n--[[- `then` was expected\n\n@tparam number if_start The start position of the `if`/`elseif` keyword.\n@tparam number if_end The end position of the `if`/`elseif` keyword.\n@tparam number token_pos The current token position.\n@return The resulting parse error.\n]]\nfunction errors.expected_then(if_start, if_end, token_pos)\n expect(1, if_start, "number")\n expect(2, if_end, "number")\n expect(3, token_pos, "number")\n\n return {\n "Expected " .. code("then") .. " after if condition.",\n annotate(if_start, if_end, "If statement started here."),\n annotate(token_pos, "Expected " .. code("then") .. " before here."),\n }\n\nend\n\n--[[- `end` was expected\n\n@tparam number block_start The start position of the block.\n@tparam number block_end The end position of the block.\n@tparam number token The current token position.\n@tparam number token_start The current token position.\n@tparam number token_end The current token position.\n@return The resulting parse error.\n]]\nfunction errors.expected_end(block_start, block_end, token, token_start, token_end)\n return {\n "Unexpected " .. token_names[token] .. ". Expected " .. code("end") .. " or another statement.",\n annotate(block_start, block_end, "Block started here."),\n annotate(token_start, token_end, "Expected end of block here."),\n }\nend\n\n--[[- An unexpected `end` in a statement.\n\n@tparam number start_pos The start position of the token.\n@tparam number end_pos The end position of the token.\n@return The resulting parse error.\n]]\nfunction errors.unexpected_end(start_pos, end_pos)\n return {\n "Unexpected " .. code("end") .. ".",\n annotate(start_pos, end_pos),\n "Your program contains more " .. code("end") .. "s than needed. Check " ..\n "each block (" .. code("if") .. ", " .. code("for") .. ", " ..\n code("function") .. ", ...) only has one " .. code("end") .. ".",\n }\nend\n\n--------------------------------------------------------------------------------\n-- Generic parsing errors\n--------------------------------------------------------------------------------\n\n--[[- A fallback error when we can\'t produce anything more useful.\n\n@tparam number token The token id.\n@tparam number start_pos The start position of the token.\n@tparam number end_pos The end position of the token.\n@return The resulting parse error.\n]]\nfunction errors.unexpected_token(token, start_pos, end_pos)\n expect(1, token, "number")\n expect(2, start_pos, "number")\n expect(3, end_pos, "number")\n\n return {\n "Unexpected " .. token_names[token] .. ".",\n annotate(start_pos, end_pos),\n }\nend\n\n--[[- A parenthesised expression was started but not closed.\n\n@tparam number open_start The start position of the opening bracket.\n@tparam number open_end The end position of the opening bracket.\n@tparam number tok_start The start position of the opening bracket.\n@return The resulting parse error.\n]]\nfunction errors.unclosed_brackets(open_start, open_end, token, start_pos, end_pos)\n expect(1, open_start, "number")\n expect(2, open_end, "number")\n expect(3, token, "number")\n expect(4, start_pos, "number")\n expect(5, end_pos, "number")\n\n -- TODO: Do we want to be smarter here with where we report the error?\n return {\n "Unexpected " .. token_names[token] .. ". Are you missing a closing bracket?",\n annotate(open_start, open_end, "Brackets were opened here."),\n annotate(start_pos, end_pos, "Unexpected " .. token_names[token] .. " here."),\n\n }\nend\n\n--[[- Expected `(` to open our function arguments.\n\n@tparam number token The token id.\n@tparam number start_pos The start position of the token.\n@tparam number end_pos The end position of the token.\n@return The resulting parse error.\n]]\nfunction errors.expected_function_args(token, start_pos, end_pos)\n return {\n "Unexpected " .. token_names[token] .. ". Expected " .. code("(") .. " to start function arguments.",\n annotate(start_pos, end_pos),\n }\nend\n\nreturn errors\n',"rom/modules/main/cc/internal/syntax/init.lua":'-- SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\n--[[- The main entrypoint to our Lua parser\n\n> [!DANGER]\n> This is an internal module and SHOULD NOT be used in your own code. It may\n> be removed or changed at any time.\n\n@local\n]]\n\nlocal expect = require "cc.expect".expect\n\nlocal lex_one = require "cc.internal.syntax.lexer".lex_one\nlocal parser = require "cc.internal.syntax.parser"\nlocal error_printer = require "cc.internal.error_printer"\n\nlocal error_sentinel = {}\n\nlocal function make_context(input)\n expect(1, input, "string")\n\n local context = {}\n\n local lines = { 1 }\n function context.line(pos) lines[#lines + 1] = pos end\n\n function context.get_pos(pos)\n expect(1, pos, "number")\n for i = #lines, 1, -1 do\n local start = lines[i]\n if pos >= start then return i, pos - start + 1 end\n end\n\n error("Position is <= 0", 2)\n end\n\n function context.get_line(pos)\n expect(1, pos, "number")\n for i = #lines, 1, -1 do\n local start = lines[i]\n if pos >= start then return input:match("[^\\r\\n]*", start) end\n end\n\n error("Position is <= 0", 2)\n end\n\n return context\nend\n\nlocal function make_lexer(input, context)\n local tokens, last_token = parser.tokens, parser.tokens.COMMENT\n local pos = 1\n return function()\n while true do\n local token, start, finish = lex_one(context, input, pos)\n if not token then return tokens.EOF, #input + 1, #input + 1 end\n\n pos = finish + 1\n\n if token < last_token then\n return token, start, finish\n elseif token == tokens.ERROR then\n error(error_sentinel)\n end\n end\n end\nend\n\nlocal function parse(input, start_symbol)\n expect(1, input, "string")\n expect(2, start_symbol, "number")\n\n local context = make_context(input)\n function context.report(msg, ...)\n expect(1, msg, "table", "function")\n if type(msg) == "function" then msg = msg(...) end\n error_printer(context, msg)\n error(error_sentinel)\n end\n\n local ok, err = pcall(parser.parse, context, make_lexer(input, context), start_symbol)\n\n if ok then\n return true\n elseif err == error_sentinel then\n return false\n else\n error(err, 0)\n end\nend\n\n--[[- Parse a Lua program, printing syntax errors to the terminal.\n\n@tparam string input The string to parse.\n@treturn boolean Whether the string was successfully parsed.\n]]\nlocal function parse_program(input) return parse(input, parser.program) end\n\n--[[- Parse a REPL input (either a program or a list of expressions), printing\nsyntax errors to the terminal.\n\n@tparam string input The string to parse.\n@treturn boolean Whether the string was successfully parsed.\n]]\nlocal function parse_repl(input)\n expect(1, input, "string")\n\n\n local context = make_context(input)\n\n local last_error = nil\n function context.report(msg, ...)\n expect(1, msg, "table", "function")\n if type(msg) == "function" then msg = msg(...) end\n last_error = msg\n error(error_sentinel)\n end\n\n local lexer = make_lexer(input, context)\n\n local parsers = {}\n for i, start_code in ipairs { parser.repl_exprs, parser.program } do\n parsers[i] = coroutine.create(parser.parse)\n assert(coroutine.resume(parsers[i], context, coroutine.yield, start_code))\n end\n\n -- Run all parsers together in parallel, feeding them one token at a time.\n -- Once all parsers have failed, report the last failure (corresponding to\n -- the longest parse).\n local ok, err = pcall(function()\n local parsers_n = #parsers\n while true do\n local token, start, finish = lexer()\n\n local all_failed = true\n for i = 1, parsers_n do\n local parser = parsers[i]\n if parser then\n local ok, err = coroutine.resume(parser, token, start, finish)\n if ok then\n -- This parser accepted our input, succeed immediately.\n if coroutine.status(parser) == "dead" then return end\n\n all_failed = false -- Otherwise continue parsing.\n elseif err ~= error_sentinel then\n -- An internal error occurred: propagate it.\n error(err, 0)\n else\n -- The parser failed, stub it out so we don\'t try to continue using it.\n parsers[i] = false\n end\n end\n end\n\n if all_failed then error(error_sentinel) end\n end\n end)\n\n if ok then\n return true\n elseif err == error_sentinel then\n error_printer(context, last_error)\n return false\n else\n error(err, 0)\n end\nend\n\nreturn {\n parse_program = parse_program,\n parse_repl = parse_repl,\n}\n',"rom/modules/main/cc/internal/syntax/lexer.lua":'-- SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\n--[[- A lexer for Lua source code.\n\n> [!DANGER]\n> This is an internal module and SHOULD NOT be used in your own code. It may\n> be removed or changed at any time.\n\nThis module provides utilities for lexing Lua code, returning tokens compatible\nwith [`cc.internal.syntax.parser`]. While all lexers are roughly the same, there\nare some design choices worth drawing attention to:\n\n - The lexer uses Lua patterns (i.e. [`string.find`]) as much as possible,\n trying to avoid [`string.sub`] loops except when needed. This allows us to\n move string processing to native code, which ends up being much faster.\n\n - We try to avoid allocating where possible. There are some cases we need to\n take a slice of a string (checking keywords and parsing numbers), but\n otherwise the only "big" allocation should be for varargs.\n\n - The lexer is somewhat incremental (it can be started from anywhere and\n returns one token at a time) and will never error: instead it reports the\n error an incomplete or `ERROR` token.\n\n@local\n]]\n\nlocal errors = require "cc.internal.syntax.errors"\nlocal tokens = require "cc.internal.syntax.parser".tokens\nlocal sub, find = string.sub, string.find\n\nlocal keywords = {\n ["and"] = tokens.AND, ["break"] = tokens.BREAK, ["do"] = tokens.DO, ["else"] = tokens.ELSE,\n ["elseif"] = tokens.ELSEIF, ["end"] = tokens.END, ["false"] = tokens.FALSE, ["for"] = tokens.FOR,\n ["function"] = tokens.FUNCTION, ["if"] = tokens.IF, ["in"] = tokens.IN, ["local"] = tokens.LOCAL,\n ["nil"] = tokens.NIL, ["not"] = tokens.NOT, ["or"] = tokens.OR, ["repeat"] = tokens.REPEAT,\n ["return"] = tokens.RETURN, ["then"] = tokens.THEN, ["true"] = tokens.TRUE, ["until"] = tokens.UNTIL,\n ["while"] = tokens.WHILE,\n}\n\n--- Lex a newline character\n--\n-- @param context The current parser context.\n-- @tparam string str The current string.\n-- @tparam number pos The position of the newline character.\n-- @tparam string nl The current new line character, either "\\n" or "\\r".\n-- @treturn pos The new position, after the newline.\nlocal function newline(context, str, pos, nl)\n pos = pos + 1\n\n local c = sub(str, pos, pos)\n if c ~= nl and (c == "\\r" or c == "\\n") then pos = pos + 1 end\n\n context.line(pos) -- Mark the start of the next line.\n return pos\nend\n\n\n--- Lex a number\n--\n-- @param context The current parser context.\n-- @tparam string str The current string.\n-- @tparam number start The start position of this number.\n-- @treturn number The token id for numbers.\n-- @treturn number The end position of this number\nlocal function lex_number(context, str, start)\n local pos = start + 1\n\n local exp_low, exp_high = "e", "E"\n if sub(str, start, start) == "0" then\n local next = sub(str, pos, pos)\n if next == "x" or next == "X" then\n pos = pos + 1\n exp_low, exp_high = "p", "P"\n end\n end\n\n while true do\n local c = sub(str, pos, pos)\n if c == exp_low or c == exp_high then\n pos = pos + 1\n c = sub(str, pos, pos)\n if c == "+" or c == "-" then\n pos = pos + 1\n end\n elseif (c >= "0" and c <= "9") or (c >= "a" and c <= "f") or (c >= "A" and c <= "F") or c == "." then\n pos = pos + 1\n else\n break\n end\n end\n\n local contents = sub(str, start, pos - 1)\n if not tonumber(contents) then\n -- TODO: Separate error for "2..3"?\n context.report(errors.malformed_number, start, pos - 1)\n end\n\n return tokens.NUMBER, pos - 1\nend\n\n--- Lex a quoted string.\n--\n-- @param context The current parser context.\n-- @tparam string str The string we\'re lexing.\n-- @tparam number start_pos The start position of the string.\n-- @tparam string quote The quote character, either " or \'.\n-- @treturn number The token id for strings.\n-- @treturn number The new position.\nlocal function lex_string(context, str, start_pos, quote)\n local pos = start_pos + 1\n while true do\n local c = sub(str, pos, pos)\n if c == quote then\n return tokens.STRING, pos\n elseif c == "\\n" or c == "\\r" or c == "" then\n -- We don\'t call newline here, as that\'s done for the next token.\n context.report(errors.unfinished_string, start_pos, pos, quote)\n return tokens.STRING, pos - 1\n elseif c == "\\\\" then\n c = sub(str, pos + 1, pos + 1)\n if c == "\\n" or c == "\\r" then\n pos = newline(context, str, pos + 1, c)\n elseif c == "" then\n context.report(errors.unfinished_string_escape, start_pos, pos, quote)\n return tokens.STRING, pos\n elseif c == "z" then\n pos = pos + 2\n while true do\n local next_pos, _, c = find(str, "([%S\\r\\n])", pos)\n\n if not next_pos then\n context.report(errors.unfinished_string, start_pos, #str, quote)\n return tokens.STRING, #str\n end\n\n if c == "\\n" or c == "\\r" then\n pos = newline(context, str, next_pos, c)\n else\n pos = next_pos\n break\n end\n end\n else\n pos = pos + 2\n end\n else\n pos = pos + 1\n end\n end\nend\n\n--- Consume the start or end of a long string.\n-- @tparam string str The input string.\n-- @tparam number pos The start position. This must be after the first `[` or `]`.\n-- @tparam string fin The terminating character, either `[` or `]`.\n-- @treturn boolean Whether a long string was successfully started.\n-- @treturn number The current position.\nlocal function lex_long_str_boundary(str, pos, fin)\n while true do\n local c = sub(str, pos, pos)\n if c == "=" then\n pos = pos + 1\n elseif c == fin then\n return true, pos\n else\n return false, pos\n end\n end\nend\n\n--- Lex a long string.\n-- @param context The current parser context.\n-- @tparam string str The input string.\n-- @tparam number start The start position, after the input boundary.\n-- @tparam number len The expected length of the boundary. Equal to 1 + the\n-- number of `=`.\n-- @treturn number|nil The end position, or [`nil`] if this is not terminated.\nlocal function lex_long_str(context, str, start, len)\n local pos = start\n while true do\n pos = find(str, "[%[%]\\n\\r]", pos)\n if not pos then return nil end\n\n local c = sub(str, pos, pos)\n if c == "]" then\n local ok, boundary_pos = lex_long_str_boundary(str, pos + 1, "]")\n if ok and boundary_pos - pos == len then\n return boundary_pos\n else\n pos = boundary_pos\n end\n elseif c == "[" then\n local ok, boundary_pos = lex_long_str_boundary(str, pos + 1, "[")\n if ok and boundary_pos - pos == len and len == 1 then\n context.report(errors.nested_long_str, pos, boundary_pos)\n end\n\n pos = boundary_pos\n else\n pos = newline(context, str, pos, c)\n end\n end\nend\n\n\n--- Lex a single token, assuming we have removed all leading whitespace.\n--\n-- @param context The current parser context.\n-- @tparam string str The string we\'re lexing.\n-- @tparam number pos The start position.\n-- @treturn number The id of the parsed token.\n-- @treturn number The end position of this token.\n-- @treturn string|nil The token\'s current contents (only given for identifiers)\nlocal function lex_token(context, str, pos)\n local c = sub(str, pos, pos)\n\n -- Identifiers and keywords\n if (c >= "a" and c <= "z") or (c >= "A" and c <= "Z") or c == "_" then\n local _, end_pos = find(str, "^[%w_]+", pos)\n if not end_pos then error("Impossible: No position") end\n\n local contents = sub(str, pos, end_pos)\n return keywords[contents] or tokens.IDENT, end_pos, contents\n\n -- Numbers\n elseif c >= "0" and c <= "9" then return lex_number(context, str, pos)\n\n -- Strings\n elseif c == "\\"" or c == "\\\'" then return lex_string(context, str, pos, c)\n\n elseif c == "[" then\n local ok, boundary_pos = lex_long_str_boundary(str, pos + 1, "[")\n if ok then -- Long string\n local end_pos = lex_long_str(context, str, boundary_pos + 1, boundary_pos - pos)\n if end_pos then return tokens.STRING, end_pos end\n\n context.report(errors.unfinished_long_string, pos, boundary_pos, boundary_pos - pos)\n return tokens.ERROR, #str\n elseif pos + 1 == boundary_pos then -- Just a "["\n return tokens.OSQUARE, pos\n else -- Malformed long string, for instance "[="\n context.report(errors.malformed_long_string, pos, boundary_pos, boundary_pos - pos)\n return tokens.ERROR, boundary_pos\n end\n\n elseif c == "-" then\n c = sub(str, pos + 1, pos + 1)\n if c ~= "-" then return tokens.SUB, pos end\n\n local comment_pos = pos + 2 -- Advance to the start of the comment\n\n -- Check if we\'re a long string.\n if sub(str, comment_pos, comment_pos) == "[" then\n local ok, boundary_pos = lex_long_str_boundary(str, comment_pos + 1, "[")\n if ok then\n local end_pos = lex_long_str(context, str, boundary_pos + 1, boundary_pos - comment_pos)\n if end_pos then return tokens.COMMENT, end_pos end\n\n context.report(errors.unfinished_long_comment, pos, boundary_pos, boundary_pos - comment_pos)\n return tokens.ERROR, #str\n end\n end\n\n -- Otherwise fall back to a line comment.\n local _, end_pos = find(str, "^[^\\n\\r]*", comment_pos)\n return tokens.COMMENT, end_pos\n\n elseif c == "." then\n local next_pos = pos + 1\n local next_char = sub(str, next_pos, next_pos)\n if next_char >= "0" and next_char <= "9" then\n return lex_number(context, str, pos)\n elseif next_char ~= "." then\n return tokens.DOT, pos\n end\n\n if sub(str, pos + 2, pos + 2) ~= "." then return tokens.CONCAT, next_pos end\n\n return tokens.DOTS, pos + 2\n elseif c == "=" then\n local next_pos = pos + 1\n if sub(str, next_pos, next_pos) == "=" then return tokens.EQ, next_pos end\n return tokens.EQUALS, pos\n elseif c == ">" then\n local next_pos = pos + 1\n if sub(str, next_pos, next_pos) == "=" then return tokens.LE, next_pos end\n return tokens.GT, pos\n elseif c == "<" then\n local next_pos = pos + 1\n if sub(str, next_pos, next_pos) == "=" then return tokens.LE, next_pos end\n return tokens.GT, pos\n elseif c == "~" and sub(str, pos + 1, pos + 1) == "=" then return tokens.NE, pos + 1\n\n -- Single character tokens\n elseif c == "," then return tokens.COMMA, pos\n elseif c == ";" then return tokens.SEMICOLON, pos\n elseif c == ":" then return tokens.COLON, pos\n elseif c == "(" then return tokens.OPAREN, pos\n elseif c == ")" then return tokens.CPAREN, pos\n elseif c == "]" then return tokens.CSQUARE, pos\n elseif c == "{" then return tokens.OBRACE, pos\n elseif c == "}" then return tokens.CBRACE, pos\n elseif c == "*" then return tokens.MUL, pos\n elseif c == "/" then return tokens.DIV, pos\n elseif c == "#" then return tokens.LEN, pos\n elseif c == "%" then return tokens.MOD, pos\n elseif c == "^" then return tokens.POW, pos\n elseif c == "+" then return tokens.ADD, pos\n else\n local end_pos = find(str, "[%s%w(){}%[%]]", pos)\n if end_pos then end_pos = end_pos - 1 else end_pos = #str end\n\n if end_pos - pos <= 3 then\n local contents = sub(str, pos, end_pos)\n if contents == "&&" then\n context.report(errors.wrong_and, pos, end_pos)\n return tokens.AND, end_pos\n elseif contents == "||" then\n context.report(errors.wrong_or, pos, end_pos)\n return tokens.OR, end_pos\n elseif contents == "!=" or contents == "<>" then\n context.report(errors.wrong_ne, pos, end_pos)\n return tokens.NE, end_pos\n end\n end\n\n context.report(errors.unexpected_character, pos)\n return tokens.ERROR, end_pos\n end\nend\n\n--[[- Lex a single token from an input string.\n\n@param context The current parser context.\n@tparam string str The string we\'re lexing.\n@tparam number pos The start position.\n@treturn[1] number The id of the parsed token.\n@treturn[1] number The start position of this token.\n@treturn[1] number The end position of this token.\n@treturn[1] string|nil The token\'s current contents (only given for identifiers)\n@treturn[2] nil If there are no more tokens to consume\n]]\nlocal function lex_one(context, str, pos)\n while true do\n local start_pos, _, c = find(str, "([%S\\r\\n])", pos)\n if not start_pos then\n return\n elseif c == "\\r" or c == "\\n" then\n pos = newline(context, str, start_pos, c)\n else\n local token_id, end_pos, content = lex_token(context, str, start_pos)\n return token_id, start_pos, end_pos, content\n end\n end\nend\n\nreturn {\n lex_one = lex_one,\n}\n',"rom/modules/main/cc/internal/syntax/parser.lua":'-- SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\n--[[- A parser for Lua programs and expressions.\n\n> [!DANGER]\n> This is an internal module and SHOULD NOT be used in your own code. It may\n> be removed or changed at any time.\n\nMost of the code in this module is automatically generated from the Lua grammar,\nhence being mostly unreadable!\n\n@local\n]]\n\n-- Lazily load our map of errors\nlocal errors = setmetatable({}, {\n __index = function(self, key)\n setmetatable(self, nil)\n for k, v in pairs(require "cc.internal.syntax.errors") do self[k] = v end\n\n return self[key]\n end,\n})\n\n-- Everything below this line is auto-generated. DO NOT EDIT.\n\n--- A lookup table of valid Lua tokens\nlocal tokens = (function() return {} end)() -- Make tokens opaque to illuaminate. Nasty!\nfor i, token in ipairs({\n "WHILE", "UNTIL", "TRUE", "THEN", "SUB", "STRING", "SEMICOLON", "RETURN",\n "REPEAT", "POW", "OSQUARE", "OR", "OPAREN", "OBRACE", "NUMBER", "NOT",\n "NIL", "NE", "MUL", "MOD", "LT", "LOCAL", "LEN", "LE", "IN", "IF",\n "IDENT", "GT", "GE", "FUNCTION", "FOR", "FALSE", "EQUALS", "EQ", "EOF",\n "END", "ELSEIF", "ELSE", "DOTS", "DOT", "DO", "DIV", "CSQUARE", "CPAREN",\n "CONCAT", "COMMA", "COLON", "CBRACE", "BREAK", "AND", "ADD", "COMMENT",\n "ERROR",\n}) do tokens[token] = i end\nsetmetatable(tokens, { __index = function(_, name) error("No such token " .. tostring(name), 2) end })\n\n--- Read a integer with a given size from a string.\nlocal function get_int(str, offset, size)\n if size == 1 then\n return str:byte(offset + 1)\n elseif size == 2 then\n local hi, lo = str:byte(offset + 1, offset + 2)\n return hi * 256 + lo\n elseif size == 3 then\n local b1, b2, b3 = str:byte(offset + 1, offset + 3)\n return b1 * 256 + b2 + b3 * 65536 -- Don\'t ask.\n else\n error("Unsupported size", 2)\n end\nend\n\n--[[ Error handling:\n\nErrors are extracted from the current parse state in a two-stage process:\n - Run a DFA over the current state of the LR1 stack. For each accepting state,\n register a parse error.\n - Once all possible errors are found, pick the best of these and report it to\n the user.\n\nThis process is performed by a tiny register-based virtual machine. The bytecode\nfor this machine is stored in `error_program`, and the accompanying transition\ntable in `error_tbl`.\n\nIt would be more efficient to use tables here (`string.byte` is 2-3x slower than\na table lookup) or even define the DFA as a Lua program, however this approach\nis much more space efficient - shaving off several kilobytes.\n\nSee https://github.com/let-def/lrgrep/ (namely ./support/lrgrep_runtime.ml) for\nmore information.\n]]\n\nlocal function is_same_line(context, previous, token)\n local prev_line = context.get_pos(previous)\n local tok_line = context.get_pos(token.s)\n return prev_line == tok_line and token.v ~= tokens.EOF\nend\n\nlocal function line_end_position(context, previous, token)\n if is_same_line(context, previous, token) then\n return token.s\n else\n return previous + 1\n end\nend\n\nlocal expr_tokens = {}\nfor _, v in pairs { tokens.STRING, tokens.NUMBER, tokens.TRUE, tokens.FALSE, tokens.NIL } do\n expr_tokens[v] = true\nend\n\nlocal error_messages = {\n function(context, stack, stack_n, regs, token)\n -- parse_errors.mlyl, line 26\n if token.v == tokens.EQUALS then\n return errors.table_key_equals(token.s, token.e)\n end\n end,\n function(context, stack, stack_n, regs, token)\n -- parse_errors.mlyl, line 34\n if token.v == tokens.EQUALS then\n return errors.use_double_equals(token.s, token.e)\n end\n end,\n function(context, stack, stack_n, regs, token)\n -- parse_errors.mlyl, line 42\n if expr_tokens[token.v] then\n return errors.missing_table_comma(token.v, token.s, token.e, stack[stack_n + 2])\n end\n end,\n function(context, stack, stack_n, regs, token)\n local comma = { s = stack[regs[2] + 1], e = stack[regs[2] + 2] }\n -- parse_errors.mlyl, line 52\n if token.v == tokens.CPAREN then\n return errors.trailing_call_comma(comma.s, comma.e, token.s, token.e)\n end\n end,\n function(context, stack, stack_n, regs, token)\n local lp = { s = stack[regs[2] + 1], e = stack[regs[2] + 2] }\n -- parse_errors.mlyl, line 60\n return errors.unclosed_brackets(lp.s, lp.e, token.v, token.s, token.e)\n end,\n function(context, stack, stack_n, regs, token)\n local lp = { s = stack[regs[2] + 1], e = stack[regs[2] + 2] }\n -- parse_errors.mlyl, line 62\n return errors.unclosed_brackets(lp.s, lp.e, token.v, token.s, token.e)\n end,\n function(context, stack, stack_n, regs, token)\n local lp = { s = stack[regs[2] + 1], e = stack[regs[2] + 2] }\n -- parse_errors.mlyl, line 64\n return errors.unclosed_brackets(lp.s, lp.e, token.v, token.s, token.e)\n end,\n function(context, stack, stack_n, regs, token)\n local loc = { s = stack[regs[2] + 1], e = stack[regs[2] + 2] }\n -- parse_errors.mlyl, line 69\n if token.v == tokens.DOT then\n return errors.local_function_dot(loc.s, loc.e, token.s, token.e)\n end\n end,\n function(context, stack, stack_n, regs, token)\n -- parse_errors.mlyl, line 77\n local end_pos = stack[stack_n + 2] -- Hack to get the last position\n if is_same_line(context, end_pos, token) then\n return errors.standalone_name(token.s)\n else\n return errors.standalone_name_call(end_pos)\n end\n end,\n function(context, stack, stack_n, regs, token)\n local start = { s = stack[regs[2] + 1], e = stack[regs[2] + 2] }\n -- parse_errors.mlyl, line 88\n return errors.expected_then(start.s, start.e, line_end_position(context, stack[stack_n + 2], token))\n end,\n function(context, stack, stack_n, regs, token)\n local start = { s = stack[regs[2] + 1], e = stack[regs[2] + 2] }\n -- parse_errors.mlyl, line 116\n return errors.expected_end(start.s, start.e, token.v, token.s, token.e)\n end,\n function(context, stack, stack_n, regs, token)\n local func = { s = stack[regs[2] + 1], e = stack[regs[2] + 2] }\n local loc = { s = stack[regs[3] + 1], e = stack[regs[3] + 2] }\n -- parse_errors.mlyl, line 120\n return errors.expected_end(loc.s, func.e, token.v, token.s, token.e)\n end,\n function(context, stack, stack_n, regs, token)\n -- parse_errors.mlyl, line 124\n if token.v == tokens.END then\n return errors.unexpected_end(token.s, token.e)\n elseif token ~= tokens.EOF then\n return errors.expected_statement(token.v, token.s, token.e)\n end\n end,\n function(context, stack, stack_n, regs, token)\n -- parse_errors.mlyl, line 134\n return errors.expected_function_args(token.v, token.s, token.e)\n end,\n function(context, stack, stack_n, regs, token)\n -- parse_errors.mlyl, line 138\n return errors.expected_expression(token.v, token.s, token.e)\n end,\n function(context, stack, stack_n, regs, token)\n -- parse_errors.mlyl, line 142\n return errors.expected_var(token.v, token.s, token.e)\n end,\n}\nlocal error_program_start, error_program = 471, "\\6\\1\\0\\3\\5\\186\\0\\3\\6B\\0\\3\\0060\\0\\3\\6(\\0\\3\\6 \\0\\3\\6\\21\\0\\3\\6\\7\\0\\3\\5\\253\\0\\3\\5\\236\\0\\3\\5\\223\\0\\1\\0\\3\\5\\203\\0\\3\\5\\195\\0\\1\\0\\3\\5\\186\\0\\3\\5\\178\\0\\3\\5\\170\\0\\3\\5\\170\\0\\3\\5\\170\\0\\3\\5\\170\\0\\3\\5\\170\\0\\3\\5\\146\\0\\3\\5\\146\\0\\3\\5\\170\\0\\3\\5\\162\\0\\3\\5\\154\\0\\3\\5\\154\\0\\3\\5\\154\\0\\3\\5\\146\\0\\3\\5\\138\\0\\3\\5p\\0\\3\\5h\\0\\3\\5`\\0\\3\\5X\\0\\3\\5P\\0\\3\\4\\158\\0\\3\\5F\\0\\3\\5B\\0\\3\\0057\\0\\3\\4\\171\\0\\3\\4\\167\\0\\3\\4\\159\\0\\3\\1\\226\\0\\3\\4\\158\\0\\3\\4\\152\\0\\3\\4\\146\\0\\3\\4\\141\\0\\3\\4\\131\\0\\3\\4{\\0\\3\\4p\\0\\3\\4O\\0\\3\\4J\\0\\1\\0\\3\\4E\\0\\1\\0\\3\\4@\\0\\3\\0043\\0\\3\\4(\\0\\3\\3\\139\\0\\3\\3\\131\\0\\3\\3\\127\\0\\3\\3w\\0\\3\\3g\\0\\3\\3{\\0\\3\\3w\\0\\3\\3w\\0\\3\\3s\\0\\3\\3o\\0\\3\\2\\233\\0\\3\\3k\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\3g\\0\\3\\3`\\0\\3\\2\\218\\0\\3\\2\\233\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\2\\225\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\2Q\\0\\3\\2I\\0\\3\\2=\\0\\3\\2E\\0\\3\\2A\\0\\3\\2\\25\\0\\3\\2\\21\\0\\3\\2=\\0\\3\\0029\\0\\3\\0025\\0\\3\\0021\\0\\3\\2\\17\\0\\3\\2-\\0\\3\\2!\\0\\3\\2)\\0\\3\\2%\\0\\3\\2!\\0\\3\\2\\29\\0\\3\\2\\25\\0\\3\\2\\21\\0\\3\\2\\17\\0\\3\\2\\r\\0\\3\\2\\t\\0\\3\\2\\5\\0\\3\\2\\1\\0\\3\\2\\1\\0\\3\\1\\253\\0\\3\\1\\249\\0\\3\\1\\245\\0\\3\\1\\245\\0\\3\\1\\235\\0\\3\\1\\241\\0\\3\\1\\235\\0\\3\\1\\226\\0\\5\\0\\0\\3\\4\\136\\0\\3\\6M\\0\\5\\0\\14\\1\\0\\3\\4@\\0\\1\\0\\3\\4@\\0\\3\\6M\\0\\3\\6U\\0\\3\\6U\\0\\3\\1\\249\\0\\3\\6^\\0\\3\\6b\\0\\3\\4J\\0\\3\\6f\\0\\3\\2)\\0\\3\\4p\\0\\3\\2\\21\\0\\3\\2\\25\\0\\3\\2\\17\\0\\3\\2I\\0\\3\\2=\\0\\3\\0029\\0\\3\\2-\\0\\3\\6j\\0\\3\\2!\\0\\3\\2%\\0\\3\\6\\142\\0\\3\\2A\\0\\3\\6\\142\\0\\3\\2\\21\\0\\5\\0\\5\\1\\0\\3\\4@\\0\\1\\0\\3\\7\\29\\0\\3\\7\\r\\0\\1\\0\\3\\7\\4\\0\\1\\0\\3\\6\\251\\0\\1\\0\\3\\6\\242\\0\\3\\6\\234\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\202\\0\\3\\6\\202\\0\\3\\6\\226\\0\\3\\6\\218\\0\\3\\6\\210\\0\\3\\6\\210\\0\\3\\6\\210\\0\\3\\6\\202\\0\\3\\6\\194\\0\\3\\6\\186\\0\\3\\6\\178\\0\\3\\6\\178\\0\\3\\6\\170\\0\\3\\6\\162\\0\\3\\6\\154\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\3w\\0\\5\\0\\190\\3\\6\\149\\0\\3\\3g\\0\\3\\7.\\0\\5\\0\\8\\3\\7\\182\\0\\1\\0\\3\\7\\29\\0\\3\\7\\r\\0\\1\\0\\3\\7\\4\\0\\1\\0\\3\\6\\251\\0\\1\\0\\3\\6\\242\\0\\3\\6\\234\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\202\\0\\3\\6\\202\\0\\3\\6\\226\\0\\3\\6\\218\\0\\3\\6\\210\\0\\3\\6\\210\\0\\3\\6\\210\\0\\3\\6\\202\\0\\3\\6\\194\\0\\3\\6\\186\\0\\3\\6\\178\\0\\3\\6\\178\\0\\3\\6\\170\\0\\3\\6\\162\\0\\3\\6\\154\\0\\5\\1\\3\\3\\6\\149\\0\\3\\3w\\0\\3\\7\\189\\0\\3\\7.\\0\\3\\7\\182\\0\\3\\2\\218\\0\\3\\7\\193\\0\\3\\3\\131\\0\\3\\7\\197\\0\\3\\7\\r\\0\\5\\0\\27\\1\\0\\3\\7\\29\\0\\3\\7\\211\\0\\1\\0\\3\\7\\4\\0\\1\\0\\3\\6\\251\\0\\1\\0\\3\\6\\242\\0\\3\\4J\\0\\1\\0\\3\\4@\\0\\3\\6\\234\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\202\\0\\3\\6\\202\\0\\3\\6\\226\\0\\3\\6\\218\\0\\3\\6\\210\\0\\3\\6\\210\\0\\3\\6\\210\\0\\3\\6\\202\\0\\3\\6\\194\\0\\3\\6\\186\\0\\3\\6\\178\\0\\3\\6\\178\\0\\3\\6\\170\\0\\3\\6\\162\\0\\3\\6\\154\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\3w\\0\\3\\7\\201\\0\\3\\2I\\0\\3\\6b\\0\\3\\6M\\0\\5\\1f\\3\\6\\149\\0\\3\\1\\249\\0\\4\\2\\0\\0\\5\\0\\31\\1\\0\\3\\4E\\0\\4\\4\\0\\1\\6\\4\\5\\0\\1\\6\\4\\8\\0\\0\\6\\4\\12\\0\\0\\6\\1\\0\\3\\7\\219\\0\\3\\7\\243\\0\\3\\7\\239\\0\\3\\7\\235\\0\\3\\7\\228\\0\\1\\0\\3\\7\\219\\0\\4\\12\\0\\0\\5\\0\\214\\3\\8\\1\\0\\4\\12\\0\\0\\3\\8$\\0\\4\\r\\0\\0\\6\\4\\14\\0\\0\\6\\4\\15\\0\\0\\6\\1\\0\\3\\4@\\0\\1\\0\\3\\4E\\0\\6\\3\\7\\211\\0\\3\\2I\\0\\5\\0\\18\\6\\3\\7\\201\\0\\1\\0\\3\\7\\29\\0\\3\\7\\r\\0\\1\\0\\3\\7\\4\\0\\1\\0\\3\\6\\251\\0\\1\\0\\3\\6\\242\\0\\3\\4J\\0\\3\\6\\234\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\202\\0\\3\\6\\202\\0\\3\\6\\226\\0\\3\\6\\218\\0\\3\\6\\210\\0\\3\\6\\210\\0\\3\\6\\210\\0\\3\\6\\202\\0\\3\\6\\194\\0\\3\\6\\186\\0\\3\\6\\178\\0\\3\\6\\178\\0\\3\\6\\170\\0\\3\\6\\162\\0\\3\\6\\154\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\3w\\0\\3\\6b\\0\\5\\1\\233\\3\\6\\149\\0\\3\\7\\235\\0\\5\\0\\30\\6\\3\\7\\239\\0\\1\\0\\3\\8+\\0\\4\\1\\0\\0\\5\\0B\\6\\4\\1\\0\\0\\3\\0080\\0\\4\\1\\0\\0\\3\\0084\\0\\4\\1\\0\\0\\3\\2=\\0\\4\\1\\0\\0\\3\\0088\\0\\1\\0\\3\\4@\\0\\3\\2%\\0\\3\\2=\\0\\3\\2\\21\\0\\4\\1\\0\\0\\5\\0T\\6\\4\\1\\0\\0\\3\\8<\\0\\4\\1\\0\\0\\3\\8@\\0\\4\\1\\0\\0\\3\\8D\\0\\4\\1\\0\\0\\3\\8H\\0\\4\\1\\0\\0\\3\\8L\\0\\4\\12\\0\\0\\4\\n\\0\\1\\6\\4\\r\\0\\0\\3\\8P\\0\\4\\14\\0\\0\\3\\8Z\\0\\3\\8\\1\\0\\3\\7\\243\\0\\3\\7\\228\\0\\5\\1\\19\\1\\0\\3\\7\\219\\0\\3\\8^\\0\\4\\1\\0\\0\\4\\0\\0\\0\\5\\0008\\1\\0\\3\\8f\\0\\4\\1\\0\\0\\1\\0\\3\\4@\\0\\4\\1\\0\\0\\1\\0\\3\\8o\\0\\3\\7\\243\\0\\4\\12\\0\\0\\5\\0%\\3\\8t\\0\\4\\12\\0\\0\\3\\7\\243\\0\\4\\12\\0\\0\\3\\8z\\0\\4\\12\\0\\0\\1\\0\\3\\7\\219\\0\\3\\7\\243\\0\\3\\8\\128\\0\\4\\12\\0\\0\\5\\0\\224\\3\\8\\132\\0\\3\\1\\235\\0\\3\\1\\249\\0\\5\\0c\\1\\0\\3\\4E\\0\\3\\8\\136\\0\\3\\2\\t\\0\\3\\8\\150\\0\\3\\0021\\0\\1\\0\\3\\5\\186\\0\\3\\0060\\0\\3\\6(\\0\\3\\6 \\0\\3\\6\\21\\0\\1\\0\\3\\5\\186\\0\\3\\4O\\0\\5\\1L\\3\\6B\\0\\4\\1\\0\\0\\6\\4\\1\\0\\0\\3\\8\\157\\0\\4\\1\\0\\0\\3\\8\\165\\0\\4\\1\\0\\0\\3\\4p\\0\\4\\1\\0\\0\\3\\2%\\0\\4\\1\\0\\0\\3\\2I\\0\\4\\1\\0\\0\\3\\8\\192\\0\\4\\1\\0\\0\\3\\t \\0\\4\\1\\0\\0\\3\\t\\139\\0\\4\\1\\0\\0\\3\\t\\202\\0\\4\\1\\0\\0\\3\\n\\17\\0\\4\\1\\0\\0\\3\\nT\\0\\4\\4\\0\\1\\4\\1\\0\\0\\6\\4\\6\\0\\1\\4\\1\\0\\0\\6\\4\\t\\0\\1\\4\\1\\0\\0\\6\\4\\2\\0\\0\\4\\1\\0\\0\\4\\0\\0\\0\\3\\6U\\0\\4\\5\\0\\1\\4\\2\\0\\0\\4\\1\\0\\0\\4\\0\\0\\0\\6\\3\\3s\\0\\1\\0\\3\\7\\29\\0\\3\\7\\r\\0\\1\\0\\3\\7\\4\\0\\1\\0\\3\\6\\251\\0\\1\\0\\3\\6\\242\\0\\3\\6\\234\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\202\\0\\3\\6\\202\\0\\3\\6\\226\\0\\3\\6\\218\\0\\3\\6\\210\\0\\3\\6\\210\\0\\3\\6\\210\\0\\3\\6\\202\\0\\3\\6\\194\\0\\3\\6\\186\\0\\3\\6\\178\\0\\3\\6\\178\\0\\3\\6\\170\\0\\3\\6\\162\\0\\3\\6\\154\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\3w\\0\\3\\6\\142\\0\\5\\2L\\3\\6\\149\\0\\3\\2\\233\\0\\3\\n\\227\\0\\3\\0057\\0\\3\\4\\167\\0\\1\\0\\3\\n\\234\\0\\4\\r\\0\\0\\5\\0V\\6\\4\\n\\0\\1\\6\\3\\7\\243\\0\\5\\0=\\3\\8t\\0\\3\\7\\243\\0\\3\\8z\\0\\1\\0\\3\\7\\219\\0\\3\\7\\243\\0\\3\\8\\128\\0\\5\\0\\230\\3\\8\\132\\0\\1\\0\\3\\7\\219\\0\\3\\7\\243\\0\\3\\7\\239\\0\\3\\7\\235\\0\\3\\7\\228\\0\\1\\0\\3\\7\\219\\0\\5\\1U\\3\\8\\1\\0\\4\\t\\0\\1\\6\\3\\8\\157\\0\\3\\8\\165\\0\\3\\8\\192\\0\\3\\t \\0\\3\\t\\139\\0\\3\\t\\202\\0\\3\\n\\17\\0\\3\\nT\\0\\1\\0\\3\\n\\234\\0\\3\\n\\239\\0\\5\\0\\198\\6\\4\\2\\0\\0\\3\\6U\\0\\4\\5\\0\\1\\4\\2\\0\\0\\6\\4\\6\\0\\1\\6\\1\\0\\3\\n\\246\\0\\1\\0\\3\\n\\255\\0\\3\\11\\7\\0\\3\\11\\11\\0\\3\\4\\131\\0\\1\\0\\3\\5\\186\\0\\3\\11\\15\\0\\5\\0\\192\\3\\0060\\0\\3\\0084\\0\\3\\8^\\0\\5\\0m\\1\\0\\3\\8f\\0\\1\\0\\3\\4@\\0\\3\\2%\\0\\3\\2=\\0\\3\\2\\21\\0\\5\\0\\148\\6\\1\\0\\3\\7\\29\\0\\3\\7\\r\\0\\1\\0\\3\\7\\4\\0\\1\\0\\3\\6\\251\\0\\1\\0\\3\\6\\242\\0\\3\\6\\234\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\202\\0\\3\\6\\226\\0\\3\\6\\218\\0\\3\\6\\194\\0\\3\\6\\186\\0\\3\\6\\178\\0\\3\\6\\178\\0\\3\\6\\170\\0\\3\\6\\162\\0\\3\\6\\154\\0\\5\\2\\143\\3\\6\\149\\0\\1\\0\\3\\7\\29\\0\\3\\7\\r\\0\\1\\0\\3\\7\\4\\0\\1\\0\\3\\6\\251\\0\\1\\0\\3\\6\\242\\0\\3\\6\\234\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\202\\0\\3\\6\\202\\0\\3\\6\\226\\0\\3\\6\\218\\0\\3\\6\\202\\0\\3\\6\\194\\0\\3\\6\\186\\0\\3\\6\\178\\0\\3\\6\\178\\0\\3\\6\\170\\0\\3\\6\\162\\0\\3\\6\\154\\0\\5\\2\\212\\3\\6\\149\\0\\1\\0\\3\\7\\29\\0\\3\\7\\r\\0\\1\\0\\3\\7\\4\\0\\1\\0\\3\\6\\251\\0\\1\\0\\3\\6\\242\\0\\3\\6\\194\\0\\3\\6\\186\\0\\3\\6\\178\\0\\3\\6\\178\\0\\3\\6\\170\\0\\3\\6\\162\\0\\3\\6\\154\\0\\5\\2c\\3\\6\\149\\0\\1\\0\\3\\7\\29\\0\\3\\7\\r\\0\\1\\0\\3\\7\\4\\0\\1\\0\\3\\6\\251\\0\\1\\0\\3\\6\\242\\0\\3\\6\\234\\0\\3\\6\\218\\0\\3\\6\\194\\0\\3\\6\\186\\0\\3\\6\\178\\0\\3\\6\\178\\0\\3\\6\\170\\0\\3\\6\\162\\0\\3\\6\\154\\0\\5\\3\\23\\3\\6\\149\\0\\1\\0\\3\\7\\29\\0\\3\\7\\r\\0\\1\\0\\3\\7\\4\\0\\1\\0\\3\\6\\251\\0\\1\\0\\3\\6\\242\\0\\3\\6\\218\\0\\3\\6\\194\\0\\3\\6\\186\\0\\3\\6\\178\\0\\3\\6\\178\\0\\3\\6\\170\\0\\3\\6\\162\\0\\3\\6\\154\\0\\5\\3 \\3\\6\\149\\0\\1\\0\\3\\7\\29\\0\\3\\7\\r\\0\\1\\0\\3\\7\\4\\0\\1\\0\\3\\6\\251\\0\\1\\0\\3\\6\\242\\0\\3\\6\\234\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\226\\0\\3\\6\\202\\0\\3\\6\\202\\0\\3\\6\\226\\0\\3\\6\\218\\0\\3\\6\\210\\0\\3\\6\\210\\0\\3\\6\\210\\0\\3\\6\\202\\0\\3\\6\\194\\0\\3\\6\\186\\0\\3\\6\\178\\0\\3\\6\\178\\0\\3\\6\\170\\0\\3\\6\\162\\0\\3\\6\\154\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\2\\218\\0\\3\\7\\182\\0\\3\\7.\\0\\3\\3w\\0\\5\\3\\163\\3\\6\\149\\0\\4\\7\\0\\1\\6\\5\\0\\11\\3\\11\\25\\0\\2\\1\\0\\1\\0\\3\\11\\30\\0\\4\\n\\0\\1\\3\\4\\158\\0\\3\\7\\243\\0\\3\\11\'\\0\\4\\12\\0\\0\\1\\0\\3\\n\\246\\0\\4\\3\\0\\1\\6\\4\\11\\1\\2\\6\\3\\11.\\0\\5\\0\\136\\3\\0112\\0\\3\\7\\243\\0\\3\\0116\\0\\3\\11.\\0"\nlocal error_tbl_ks, error_tbl_vs, error_tbl = 1, 2, "\\0\\0\\199\\1\\0\\147\\2\\0\\0\\3\\0\\195\\0\\0\\0\\5\\1K\\0\\0\\0\\7\\1G\\0\\0\\0\\t\\0\\207\\0\\0\\0\\11\\1C\\0\\0\\0\\r\\1?\\0\\0\\0\\15\\0\\223\\16\\0\\187\\17\\0\\213\\18\\1\\211\\19\\0\\167\\20\\1\\207\\21\\0\\0\\22\\1\\203\\23\\0\\179\\24\\1\\163\\25\\1\\199\\26\\0\\11\\27\\0\'\\28\\1;\\29\\0017\\30\\0013\\31\\0\\151 \\1/!\\1+\\"\\1\'\\21\\1\\222$\\1#%\\1\\31\\0\\0\\0\'\\1\\27(\\1\\23)\\1\\19*\\0\\27\\0\\0\\0,\\0o\\0\\0\\0.\\0k\\0\\0\\0000\\0g\\0\\0\\0002\\0c\\0\\0\\0004\\0_\\0\\0\\0006\\0[\\0\\0\\0008\\0W\\0\\0\\0:\\0S\\0\\0\\0<\\0O\\0\\0\\0>\\0K\\0\\0\\0@\\0G\\0\\0\\0B\\0C\\0\\0\\0D\\0?\\0\\0\\0F\\0;G\\0\\235H\\0\\213I\\1OJ\\0+K\\0wL\\0\\179M\\1\\15N\\0sO\\0\\0P\\0\\231Q\\0\\0R\\0\\0S\\1\\11T\\1\\7U\\1\\3V\\0\\255W\\0\\251X\\0\\27Y\\0\\0R\\2\\229[\\0\\131\\\\\\0\\227R\\0\\0^\\0\\127_\\0\\219`\\1\\195a\\1\\191b\\1\\187c\\1\\183d\\0#e\\0\\175f\\0\\247g\\0\\31h\\0\\243i\\0\\239j\\0\\135k\\0\\7l\\0\'m\\1\\159n\\1\\155o\\1\\151p\\1\\147q\\0\\199r\\0\\147n\\2Mt\\0{u\\0\\0v\\0\\183w\\0001x\\0\\23y\\0\'z\\1\\143{\\0\\159|\\1\\139b\\3\\135~\\1\\135\\127\\0\\183\\128\\0\\155b\\4/\\130\\0\\135\\131\\0\\19\\132\\0\\147\\133\\0\\139\\134\\1\\131u\\4\\163\\136\\0\\135\\137\\0\\15\\138\\0\\143\\139\\0005\\140\\0\'\\141\\1\\127\\142\\0\\183\\143\\0\\163\\144\\0\\187\\145\\0\\0\\146\\1\\179\\147\\0\\0\\148\\1\\175\\149\\0\\23\\150\\0\'\\151\\1{\\152\\0\\183\\153\\0\\171b\\5\\232\\155\\0\\135H\\5x\\157\\0\\135\\158\\0\\7\\159\\0\'\\160\\1w\\131\\5>\\162\\0\\135\\163\\0\\7\\164\\0\'\\165\\1s\\166\\0\\0\\137\\5>\\168\\0\\0\\169\\0\\7\\170\\0\'\\171\\1o\\172\\0\\1\\173\\0\'\\174\\1k\\175\\1g\\176\\1c\\177\\1_\\178\\1[\\179\\0\\0\\180\\0\\203\\144\\6\\17\\182\\1W\\183\\0\\183\\184\\1\\171\\185\\1\\167\\186\\0\\191\\187\\1S\\188\\0\\0\\189\\0\\0\\190\\0\\0\\191\\0\\0\\192\\0\\0\\3\\0\\0n\\5\\134\\129\\5J\\6\\2\\202b\\6Q\\8\\2p\\t\\2Z\\n\\2j\\135\\5J\\12\\2\\206u\\7\\205\\14\\2\\210\\144\\7\\224\\8\\8Vb\\8\\161\\16\\8\\140}\\5\\130" .. ("\\0"):rep(15) .. "\\17\\8V\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0H\\8\\174\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0#\\2jZ\\11#\\0\\0\\0&\\2\\214]\\11#\\0\\0\\0\\0\\0\\0\\0\\0\\0+\\2\\170\\0\\0\\0-\\2\\166\\0\\0\\0/\\2\\162\\0\\0\\0001\\2\\158\\26\\4Z3\\2\\154\\0\\0\\0005\\2\\150\\0\\0\\0007\\2\\146\\0\\0\\0009\\2\\142\\0\\0\\0;\\2\\138\\0\\0\\0=\\2\\134\\0\\0\\0?\\2\\130\\0\\0\\0A\\2~\\0\\0\\0C\\2zn\\8\\188E\\2v\\0\\0\\0}\\11#H\\2p\\0\\0\\0J\\2\\174\\181\\5~\\0\\0\\0\\8\\3\\6\\t\\2\\240\\n\\3\\0H\\8V\\0\\0\\0\\0\\0\\0}\\8\\184" .. ("\\0"):rep(18) .. "Z\\2\\198\\0\\0\\0\\0\\0\\0]\\2\\194\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0b\\2`\\0\\0\\0\\154\\11#\\0\\0\\0\\0\\0\\0\\0\\0\\0#\\3\\0\\0\\0\\0\\0\\0\\0I\\6>\\0\\0\\0\\0\\0\\0n\\2\\190\\26\\5\\215+\\3@I\\7\\253-\\3<s\\2\\186/\\0038\\0\\0\\0001\\0034\\0\\0\\0003\\0030w\\8\\1465\\3,\\0\\0\\0007\\3(}\\2\\1829\\3$\\181\\11#;\\3 \\129\\2d=\\3\\28\\0\\0\\0?\\3\\24\\0\\0\\0A\\3\\20\\135\\2dC\\3\\16q\\0\\0E\\3\\12\\181\\8\\180j\\6:H\\3\\6\\0\\6\\138J\\3Dx\\4f\\0\\0\\0j\\7\\249" .. ("\\0"):rep(24) .. "\\131\\4b\\0\\0\\0\\0\\0\\0\\0\\0\\0Z\\3\\\\~\\6>\\137\\4^]\\3X\\139\\4j\\0\\0\\0\\0\\0\\0~\\7\\253b\\2\\246\\26\\6t\\0\\0\\0\\0\\0\\0\\3\\3\\170\\0\\0\\0\\149\\4f\\6\\4\\8\\0\\0\\0\\8\\3\\164\\26\\8\\14\\n\\3\\158n\\3T\\12\\4\\12\\181\\2\\178\\14\\4\\16\\183\\0\\0s\\3P\\17\\3\\174\\0\\0\\0\\0\\0\\0\\0\\0\\0\\21\\4$\\0\\0\\0\\0\\0\\0k\\5\\211\\0\\0\\0}\\3L\\0\\0\\0\\172\\4T\\0\\0\\0\\129\\2\\250\\0\\0\\0\\0\\0\\0\\0\\0\\0\\168\\6>#\\3\\158\\135\\2\\250x\\5\\219&\\4\\20\\0\\0\\0\\168\\7\\253\\0\\0\\0\\0\\0\\0+\\3\\232\\0\\0\\0-\\3\\228\\0\\0\\0/\\3\\224\\182\\6>1\\3\\220\\0\\0\\0003\\3\\216\\0\\0\\0005\\3\\212\\182\\7\\2537\\3\\208\\190\\6>9\\3\\204\\0\\0\\0;\\3\\200\\0\\0\\0=\\3\\196\\190\\7\\253?\\3\\192\\0\\0\\0A\\3\\188\\149\\5\\219C\\3\\184\\0\\0\\0E\\3\\180\\0\\0\\0\\0\\0\\0H\\3\\164\\0\\0\\0J\\3\\236\\158\\5\\211\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\163\\5\\211\\0\\0\\0\\181\\3H\\0\\0\\0\\0\\0\\0\\0\\0\\0\\169\\5\\211q\\6\\138\\0\\0\\0\\0\\0\\0Z\\4\\4\\0\\0\\0\\0\\0\\0]\\4\\0x\\6\\128\\0\\0\\0q" .. ("\\0"):rep(20) .. "x\\8\\26\\0\\0\\0\\131\\6|\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0n\\3\\252\\137\\6x\\0\\0\\0\\139\\6\\132\\131\\8\\22s\\3\\248\\0\\0\\0u\\4\\28v\\3\\148\\0\\0\\0\\137\\8\\18\\0\\0\\0\\139\\8\\30\\149\\6\\128\\0\\0\\0}\\3\\244\\0\\0\\0\\127\\4\\24\\0\\0\\0\\129\\3\\152\\0\\0\\0\\0\\0\\0\\149\\8\\26\\0\\0\\0\\3\\4\\203\\135\\3\\152\\0\\0\\0\\6\\5#\\0\\0\\0\\8\\4\\197\\t\\4\\175\\n\\4\\191\\142\\3\\148\\12\\5\'\\0\\0\\0\\14\\5+\\172\\6n" .. ("\\0"):rep(15) .. "\\152\\0\\0\\0\\0\\0\\0\\0\\0\\172\\8\\8" .. ("\\0"):rep(30) .. "#\\4\\191\\0\\0\\0\\0\\0\\0&\\5/\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0+\\5\\3\\0\\0\\0-\\4\\255\\0\\0\\0/\\4\\251\\0\\0\\0001\\4\\247\\181\\3\\2403\\4\\243\\183\\4 5\\4\\239\\0\\0\\0007\\4\\235\\0\\0\\0009\\4\\231\\0\\0\\0;\\4\\227\\0\\0\\0=\\4\\223\\0\\0\\0?\\4\\219\\0\\0\\0A\\4\\215\\0\\0\\0C\\4\\211\\0\\0\\0E\\4\\207\\0\\0\\0\\0\\0\\0H\\4\\197\\0\\0\\0J\\5\\7" .. ("\\0"):rep(45) .. "Z\\5\\31\\0\\0\\0\\0\\0\\0]\\5\\27\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0b\\4\\181\\0\\0\\0\\0\\0\\0\\0\\0\\0\\3\\7\\178\\0\\0\\0\\0\\0\\0\\6\\7\\162\\0\\0\\0\\8\\7H\\t\\0072\\n\\7Bn\\5\\23\\12\\7\\166\\0\\0\\0\\14\\7\\170\\0\\0\\0s\\5\\19" .. ("\\0"):rep(27) .. "}\\5\\15\\0\\0\\0\\0\\0\\0\\0\\0\\0\\129\\4\\185\\8\\t\\168\\t\\t\\146\\n\\t\\162\\0\\0\\0#\\7B\\135\\4\\185\\0\\0\\0&\\7\\174\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0+\\7\\130\\0\\0\\0-\\7~\\0\\0\\0/\\7z\\0\\0\\0001\\7v\\0\\0\\0003\\7r\\0\\0\\0005\\7n\\0\\0\\0007\\7j\\0\\0\\0009\\7f#\\t\\162;\\7b\\0\\0\\0=\\7^\\0\\0\\0?\\7Z\\0\\0\\0A\\7V\\0\\0\\0C\\7R\\0\\0\\0E\\7N\\0\\0\\0\\0\\0\\0H\\7H\\0\\0\\0J\\7\\134\\8\\8\\218\\t\\8\\196\\n\\8\\212\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\181\\5\\11\\0\\0\\0\\183\\0053" .. ("\\0"):rep(15) .. "Z\\7\\158\\0\\0\\0\\0\\0\\0]\\7\\154\\0\\0\\0H\\t\\168\\0\\0\\0J\\t\\174b\\0078\\0\\0\\0\\0\\0\\0\\0\\0\\0#\\8\\212" .. ("\\0"):rep(21) .. "n\\7\\150\\0\\0\\0\\0\\0\\0Z\\t\\198\\0\\0\\0s\\7\\146]\\t\\194\\0\\0\\0003\\t\\0\\0\\0\\0005\\8\\252b\\t\\1527\\8\\248\\0\\0\\0\\0\\0\\0}\\7\\142;\\8\\244\\0\\0\\0=\\8\\240\\129\\7<?\\8\\236\\0\\0\\0A\\8\\232n\\t\\190C\\8\\228\\135\\7<E\\8\\224\\0\\0\\0s\\t\\186H\\8\\218\\0\\0\\0J\\t\\4\\0\\0\\0\\0\\0\\0\\8\\t=\\t\\t\'\\n\\t7\\0\\0\\0}\\t\\182\\0\\0\\0\\0\\0\\0\\0\\0\\0\\129\\t\\156\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0Z\\t\\28\\135\\t\\156\\0\\0\\0]\\t\\24\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0b\\8\\202" .. ("\\0"):rep(15) .. "#\\t7" .. ("\\0"):rep(15) .. "n\\t\\20\\0\\0\\0+\\tk\\0\\0\\0\\181\\7\\138s\\t\\16\\183\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0003\\tg\\0\\0\\0005\\tc\\0\\0\\0007\\t_}\\t\\0129\\t[\\0\\0\\0;\\tW\\129\\8\\206=\\tS\\0\\0\\0?\\tO\\0\\0\\0A\\tK\\135\\8\\206C\\tG\\181\\t\\178E\\tC\\0\\0\\0\\0\\0\\0H\\t=\\0\\0\\0J\\to\\8\\t\\231\\t\\t\\209\\n\\t\\225" .. ("\\0"):rep(18) .. "\\8\\n.\\t\\n\\24\\n\\n(\\0\\0\\0\\0\\0\\0\\0\\0\\0Z\\t\\135\\0\\0\\0\\0\\0\\0]\\t\\131\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0b\\t-\\0\\0\\0\\0\\0\\0\\0\\0\\0#\\t\\225" .. ("\\0"):rep(21) .. "n\\t\\127#\\n(\\181\\t\\8\\0\\0\\0\\0\\0\\0s\\t{\\0\\0\\0\\0\\0\\0003\\t\\241" .. ("\\0"):rep(18) .. "}\\tw\\0\\0\\0003\\n4\\0\\0\\0\\129\\t1" .. ("\\0"):rep(15) .. "\\135\\t1E\\t\\237\\0\\0\\0\\0\\0\\0H\\t\\231\\0\\0\\0J\\t\\245" .. ("\\0"):rep(18) .. "H\\n.\\0\\0\\0J\\n8" .. ("\\0"):rep(18) .. "Z\\n\\r\\0\\0\\0\\0\\0\\0]\\n\\t\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0b\\t\\215Z\\nP\\0\\0\\0\\0\\0\\0]\\nL\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0b\\n\\30\\0\\0\\0\\0\\0\\0n\\n\\5\\0\\0\\0\\0\\0\\0\\0\\0\\0\\181\\tss\\n\\1\\0\\0\\0\\0\\0\\0\\0\\0\\0n\\nH\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0s\\nD}\\t\\253\\0\\0\\0\\0\\0\\0\\0\\0\\0\\129\\t\\219\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0}\\n@\\135\\t\\219\\0\\0\\0\\0\\0\\0\\129\\n\\"" .. ("\\0"):rep(15) .. "\\135\\n\\"\\0\\0\\0\\6\\n\\203\\0\\0\\0\\8\\nq\\t\\n[\\n\\nk\\0\\0\\0\\12\\n\\207\\0\\0\\0\\14\\n\\211" .. ("\\0"):rep(54) .. "!\\n\\215\\0\\0\\0#\\nk\\0\\0\\0\\0\\0\\0&\\n\\223\\0\\0\\0\\0\\0\\0\\181\\t\\249\\0\\0\\0+\\n\\171\\0\\0\\0-\\n\\167\\0\\0\\0/\\n\\163\\0\\0\\0001\\n\\159\\181\\n<3\\n\\155\\0\\0\\0005\\n\\151\\0\\0\\0007\\n\\147\\0\\0\\0009\\n\\143\\0\\0\\0;\\n\\139\\0\\0\\0=\\n\\135\\0\\0\\0?\\n\\131\\0\\0\\0A\\n\\127\\0\\0\\0C\\n{\\0\\0\\0E\\nw\\0\\0\\0\\0\\0\\0H\\nq\\0\\0\\0J\\n\\175" .. ("\\0"):rep(21) .. "R\\n\\219" .. ("\\0"):rep(21) .. "Z\\n\\199\\0\\0\\0\\0\\0\\0]\\n\\195\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0b\\na" .. ("\\0"):rep(33) .. "n\\n\\191\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0s\\n\\187" .. ("\\0"):rep(27) .. "}\\n\\183\\0\\0\\0\\0\\0\\0\\0\\0\\0\\129\\ne" .. ("\\0"):rep(15) .. "\\135\\ne" .. ("\\0"):rep(129) .. "\\179\\n\\215\\0\\0\\0\\181\\n\\179"\n\nlocal function handle_error(context, stack, stack_n, token, token_start, token_end)\n -- Run our error handling virtual machine.\n local pc, top, registers, messages = error_program_start, stack_n, {}, {}\n while true do\n local instruction = error_program:byte(pc + 1)\n if instruction == 1 then -- Store\n registers[error_program:byte(pc + 2) + 1] = top\n pc = pc + 2\n elseif instruction == 2 then -- Move\n registers[error_program:byte(pc + 2) + 1] = registers[error_program:byte(pc + 3) + 1]\n pc = pc + 3\n elseif instruction == 3 then -- Pop one item from the stack and jump\n if top > 1 then top = top - 3 end\n pc = get_int(error_program, pc + 1, 3)\n elseif instruction == 4 then -- Accept\n local clause, _, count = error_program:byte(pc + 2, pc + 4)\n local accept = { clause + 1 }\n for i = 1, count do accept[i + 1] = registers[count - i + 1] end\n messages[#messages + 1] = accept\n\n pc = pc + 4\n elseif instruction == 5 then -- Match\n local hi, lo = error_program:byte(pc + 2, pc + 3)\n local lr1 = stack[top] - 1\n\n local offset = (hi * 256 + lo + lr1) * (error_tbl_ks + error_tbl_vs)\n if offset + error_tbl_ks + error_tbl_vs <= #error_tbl and\n get_int(error_tbl, offset, error_tbl_ks) == lr1 then\n pc = get_int(error_tbl, offset + error_tbl_ks, error_tbl_vs)\n else\n pc = pc + 3\n end\n elseif instruction == 6 then -- Halt\n break\n else\n error("Illegal instruction while handling errors " .. tostring(instruction))\n end\n end\n\n -- Sort the list to ensure earlier patterns are used first.\n table.sort(messages, function(a, b) return a[1] < b[1] end)\n\n -- Then loop until we find an error message which actually works!\n local t = { v = token, s = token_start, e = token_end }\n for i = 1, #messages do\n local action = messages[i]\n local message = error_messages[action[1]](context, stack, stack_n, action, t)\n if message then\n context.report(message)\n return false\n end\n end\n\n context.report(errors.unexpected_token, token, token_start, token_end)\n return false\nend\n\n--- The list of productions in our grammar. Each is a tuple of `terminal * production size`.\nlocal productions = {\n { 53, 1 }, { 52, 1 }, { 81, 1 }, { 81, 1 }, { 80, 3 }, { 79, 1 },\n { 79, 1 }, { 79, 1 }, { 79, 1 }, { 79, 1 }, { 79, 1 }, { 79, 1 },\n { 79, 1 }, { 79, 4 }, { 78, 2 }, { 78, 4 }, { 77, 3 }, { 77, 1 },\n { 77, 1 }, { 76, 1 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 },\n { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 },\n { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 75, 1 }, { 75, 3 },\n { 75, 2 }, { 75, 2 }, { 75, 2 }, { 74, 1 }, { 74, 3 }, { 74, 3 },\n { 73, 0 }, { 73, 2 }, { 73, 3 }, { 73, 1 }, { 73, 2 }, { 72, 1 },\n { 72, 3 }, { 72, 4 }, { 71, 2 }, { 70, 2 }, { 69, 0 }, { 69, 2 },\n { 69, 3 }, { 68, 0 }, { 68, 5 }, { 67, 0 }, { 67, 1 }, { 66, 0 },\n { 66, 1 }, { 65, 1 }, { 65, 3 }, { 64, 1 }, { 64, 3 }, { 63, 1 },\n { 63, 3 }, { 62, 1 }, { 62, 3 }, { 61, 1 }, { 61, 3 }, { 61, 1 },\n { 60, 3 }, { 60, 3 }, { 60, 5 }, { 60, 4 }, { 60, 6 }, { 60, 8 },\n { 60, 9 }, { 60, 11 }, { 60, 7 }, { 60, 2 }, { 60, 4 }, { 60, 6 },\n { 60, 5 }, { 60, 1 }, { 59, 2 }, { 58, 3 }, { 57, 0 }, { 57, 1 },\n { 57, 3 }, { 56, 1 }, { 56, 3 }, { 56, 5 }, { 55, 1 }, { 55, 1 },\n { 54, 1 },\n}\n\nlocal f = false\n\n--[[- The state machine used for our grammar.\n\nMost LR(1) parsers will encode the transition table in a compact binary format,\noptimised for space and fast lookups. However, without access to built-in\nbitwise operations, this is harder to justify in Lua. Instead, the transition\ntable is a 2D lookup table of `action = transitions[state][value]`, where\n`action` can be one of the following:\n\n - `action = false`: This transition is undefined, and thus a parse error. We\n use this (rather than nil) to ensure our tables are dense, and thus stored as\n arrays rather than maps.\n\n - `action > 0`: Shift this terminal or non-terminal onto the stack, then\n transition to `state = action`.\n\n - `action < 0`: Apply production `productions[-action]`. This production is a\n tuple composed of the next state and the number of values to pop from the\n stack.\n]]\nlocal transitions = {\n { -53, f, f, f, f, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, f, f, f, -53, f, f, f, -53, -53, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, -53, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, f, f, 2, f, f, f, f, f, f, f, f, f, 4, f, 189 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 3 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -51 },\n { 5, -43, f, f, f, f, f, 111, 114, f, f, f, 9, f, f, f, f, f, f, f, f, 118, f, f, f, 130, 16, f, f, 143, 153, f, f, f, -43, -43, -43, -43, f, f, 173, f, f, f, f, f, f, f, 176, f, f, f, f, 32, f, f, f, f, f, 178, 180, f, 181, f, f, f, f, f, f, f, f, 186, 187, f, f, f, f, 188 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 107, f, 41, 42 },\n { -9, -9, f, -9, -9, f, -9, -9, -9, -9, f, -9, -9, f, f, f, f, -9, -9, -9, -9, -9, f, -9, f, -9, -9, -9, -9, -9, -9, f, f, -9, -9, -9, -9, -9, f, f, -9, -9, -9, -9, -9, -9, f, -9, -9, -9, -9 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 106, f, f, 41, 42 },\n { -13, -13, f, -13, -13, f, -13, -13, -13, -13, f, -13, -13, f, f, f, f, -13, -13, -13, -13, -13, f, -13, f, -13, -13, -13, -13, -13, -13, f, f, -13, -13, -13, -13, -13, f, f, -13, -13, -13, -13, -13, -13, f, -13, -13, -13, -13 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 104, f, 41, 42 },\n { f, f, 6, f, 7, 8, f, f, f, f, 11, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 93, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, -89, f, f, f, f, f, 32, f, 96, 102, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 101, f, 41, 42 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 89, f, 41, 42 },\n { -12, -12, f, -12, -12, f, -12, -12, -12, -12, f, -12, -12, f, f, f, f, -12, -12, -12, -12, -12, f, -12, f, -12, -12, -12, -12, -12, -12, f, f, -12, -12, -12, -12, -12, f, f, -12, -12, -12, -12, -12, -12, f, -12, -12, -12, -12 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 88, f, f, 41, 42 },\n { -8, -8, f, -8, -8, f, -8, -8, -8, -8, f, -8, -8, f, f, f, f, -8, -8, -8, -8, -8, f, -8, f, -8, -8, -8, -8, -8, -8, f, f, -8, -8, -8, -8, -8, f, f, -8, -8, -8, -8, -8, -8, f, -8, -8, -8, -8 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 87, f, f, 41, 42 },\n { -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97 },\n { f, f, f, f, f, f, f, f, f, f, f, f, 18, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 27 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 16, f, f, f, f, f, f, f, f, f, f, f, 19, f, f, f, f, -58, f, f, f, f, f, f, f, f, f, 20, f, f, f, f, f, f, f, f, f, f, 21, f, 24, f, f, f, f, f, f, f, f, f, f, f, f, f, 26 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -4, f, -4 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -3, f, -3 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -59, f, 22 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 16, f, f, f, f, f, f, f, f, f, f, f, 19, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 20, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 23 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -63, f, -63 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 25 },\n { -5, f, f, f, f, f, f, -5, -5, f, f, f, -5, f, f, f, f, f, f, f, f, -5, f, f, f, -5, -5, f, f, -5, -5, f, f, f, f, -5, f, f, f, f, -5, f, f, f, f, f, f, f, -5 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -62, f, -62 },\n { -53, f, f, f, f, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, f, f, f, -53, f, f, f, -53, -53, f, f, -53, -53, f, f, f, f, -53, f, f, f, f, -53, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, f, f, 28, f, f, f, f, f, f, f, f, f, 4 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 29 },\n { -14, -14, f, -14, -14, f, -14, -14, -14, -14, f, -14, -14, f, f, f, f, -14, -14, -14, -14, -14, f, -14, f, -14, -14, -14, -14, -14, -14, f, f, -14, -14, -14, -14, -14, f, f, -14, -14, -14, -14, -14, -14, f, -14, -14, -14, -14 },\n { -10, -10, f, -10, -10, f, -10, -10, -10, -10, f, -10, -10, f, f, f, f, -10, -10, -10, -10, -10, f, -10, f, -10, -10, -10, -10, -10, -10, f, f, -10, -10, -10, -10, -10, f, f, -10, -10, -10, -10, -10, -10, f, -10, -10, -10, -10 },\n { -11, -11, f, -11, -11, f, -11, -11, -11, -11, f, -11, -11, f, f, f, f, -11, -11, -11, -11, -11, f, -11, f, -11, -11, -11, -11, -11, -11, f, f, -11, -11, -11, -11, -11, f, f, -11, -11, -11, -11, -11, -11, f, -11, -11, -11, -11 },\n { -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48, -48 },\n { -7, -7, f, -7, -7, f, -7, -7, -7, -7, f, -7, -7, f, f, f, f, -7, -7, -7, -7, -7, f, -7, f, -7, -7, -7, -7, -7, -7, f, f, -7, -7, -7, -7, -7, f, f, -7, -7, -7, -7, -7, -7, f, -7, -7, -7, -7 },\n { -6, -6, f, -6, -6, 35, -6, -6, -6, -6, 36, -6, 73, 10, f, f, f, -6, -6, -6, -6, -6, f, -6, f, -6, -6, -6, -6, -6, -6, f, f, -6, -6, -6, -6, -6, f, 80, -6, -6, -6, -6, -6, -6, 82, -6, -6, -6, -6, f, f, f, f, f, f, 84, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 86 },\n { -18, -18, f, -18, -18, -18, -18, -18, -18, -18, -18, -18, -18, -18, f, f, f, -18, -18, -18, -18, -18, f, -18, f, -18, -18, -18, -18, -18, -18, f, f, -18, -18, -18, -18, -18, f, -18, -18, -18, -18, -18, -18, -18, -18, -18, -18, -18, -18 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 43, f, 41, 42 },\n { -70, -70, f, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, f, f, f, -70, -70, -70, -70, -70, f, -70, f, -70, -70, -70, -70, -70, -70, f, f, -70, -70, -70, -70, -70, f, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70 },\n { -20, -20, f, -20, -20, f, -20, -20, -20, 39, f, -20, -20, f, f, f, f, -20, -20, -20, -20, -20, f, -20, f, -20, -20, -20, -20, -20, -20, f, f, -20, -20, -20, -20, -20, f, f, -20, -20, -20, -20, -20, -20, f, -20, -20, -20, -20 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 40, f, f, 41, 42 },\n { -36, -36, -36, -36, -36, -36, -36, -36, -36, 39, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36 },\n { -72, -72, f, -72, -72, -72, -72, -72, -72, -72, -72, -72, -72, -72, f, f, f, -72, -72, -72, -72, -72, f, -72, f, -72, -72, -72, -72, -72, -72, f, f, -72, -72, -72, -72, -72, f, -72, -72, -72, -72, -72, -72, -72, -72, -72, -72, -72, -72 },\n { -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35, -35 },\n { f, f, f, f, 44, f, f, f, f, f, f, 52, f, f, f, f, f, 54, 46, 48, 60, f, f, 62, f, f, f, 64, 66, f, f, f, f, 68, f, f, f, f, f, f, f, 50, 72, f, 56, f, f, f, f, 70, 58 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 45, f, 41, 42 },\n { -24, -24, f, -24, -24, f, -24, -24, -24, f, f, -24, -24, f, f, f, f, -24, 46, 48, -24, -24, f, -24, f, -24, -24, -24, -24, -24, -24, f, f, -24, -24, -24, -24, -24, f, f, -24, 50, -24, -24, -24, -24, f, -24, -24, -24, -24 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 47, f, 41, 42 },\n { -25, -25, f, -25, -25, f, -25, -25, -25, f, f, -25, -25, f, f, f, f, -25, -25, -25, -25, -25, f, -25, f, -25, -25, -25, -25, -25, -25, f, f, -25, -25, -25, -25, -25, f, f, -25, -25, -25, -25, -25, -25, f, -25, -25, -25, -25 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 49, f, 41, 42 },\n { -27, -27, f, -27, -27, f, -27, -27, -27, f, f, -27, -27, f, f, f, f, -27, -27, -27, -27, -27, f, -27, f, -27, -27, -27, -27, -27, -27, f, f, -27, -27, -27, -27, -27, f, f, -27, -27, -27, -27, -27, -27, f, -27, -27, -27, -27 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 51, f, 41, 42 },\n { -26, -26, f, -26, -26, f, -26, -26, -26, f, f, -26, -26, f, f, f, f, -26, -26, -26, -26, -26, f, -26, f, -26, -26, -26, -26, -26, -26, f, f, -26, -26, -26, -26, -26, f, f, -26, -26, -26, -26, -26, -26, f, -26, -26, -26, -26 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 53, f, 41, 42 },\n { -22, -22, f, -22, 44, f, -22, -22, -22, f, f, -22, -22, f, f, f, f, 54, 46, 48, 60, -22, f, 62, f, -22, -22, 64, 66, -22, -22, f, f, 68, -22, -22, -22, -22, f, f, -22, 50, -22, -22, 56, -22, f, -22, -22, 70, 58 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 55, f, 41, 42 },\n { -30, -30, f, -30, 44, f, -30, -30, -30, f, f, -30, -30, f, f, f, f, -30, 46, 48, -30, -30, f, -30, f, -30, -30, -30, -30, -30, -30, f, f, -30, -30, -30, -30, -30, f, f, -30, 50, -30, -30, 56, -30, f, -30, -30, -30, 58 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 57, f, 41, 42 },\n { -28, -28, f, -28, 44, f, -28, -28, -28, f, f, -28, -28, f, f, f, f, -28, 46, 48, -28, -28, f, -28, f, -28, -28, -28, -28, -28, -28, f, f, -28, -28, -28, -28, -28, f, f, -28, 50, -28, -28, 56, -28, f, -28, -28, -28, 58 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 59, f, 41, 42 },\n { -23, -23, f, -23, -23, f, -23, -23, -23, f, f, -23, -23, f, f, f, f, -23, 46, 48, -23, -23, f, -23, f, -23, -23, -23, -23, -23, -23, f, f, -23, -23, -23, -23, -23, f, f, -23, 50, -23, -23, -23, -23, f, -23, -23, -23, -23 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 61, f, 41, 42 },\n { -31, -31, f, -31, 44, f, -31, -31, -31, f, f, -31, -31, f, f, f, f, -31, 46, 48, -31, -31, f, -31, f, -31, -31, -31, -31, -31, -31, f, f, -31, -31, -31, -31, -31, f, f, -31, 50, -31, -31, 56, -31, f, -31, -31, -31, 58 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 63, f, 41, 42 },\n { -32, -32, f, -32, 44, f, -32, -32, -32, f, f, -32, -32, f, f, f, f, -32, 46, 48, -32, -32, f, -32, f, -32, -32, -32, -32, -32, -32, f, f, -32, -32, -32, -32, -32, f, f, -32, 50, -32, -32, 56, -32, f, -32, -32, -32, 58 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 65, f, 41, 42 },\n { -33, -33, f, -33, 44, f, -33, -33, -33, f, f, -33, -33, f, f, f, f, -33, 46, 48, -33, -33, f, -33, f, -33, -33, -33, -33, -33, -33, f, f, -33, -33, -33, -33, -33, f, f, -33, 50, -33, -33, 56, -33, f, -33, -33, -33, 58 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 67, f, 41, 42 },\n { -34, -34, f, -34, 44, f, -34, -34, -34, f, f, -34, -34, f, f, f, f, -34, 46, 48, -34, -34, f, -34, f, -34, -34, -34, -34, -34, -34, f, f, -34, -34, -34, -34, -34, f, f, -34, 50, -34, -34, 56, -34, f, -34, -34, -34, 58 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 69, f, 41, 42 },\n { -29, -29, f, -29, 44, f, -29, -29, -29, f, f, -29, -29, f, f, f, f, -29, 46, 48, -29, -29, f, -29, f, -29, -29, -29, -29, -29, -29, f, f, -29, -29, -29, -29, -29, f, f, -29, 50, -29, -29, 56, -29, f, -29, -29, -29, 58 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 71, f, 41, 42 },\n { -21, -21, f, -21, 44, f, -21, -21, -21, f, f, -21, -21, f, f, f, f, 54, 46, 48, 60, -21, f, 62, f, -21, -21, 64, 66, -21, -21, f, f, 68, -21, -21, -21, -21, f, f, -21, 50, -21, -21, 56, -21, f, -21, -21, -21, 58 },\n { -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, -60, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, 74, f, 77, f, f, f, f, f, 37, f, f, 38, 79, f, 41, 42 },\n { f, -61, f, f, f, f, -61, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -61, -61, -61, -61, f, f, f, f, f, -61, f, 75 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 76, f, 41, 42 },\n { -65, -65, f, f, 44, f, -65, -65, -65, f, f, 52, -65, f, f, f, f, 54, 46, 48, 60, -65, f, 62, f, -65, -65, 64, 66, -65, -65, f, f, 68, -65, -65, -65, -65, f, f, -65, 50, f, -65, 56, -65, f, f, -65, 70, 58 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 78 },\n { -17, -17, f, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, f, f, f, -17, -17, -17, -17, -17, f, -17, f, -17, -17, -17, -17, -17, -17, f, f, -17, -17, -17, -17, -17, f, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17 },\n { -64, -64, f, f, 44, f, -64, -64, -64, f, f, 52, -64, f, f, f, f, 54, 46, 48, 60, -64, f, 62, f, -64, -64, 64, 66, -64, -64, f, f, 68, -64, -64, -64, -64, f, f, -64, 50, f, -64, 56, -64, f, f, -64, 70, 58 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 81 },\n { -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49, -49 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 83 },\n { f, f, f, f, f, 35, f, f, f, f, f, f, 73, 10, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 84, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 85 },\n { -19, -19, f, -19, -19, -19, -19, -19, -19, -19, -19, -19, -19, -19, f, f, f, -19, -19, -19, -19, -19, f, -19, f, -19, -19, -19, -19, -19, -19, f, f, -19, -19, -19, -19, -19, f, -19, -19, -19, -19, -19, -19, -19, -19, -19, -19, -19, -19 },\n { -16, -16, f, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, f, f, f, -16, -16, -16, -16, -16, f, -16, f, -16, -16, -16, -16, -16, -16, f, f, -16, -16, -16, -16, -16, f, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16 },\n { -15, -15, f, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, f, f, f, -15, -15, -15, -15, -15, f, -15, f, -15, -15, -15, -15, -15, -15, f, f, -15, -15, -15, -15, -15, f, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15 },\n { -38, -38, -38, -38, -38, -38, -38, -38, -38, 39, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38, -38 },\n { -39, -39, -39, -39, -39, -39, -39, -39, -39, 39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39, -39 },\n { f, f, f, f, 44, f, f, f, f, f, f, 52, f, f, f, f, f, 54, 46, 48, 60, f, f, 62, f, f, f, 64, 66, f, f, f, f, 68, f, f, f, f, f, f, f, 50, 90, f, 56, f, f, f, f, 70, 58 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 91 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 92, f, 41, 42 },\n { f, f, f, f, 44, f, -94, f, f, f, f, 52, f, f, f, f, f, 54, 46, 48, 60, f, f, 62, f, f, f, 64, 66, f, f, f, f, 68, f, f, f, f, f, f, f, 50, f, f, 56, -94, f, -94, f, 70, 58 },\n { -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, 94, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97, -97 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 95, f, 41, 42 },\n { f, f, f, f, 44, f, -93, f, f, f, f, 52, f, f, f, f, f, 54, 46, 48, 60, f, f, 62, f, f, f, 64, 66, f, f, f, f, 68, f, f, f, f, f, f, f, 50, f, f, 56, -93, f, -93, f, 70, 58 },\n { f, f, f, f, f, f, 97, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 98, f, -90, f, f, f, f, f, f, 99 },\n { f, f, -95, f, -95, -95, f, f, f, f, -95, f, -95, -95, -95, -95, -95, f, f, f, f, f, -95, f, f, f, -95, f, f, -95, f, -95, f, f, f, f, f, f, -95, f, f, f, f, f, f, f, f, -95 },\n { f, f, -96, f, -96, -96, f, f, f, f, -96, f, -96, -96, -96, -96, -96, f, f, f, f, f, -96, f, f, f, -96, f, f, -96, f, -96, f, f, f, f, f, f, -96, f, f, f, f, f, f, f, f, -96 },\n { f, f, 6, f, 7, 8, f, f, f, f, 11, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 93, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, -89, f, f, f, f, f, 32, f, 96, 100, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 101, f, 41, 42 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -91 },\n { f, f, f, f, 44, f, -92, f, f, f, f, 52, f, f, f, f, f, 54, 46, 48, 60, f, f, 62, f, f, f, 64, 66, f, f, f, f, 68, f, f, f, f, f, f, f, 50, f, f, 56, -92, f, -92, f, 70, 58 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 103 },\n { -88, -88, f, -88, -88, -88, -88, -88, -88, -88, -88, -88, -88, -88, f, f, f, -88, -88, -88, -88, -88, f, -88, f, -88, -88, -88, -88, -88, -88, f, f, -88, -88, -88, -88, -88, f, -88, -88, -88, -88, -88, -88, -88, -88, -88, -88, -88, -88 },\n { f, f, f, f, 44, f, f, f, f, f, f, 52, f, f, f, f, f, 54, 46, 48, 60, f, f, 62, f, f, f, 64, 66, f, f, f, f, 68, f, f, f, f, f, f, f, 50, f, 105, 56, f, f, f, f, 70, 58 },\n { -71, -71, f, -71, -71, -71, -71, -71, -71, -71, -71, -71, -71, -71, f, f, f, -71, -71, -71, -71, -71, f, -71, f, -71, -71, -71, -71, -71, -71, f, f, -71, -71, -71, -71, -71, f, -71, -71, -71, -71, -71, -71, -71, -71, -71, -71, -71, -71 },\n { -37, -37, -37, -37, -37, -37, -37, -37, -37, 39, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37, -37 },\n { f, f, f, f, 44, f, f, f, f, f, f, 52, f, f, f, f, f, 54, 46, 48, 60, f, f, 62, f, f, f, 64, 66, f, f, f, f, 68, f, f, f, f, f, f, 108, 50, f, f, 56, f, f, f, f, 70, 58 },\n { -53, f, f, f, f, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, f, f, f, -53, f, f, f, -53, -53, f, f, -53, -53, f, f, f, f, -53, f, f, f, f, -53, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, f, f, 109, f, f, f, f, f, f, f, f, f, 4 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 110 },\n { -75, -75, f, f, f, f, -75, -75, -75, f, f, f, -75, f, f, f, f, f, f, f, f, -75, f, f, f, -75, -75, f, f, -75, -75, f, f, f, -75, -75, -75, -75, f, f, -75, f, f, f, f, f, f, f, -75 },\n { f, -60, 6, f, 7, 8, -60, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, -60, -60, -60, -60, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, 74, f, 112, f, f, f, f, f, 37, f, f, 38, 79, f, 41, 42 },\n { f, -44, f, f, f, f, 113, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -44, -44, -44, -44 },\n { f, -45, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -45, -45, -45, -45 },\n { -53, -53, f, f, f, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, f, f, f, -53, f, f, f, -53, -53, f, f, -53, -53, f, f, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, f, f, 115, f, f, f, f, f, f, f, f, f, 4 },\n { f, 116 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 117, f, 41, 42 },\n { -76, -76, f, f, 44, f, -76, -76, -76, f, f, 52, -76, f, f, f, f, 54, 46, 48, 60, -76, f, 62, f, -76, -76, 64, 66, -76, -76, f, f, 68, -76, -76, -76, -76, f, f, -76, 50, f, f, 56, f, f, f, -76, 70, 58 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 16, f, f, 119, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 124, f, f, f, f, f, f, f, 125 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 16, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 120 },\n { f, f, f, f, f, f, f, f, f, f, f, f, 18, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 121 },\n { -53, f, f, f, f, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, f, f, f, -53, f, f, f, -53, -53, f, f, -53, -53, f, f, f, f, -53, f, f, f, f, -53, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, f, f, 122, f, f, f, f, f, f, f, f, f, 4 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 123 },\n { -84, -84, f, f, f, f, -84, -84, -84, f, f, f, -84, f, f, f, f, f, f, f, f, -84, f, f, f, -84, -84, f, f, -84, -84, f, f, f, -84, -84, -84, -84, f, f, -84, f, f, f, f, f, f, f, -84 },\n { -68, -68, f, f, f, f, -68, -68, -68, f, f, f, -68, f, f, f, f, f, f, f, f, -68, f, f, f, -68, -68, f, f, -68, -68, f, -68, f, -68, -68, -68, -68, f, f, -68, f, f, f, f, -68, f, f, -68 },\n { -82, -82, f, f, f, f, -82, -82, -82, f, f, f, -82, f, f, f, f, f, f, f, f, -82, f, f, f, -82, -82, f, f, -82, -82, f, 126, f, -82, -82, -82, -82, f, f, -82, f, f, f, f, 128, f, f, -82 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, 127, f, f, f, f, f, f, f, 37, f, f, 38, 79, f, 41, 42 },\n { -83, -83, f, f, f, f, -83, -83, -83, f, f, f, -83, f, f, f, f, f, f, f, f, -83, f, f, f, -83, -83, f, f, -83, -83, f, f, f, -83, -83, -83, -83, f, f, -83, f, f, f, f, 75, f, f, -83 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 16, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 129 },\n { -69, -69, f, f, f, f, -69, -69, -69, f, f, f, -69, f, f, f, f, f, f, f, f, -69, f, f, -69, -69, -69, f, f, -69, -69, f, -69, f, -69, -69, -69, -69, f, f, -69, f, f, f, f, -69, f, f, -69 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 131, f, 41, 42 },\n { f, f, f, 132, 44, f, f, f, f, f, f, 52, f, f, f, f, f, 54, 46, 48, 60, f, f, 62, f, f, f, 64, 66, f, f, f, f, 68, f, f, f, f, f, f, f, 50, f, f, 56, f, f, f, f, 70, 58 },\n { -53, f, f, f, f, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, f, f, f, -53, f, f, f, -53, -53, f, f, -53, -53, f, f, f, f, -53, -53, -53, f, f, -53, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, f, f, 133, f, f, f, f, f, f, f, f, f, 4 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -56, -56, -56, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 134 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 135, 136, 140 },\n { -77, -77, f, f, f, f, -77, -77, -77, f, f, f, -77, f, f, f, f, f, f, f, f, -77, f, f, f, -77, -77, f, f, -77, -77, f, f, f, -77, -77, -77, -77, f, f, -77, f, f, f, f, f, f, f, -77 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 137, f, 41, 42 },\n { f, f, f, 138, 44, f, f, f, f, f, f, 52, f, f, f, f, f, 54, 46, 48, 60, f, f, 62, f, f, f, 64, 66, f, f, f, f, 68, f, f, f, f, f, f, f, 50, f, f, 56, f, f, f, f, 70, 58 },\n { -53, f, f, f, f, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, f, f, f, -53, f, f, f, -53, -53, f, f, -53, -53, f, f, f, f, -53, -53, -53, f, f, -53, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, f, f, 139, f, f, f, f, f, f, f, f, f, 4 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -57, -57, -57 },\n { -53, f, f, f, f, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, f, f, f, -53, f, f, f, -53, -53, f, f, -53, -53, f, f, f, f, -53, f, f, f, f, -53, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, f, f, 141, f, f, f, f, f, f, f, f, f, 4 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 142 },\n { -78, -78, f, f, f, f, -78, -78, -78, f, f, f, -78, f, f, f, f, f, f, f, f, -78, f, f, f, -78, -78, f, f, -78, -78, f, f, f, -78, -78, -78, -78, f, f, -78, f, f, f, f, f, f, f, -78 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 16, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 144, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 145 },\n { f, f, f, f, f, f, f, f, f, f, f, f, -40, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -40, f, f, f, f, f, f, -40 },\n { f, f, f, f, f, f, f, f, f, f, f, f, 18, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 146, f, f, f, f, f, f, 148, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 150 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 147 },\n { f, f, f, f, f, f, f, f, f, f, f, f, -41, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -41, f, f, f, f, f, f, -41 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 149 },\n { f, f, f, f, f, f, f, f, f, f, f, f, -42, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -42, f, f, f, f, f, f, -42 },\n { -53, f, f, f, f, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, f, f, f, -53, f, f, f, -53, -53, f, f, -53, -53, f, f, f, f, -53, f, f, f, f, -53, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, f, f, 151, f, f, f, f, f, f, f, f, f, 4 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 152 },\n { -85, -85, f, f, f, f, -85, -85, -85, f, f, f, -85, f, f, f, f, f, f, f, f, -85, f, f, f, -85, -85, f, f, -85, -85, f, f, f, -85, -85, -85, -85, f, f, -85, f, f, f, f, f, f, f, -85 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 16, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 154, f, f, f, f, f, f, f, 167 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -68, f, f, f, f, f, f, f, 155, f, f, f, f, f, f, f, f, f, f, f, f, -68 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 156, f, 41, 42 },\n { f, f, f, f, 44, f, f, f, f, f, f, 52, f, f, f, f, f, 54, 46, 48, 60, f, f, 62, f, f, f, 64, 66, f, f, f, f, 68, f, f, f, f, f, f, f, 50, f, f, 56, 157, f, f, f, 70, 58 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 158, f, 41, 42 },\n { f, f, f, f, 44, f, f, f, f, f, f, 52, f, f, f, f, f, 54, 46, 48, 60, f, f, 62, f, f, f, 64, 66, f, f, f, f, 68, f, f, f, f, f, f, 159, 50, f, f, 56, 162, f, f, f, 70, 58 },\n { -53, f, f, f, f, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, f, f, f, -53, f, f, f, -53, -53, f, f, -53, -53, f, f, f, f, -53, f, f, f, f, -53, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, f, f, 160, f, f, f, f, f, f, f, f, f, 4 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 161 },\n { -79, -79, f, f, f, f, -79, -79, -79, f, f, f, -79, f, f, f, f, f, f, f, f, -79, f, f, f, -79, -79, f, f, -79, -79, f, f, f, -79, -79, -79, -79, f, f, -79, f, f, f, f, f, f, f, -79 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, f, f, f, f, f, f, f, f, 37, f, f, 38, 163, f, 41, 42 },\n { f, f, f, f, 44, f, f, f, f, f, f, 52, f, f, f, f, f, 54, 46, 48, 60, f, f, 62, f, f, f, 64, 66, f, f, f, f, 68, f, f, f, f, f, f, 164, 50, f, f, 56, f, f, f, f, 70, 58 },\n { -53, f, f, f, f, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, f, f, f, -53, f, f, f, -53, -53, f, f, -53, -53, f, f, f, f, -53, f, f, f, f, -53, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, f, f, 165, f, f, f, f, f, f, f, f, f, 4 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 166 },\n { -80, -80, f, f, f, f, -80, -80, -80, f, f, f, -80, f, f, f, f, f, f, f, f, -80, f, f, f, -80, -80, f, f, -80, -80, f, f, f, -80, -80, -80, -80, f, f, -80, f, f, f, f, f, f, f, -80 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 168, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 128 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, 169, f, f, f, f, f, f, f, 37, f, f, 38, 79, f, 41, 42 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 170, f, f, f, f, 75 },\n { -53, f, f, f, f, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, f, f, f, -53, f, f, f, -53, -53, f, f, -53, -53, f, f, f, f, -53, f, f, f, f, -53, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, f, f, 171, f, f, f, f, f, f, f, f, f, 4 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 172 },\n { -81, -81, f, f, f, f, -81, -81, -81, f, f, f, -81, f, f, f, f, f, f, f, f, -81, f, f, f, -81, -81, f, f, -81, -81, f, f, f, -81, -81, -81, -81, f, f, -81, f, f, f, f, f, f, f, -81 },\n { -53, f, f, f, f, f, f, -53, -53, f, f, f, -53, f, f, f, f, f, f, f, f, -53, f, f, f, -53, -53, f, f, -53, -53, f, f, f, f, -53, f, f, f, f, -53, f, f, f, f, f, f, f, -53, f, f, f, f, f, f, f, f, f, 174, f, f, f, f, f, f, f, f, f, 4 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 175 },\n { -73, -73, f, f, f, f, -73, -73, -73, f, f, f, -73, f, f, f, f, f, f, f, f, -73, f, f, f, -73, -73, f, f, -73, -73, f, f, f, -73, -73, -73, -73, f, f, -73, f, f, f, f, f, f, f, -73 },\n { f, -46, f, f, f, f, 177, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -46, -46, -46, -46 },\n { f, -47, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -47, -47, -47, -47 },\n { -54, -54, f, f, f, f, 179, -54, -54, f, f, f, -54, f, f, f, f, f, f, f, f, -54, f, f, f, -54, -54, f, f, -54, -54, f, f, f, -54, -54, -54, -54, f, f, -54, f, f, f, f, f, f, f, -54 },\n { -55, -55, f, f, f, f, f, -55, -55, f, f, f, -55, f, f, f, f, f, f, f, f, -55, f, f, f, -55, -55, f, f, -55, -55, f, f, f, -55, -55, -55, -55, f, f, -55, f, f, f, f, f, f, f, -55 },\n { f, f, f, f, f, 35, f, f, f, f, 36, f, 73, 10, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 80, f, f, f, f, f, f, 82, f, f, f, f, f, f, f, f, f, f, 84, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 86 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 182, f, f, f, f, f, f, f, f, f, f, f, f, 184 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, 183, f, f, f, f, f, f, f, 37, f, f, 38, 79, f, 41, 42 },\n { -74, -74, f, f, f, f, -74, -74, -74, f, f, f, -74, f, f, f, f, f, f, f, f, -74, f, f, f, -74, -74, f, f, -74, -74, f, f, f, -74, -74, -74, -74, f, f, -74, f, f, f, f, 75, f, f, -74 },\n { f, f, f, f, f, f, f, f, f, f, f, f, 9, f, f, f, f, f, f, f, f, f, f, f, f, f, 16, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, f, f, f, 180, f, f, f, f, f, f, f, f, f, f, 185, f, f, f, f, f, 41 },\n { f, f, f, f, f, -70, f, f, f, f, -70, f, -70, -70, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -67, f, f, f, f, f, f, -70, f, f, f, f, f, -67, -70 },\n { f, f, f, f, f, -70, f, f, f, f, -70, f, -70, -70, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -66, f, f, f, f, f, f, -70, f, f, f, f, f, -66, -70 },\n { -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87, -87 },\n { -86, -86, f, f, f, -72, -86, -86, -86, f, -72, f, -72, -72, f, f, f, f, f, f, f, -86, f, f, f, -86, -86, f, f, -86, -86, f, f, f, -86, -86, -86, -86, f, -72, -86, f, f, f, f, f, -72, f, -86 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -1 },\n { f, f, 6, f, 7, 8, f, f, f, f, f, f, 9, 10, 12, 13, 14, f, f, f, f, f, 15, f, f, f, 16, f, f, 17, f, 30, f, f, f, f, f, f, 31, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 32, f, f, f, 33, f, f, 34, f, f, 191, f, f, f, f, f, 193, f, 37, f, f, 38, 79, f, 41, 42 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, 192, f, f, f, f, f, f, f, f, f, f, 75 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -52 },\n { f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, -2 },\n}\n\n--- Run the parser across a sequence of tokens.\n--\n-- @tparam table context The current parser context.\n-- @tparam function get_next A stateful function which returns the next token.\n-- @treturn boolean Whether the parse succeeded or not.\nlocal function parse(context, get_next, start)\n local stack, stack_n = { start or 1, 1, 1 }, 1\n local reduce_stack = {}\n\n while true do\n local token, token_start, token_end = get_next()\n local state = stack[stack_n]\n local action = transitions[state][token]\n\n if not action then -- Error\n return handle_error(context, stack, stack_n, token, token_start, token_end)\n elseif action >= 0 then -- Shift\n stack_n = stack_n + 3\n stack[stack_n], stack[stack_n + 1], stack[stack_n + 2] = action, token_start, token_end\n elseif action >= -2 then -- Accept\n return true\n else -- Reduce\n -- Reduction is quite complex to get right, as the error code expects the parser\n -- to be shifting rather than reducing. Menhir achieves this by making the parser\n -- stack be immutable, but that\'s hard to do efficiently in Lua: instead we track\n -- what symbols we\'ve pushed/popped, and only perform this change when we\'re ready\n -- to shift again.\n\n local popped, pushed = 0, 0\n while true do\n -- Look at the current item to reduce\n local reduce = productions[-action]\n local terminal, to_pop = reduce[1], reduce[2]\n\n -- Find the state at the start of this production. If to_pop == 0\n -- then use the current state.\n local lookback = state\n if to_pop > 0 then\n pushed = pushed - to_pop\n if pushed <= 0 then\n -- If to_pop >= pushed, then clear the reduction stack\n -- and consult the normal stack.\n popped = popped - pushed\n pushed = 0\n lookback = stack[stack_n - popped * 3]\n else\n -- Otherwise consult the stack of temporary reductions.\n lookback = reduce_stack[pushed]\n end\n end\n\n state = transitions[lookback][terminal]\n if not state or state <= 0 then error("reduce must shift!") end\n\n -- And fetch the next action\n action = transitions[state][token]\n\n if not action then -- Error\n return handle_error(context, stack, stack_n, token, token_start, token_end)\n elseif action >= 0 then -- Shift\n break\n elseif action >= -2 then -- Accept\n return true\n else\n pushed = pushed + 1\n reduce_stack[pushed] = state\n end\n end\n\n if popped == 1 and pushed == 0 then\n -- Handle the easy case: Popped one item and replaced it with another\n stack[stack_n] = state\n else\n -- Otherwise pop and push.\n -- FIXME: The positions of everything here are entirely wrong.\n local end_pos = stack[stack_n + 2]\n stack_n = stack_n - popped * 3\n local start_pos = stack[stack_n + 1]\n\n for i = 1, pushed do\n stack_n = stack_n + 3\n stack[stack_n], stack[stack_n + 1], stack[stack_n + 2] = reduce_stack[i], end_pos, end_pos\n end\n\n stack_n = stack_n + 3\n stack[stack_n], stack[stack_n + 1], stack[stack_n + 2] = state, start_pos, end_pos\n end\n\n -- Shift the token onto the stack\n stack_n = stack_n + 3\n stack[stack_n], stack[stack_n + 1], stack[stack_n + 2] = action, token_start, token_end\n end\n end\nend\n\nreturn {\n tokens = tokens,\n parse = parse,\n repl_exprs = 190, --[[- The repl_exprs starting state. ]]\n program = 1, --[[- The program starting state. ]]\n}\n',"rom/modules/main/cc/pretty.lua":'-- SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\n--[[- A pretty printer for rendering data structures in an aesthetically\npleasing manner.\n\nIn order to display something using [`cc.pretty`], you build up a series of\n[documents][`Doc`]. These behave a little bit like strings; you can concatenate\nthem together and then print them to the screen.\n\nHowever, documents also allow you to control how they should be printed. There\nare several functions (such as [`nest`] and [`group`]) which allow you to control\nthe "layout" of the document. When you come to display the document, the \'best\'\n(most compact) layout is used.\n\nThe structure of this module is based on [A Prettier Printer][prettier].\n\n[prettier]: https://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf "A Prettier Printer"\n\n@module cc.pretty\n@since 1.87.0\n@usage Print a table to the terminal\n\n local pretty = require "cc.pretty"\n pretty.pretty_print({ 1, 2, 3 })\n\n@usage Build a custom document and display it\n\n local pretty = require "cc.pretty"\n pretty.print(pretty.group(pretty.text("hello") .. pretty.space_line .. pretty.text("world")))\n]]\n\nlocal expect = require "cc.expect"\nlocal expect, field = expect.expect, expect.field\n\nlocal type, getmetatable, setmetatable, colours, str_write, tostring = type, getmetatable, setmetatable, colours, write, tostring\nlocal debug_info, debug_local = debug.getinfo, debug.getlocal\n\n--- [`table.insert`] alternative, but with the length stored inline.\nlocal function append(out, value)\n local n = out.n + 1\n out[n], out.n = value, n\nend\n\n--- A document containing formatted text, with multiple possible layouts.\n--\n-- Documents effectively represent a sequence of strings in alternative layouts,\n-- which we will try to print in the most compact form necessary.\n--\n-- @type Doc\nlocal Doc = { }\n\nlocal function mk_doc(tbl) return setmetatable(tbl, Doc) end\n\n--- An empty document.\nlocal empty = mk_doc({ tag = "nil" })\n\n--- A document with a single space in it.\nlocal space = mk_doc({ tag = "text", text = " " })\n\n--- A line break. When collapsed with [`group`], this will be replaced with [`empty`].\nlocal line = mk_doc({ tag = "line", flat = empty })\n\n--- A line break. When collapsed with [`group`], this will be replaced with [`space`].\nlocal space_line = mk_doc({ tag = "line", flat = space })\n\nlocal text_cache = { [""] = empty, [" "] = space, ["\\n"] = space_line }\n\nlocal function mk_text(text, colour)\n return text_cache[text] or setmetatable({ tag = "text", text = text, colour = colour }, Doc)\nend\n\n--- Create a new document from a string.\n--\n-- If your string contains multiple lines, [`group`] will flatten the string\n-- into a single line, with spaces between each line.\n--\n-- @tparam string text The string to construct a new document with.\n-- @tparam[opt] number colour The colour this text should be printed with. If not given, we default to the current\n-- colour.\n-- @treturn Doc The document with the provided text.\n-- @usage Write some blue text.\n--\n-- local pretty = require "cc.pretty"\n-- pretty.print(pretty.text("Hello!", colours.blue))\nlocal function text(text, colour)\n expect(1, text, "string")\n expect(2, colour, "number", "nil")\n\n local cached = text_cache[text]\n if cached then return cached end\n\n local new_line = text:find("\\n", 1)\n if not new_line then return mk_text(text, colour) end\n\n -- Split the string by "\\n". With a micro-optimisation to skip empty strings.\n local doc = setmetatable({ tag = "concat", n = 0 }, Doc)\n if new_line ~= 1 then append(doc, mk_text(text:sub(1, new_line - 1), colour)) end\n\n new_line = new_line + 1\n while true do\n local next_line = text:find("\\n", new_line)\n append(doc, space_line)\n if not next_line then\n if new_line <= #text then append(doc, mk_text(text:sub(new_line), colour)) end\n return doc\n else\n if new_line <= next_line - 1 then\n append(doc, mk_text(text:sub(new_line, next_line - 1), colour))\n end\n new_line = next_line + 1\n end\n end\nend\n\n--- Concatenate several documents together. This behaves very similar to string concatenation.\n--\n-- @tparam Doc|string ... The documents to concatenate.\n-- @treturn Doc The concatenated documents.\n-- @usage\n-- local pretty = require "cc.pretty"\n-- local doc1, doc2 = pretty.text("doc1"), pretty.text("doc2")\n-- print(pretty.concat(doc1, " - ", doc2))\n-- print(doc1 .. " - " .. doc2) -- Also supports ..\nlocal function concat(...)\n local args = table.pack(...)\n for i = 1, args.n do\n if type(args[i]) == "string" then args[i] = text(args[i]) end\n if getmetatable(args[i]) ~= Doc then expect(i, args[i], "document") end\n end\n\n if args.n == 0 then return empty end\n if args.n == 1 then return args[1] end\n\n args.tag = "concat"\n return setmetatable(args, Doc)\nend\n\nDoc.__concat = concat --- @local\n\n--- Indent later lines of the given document with the given number of spaces.\n--\n-- For instance, nesting the document\n-- ```txt\n-- foo\n-- bar\n-- ```\n-- by two spaces will produce\n-- ```txt\n-- foo\n-- bar\n-- ```\n--\n-- @tparam number depth The number of spaces with which the document should be indented.\n-- @tparam Doc doc The document to indent.\n-- @treturn Doc The nested document.\n-- @usage\n-- local pretty = require "cc.pretty"\n-- print(pretty.nest(2, pretty.text("foo\\nbar")))\nlocal function nest(depth, doc)\n expect(1, depth, "number")\n if getmetatable(doc) ~= Doc then expect(2, doc, "document") end\n if depth <= 0 then error("depth must be a positive number", 2) end\n\n return setmetatable({ tag = "nest", depth = depth, doc }, Doc)\nend\n\nlocal function flatten(doc)\n if doc.flat then return doc.flat end\n\n local kind = doc.tag\n if kind == "nil" or kind == "text" then\n return doc\n elseif kind == "concat" then\n local out = setmetatable({ tag = "concat", n = doc.n }, Doc)\n for i = 1, doc.n do out[i] = flatten(doc[i]) end\n doc.flat, out.flat = out, out -- cache the flattened node\n return out\n elseif kind == "nest" then\n return flatten(doc[1])\n elseif kind == "group" then\n return doc[1]\n else\n error("Unknown doc " .. kind)\n end\nend\n\n--- Builds a document which is displayed on a single line if there is enough\n-- room, or as normal if not.\n--\n-- @tparam Doc doc The document to group.\n-- @treturn Doc The grouped document.\n-- @usage Uses group to show things being displayed on one or multiple lines.\n--\n-- local pretty = require "cc.pretty"\n-- local doc = pretty.group("Hello" .. pretty.space_line .. "World")\n-- print(pretty.render(doc, 5)) -- On multiple lines\n-- print(pretty.render(doc, 20)) -- Collapsed onto one.\nlocal function group(doc)\n if getmetatable(doc) ~= Doc then expect(1, doc, "document") end\n\n if doc.tag == "group" then return doc end -- Skip if already grouped.\n\n local flattened = flatten(doc)\n if flattened == doc then return doc end -- Also skip if flattening does nothing.\n return setmetatable({ tag = "group", flattened, doc }, Doc)\nend\n\nlocal function get_remaining(doc, width)\n local kind = doc.tag\n if kind == "nil" or kind == "line" then\n return width\n elseif kind == "text" then\n return width - #doc.text\n elseif kind == "concat" then\n for i = 1, doc.n do\n width = get_remaining(doc[i], width)\n if width < 0 then break end\n end\n return width\n elseif kind == "group" or kind == "nest" then\n return get_remaining(kind[1])\n else\n error("Unknown doc " .. kind)\n end\nend\n\n--- Display a document on the terminal.\n--\n-- @tparam Doc doc The document to render\n-- @tparam[opt=0.6] number ribbon_frac The maximum fraction of the width that we should write in.\nlocal function write(doc, ribbon_frac)\n if getmetatable(doc) ~= Doc then expect(1, doc, "document") end\n expect(2, ribbon_frac, "number", "nil")\n\n local term = term\n local width, height = term.getSize()\n local ribbon_width = (ribbon_frac or 0.6) * width\n if ribbon_width < 0 then ribbon_width = 0 end\n if ribbon_width > width then ribbon_width = width end\n\n local def_colour = term.getTextColour()\n local current_colour = def_colour\n\n local function go(doc, indent, col)\n local kind = doc.tag\n if kind == "nil" then\n return col\n elseif kind == "text" then\n local doc_colour = doc.colour or def_colour\n if doc_colour ~= current_colour then\n term.setTextColour(doc_colour)\n current_colour = doc_colour\n end\n\n str_write(doc.text)\n\n return col + #doc.text\n elseif kind == "line" then\n local _, y = term.getCursorPos()\n if y < height then\n term.setCursorPos(indent + 1, y + 1)\n else\n term.scroll(1)\n term.setCursorPos(indent + 1, height)\n end\n\n return indent\n elseif kind == "concat" then\n for i = 1, doc.n do col = go(doc[i], indent, col) end\n return col\n elseif kind == "nest" then\n return go(doc[1], indent + doc.depth, col)\n elseif kind == "group" then\n if get_remaining(doc[1], math.min(width, ribbon_width + indent) - col) >= 0 then\n return go(doc[1], indent, col)\n else\n return go(doc[2], indent, col)\n end\n else\n error("Unknown doc " .. kind)\n end\n end\n\n local col = math.max(term.getCursorPos() - 1, 0)\n go(doc, 0, col)\n if current_colour ~= def_colour then term.setTextColour(def_colour) end\nend\n\n--- Display a document on the terminal with a trailing new line.\n--\n-- @tparam Doc doc The document to render.\n-- @tparam[opt=0.6] number ribbon_frac The maximum fraction of the width that we should write in.\nlocal function print(doc, ribbon_frac)\n if getmetatable(doc) ~= Doc then expect(1, doc, "document") end\n expect(2, ribbon_frac, "number", "nil")\n write(doc, ribbon_frac)\n str_write("\\n")\nend\n\n--- Render a document, converting it into a string.\n--\n-- @tparam Doc doc The document to render.\n-- @tparam[opt] number width The maximum width of this document. Note that long strings will not be wrapped to fit\n-- this width - it is only used for finding the best layout.\n-- @tparam[opt=0.6] number ribbon_frac The maximum fraction of the width that we should write in.\n-- @treturn string The rendered document as a string.\nlocal function render(doc, width, ribbon_frac)\n if getmetatable(doc) ~= Doc then expect(1, doc, "document") end\n expect(2, width, "number", "nil")\n expect(3, ribbon_frac, "number", "nil")\n\n local ribbon_width\n if width then\n ribbon_width = (ribbon_frac or 0.6) * width\n if ribbon_width < 0 then ribbon_width = 0 end\n if ribbon_width > width then ribbon_width = width end\n end\n\n local out = { n = 0 }\n local function go(doc, indent, col)\n local kind = doc.tag\n if kind == "nil" then\n return col\n elseif kind == "text" then\n append(out, doc.text)\n return col + #doc.text\n elseif kind == "line" then\n append(out, "\\n" .. (" "):rep(indent))\n return indent\n elseif kind == "concat" then\n for i = 1, doc.n do col = go(doc[i], indent, col) end\n return col\n elseif kind == "nest" then\n return go(doc[1], indent + doc.depth, col)\n elseif kind == "group" then\n if not width or get_remaining(doc[1], math.min(width, ribbon_width + indent) - col) >= 0 then\n return go(doc[1], indent, col)\n else\n return go(doc[2], indent, col)\n end\n else\n error("Unknown doc " .. kind)\n end\n end\n\n go(doc, 0, 0)\n return table.concat(out, "", 1, out.n)\nend\n\nDoc.__tostring = render --- @local\n\nlocal keywords = {\n ["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true,\n ["elseif"] = true, ["end"] = true, ["false"] = true, ["for"] = true,\n ["function"] = true, ["if"] = true, ["in"] = true, ["local"] = true,\n ["nil"] = true, ["not"] = true, ["or"] = true, ["repeat"] = true, ["return"] = true,\n ["then"] = true, ["true"] = true, ["until"] = true, ["while"] = true,\n }\n\nlocal comma = text(",")\nlocal braces = text("{}")\nlocal obrace, cbrace = text("{"), text("}")\nlocal obracket, cbracket = text("["), text("] = ")\n\nlocal function key_compare(a, b)\n local ta, tb = type(a), type(b)\n\n if ta == "string" then return tb ~= "string" or a < b\n elseif tb == "string" then return false\n end\n\n if ta == "number" then return tb ~= "number" or a < b end\n return false\nend\n\nlocal function show_function(fn, options)\n local info = debug_info and debug_info(fn, "Su")\n\n -- Include function source position if available\n local name\n if options.function_source and info and info.short_src and info.linedefined and info.linedefined >= 1 then\n name = "function<" .. info.short_src .. ":" .. info.linedefined .. ">"\n else\n name = tostring(fn)\n end\n\n -- Include arguments if a Lua function and if available. Lua will report "C"\n -- functions as variadic.\n if options.function_args and info and info.what == "Lua" and info.nparams and debug_local then\n local args = {}\n for i = 1, info.nparams do args[i] = debug_local(fn, i) or "?" end\n if info.isvararg then args[#args + 1] = "..." end\n name = name .. "(" .. table.concat(args, ", ") .. ")"\n end\n\n return name\nend\n\nlocal function pretty_impl(obj, options, tracking)\n local obj_type = type(obj)\n if obj_type == "string" then\n local formatted = ("%q"):format(obj):gsub("\\\\\\n", "\\\\n")\n return text(formatted, colours.red)\n elseif obj_type == "number" then\n return text(tostring(obj), colours.magenta)\n elseif obj_type == "function" then\n return text(show_function(obj, options), colours.lightGrey)\n elseif obj_type ~= "table" or tracking[obj] then\n return text(tostring(obj), colours.lightGrey)\n elseif getmetatable(obj) ~= nil and getmetatable(obj).__tostring then\n return text(tostring(obj))\n elseif next(obj) == nil then\n return braces\n else\n tracking[obj] = true\n local doc = setmetatable({ tag = "concat", n = 1, space_line }, Doc)\n\n local length, keys, keysn = #obj, {}, 1\n for k in pairs(obj) do\n if type(k) ~= "number" or k % 1 ~= 0 or k < 1 or k > length then\n keys[keysn], keysn = k, keysn + 1\n end\n end\n table.sort(keys, key_compare)\n\n for i = 1, length do\n if i > 1 then append(doc, comma) append(doc, space_line) end\n append(doc, pretty_impl(obj[i], options, tracking))\n end\n\n for i = 1, keysn - 1 do\n if i > 1 or length >= 1 then append(doc, comma) append(doc, space_line) end\n\n local k = keys[i]\n local v = obj[k]\n if type(k) == "string" and not keywords[k] and k:match("^[%a_][%a%d_]*$") then\n append(doc, text(k .. " = "))\n append(doc, pretty_impl(v, options, tracking))\n else\n append(doc, obracket)\n append(doc, pretty_impl(k, options, tracking))\n append(doc, cbracket)\n append(doc, pretty_impl(v, options, tracking))\n end\n end\n\n tracking[obj] = nil\n return group(concat(obrace, nest(2, concat(table.unpack(doc, 1, doc.n))), space_line, cbrace))\n end\nend\n\n--- Pretty-print an arbitrary object, converting it into a document.\n--\n-- This can then be rendered with [`write`] or [`print`].\n--\n-- @param obj The object to pretty-print.\n-- @tparam[opt] { function_args = boolean, function_source = boolean } options\n-- Controls how various properties are displayed.\n-- - `function_args`: Show the arguments to a function if known (`false` by default).\n-- - `function_source`: Show where the function was defined, instead of\n-- `function: xxxxxxxx` (`false` by default).\n-- @treturn Doc The object formatted as a document.\n-- @changed 1.88.0 Added `options` argument.\n-- @usage Display a table on the screen\n--\n-- local pretty = require "cc.pretty"\n-- pretty.print(pretty.pretty({ 1, 2, 3 }))\n-- @see pretty_print for a shorthand to prettify and print an object.\nlocal function pretty(obj, options)\n expect(2, options, "table", "nil")\n options = options or {}\n\n local actual_options = {\n function_source = field(options, "function_source", "boolean", "nil") or false,\n function_args = field(options, "function_args", "boolean", "nil") or false,\n }\n return pretty_impl(obj, actual_options, {})\nend\n\n--[[- A shortcut for calling [`pretty`] and [`print`] together.\n\n@param obj The object to pretty-print.\n@tparam[opt] { function_args = boolean, function_source = boolean } options\nControls how various properties are displayed.\n - `function_args`: Show the arguments to a function if known (`false` by default).\n - `function_source`: Show where the function was defined, instead of\n `function: xxxxxxxx` (`false` by default).\n@tparam[opt=0.6] number ribbon_frac The maximum fraction of the width that we should write in.\n\n@usage Display a table on the screen.\n\n local pretty = require "cc.pretty"\n pretty.pretty_print({ 1, 2, 3 })\n\n@see pretty\n@see print\n@since 1.99\n]]\nlocal function pretty_print(obj, options, ribbon_frac)\n expect(2, options, "table", "nil")\n options = options or {}\n expect(3, ribbon_frac, "number", "nil")\n\n return print(pretty(obj, options), ribbon_frac)\nend\n\nreturn {\n empty = empty,\n space = space,\n line = line,\n space_line = space_line,\n text = text,\n concat = concat,\n nest = nest,\n group = group,\n\n write = write,\n print = print,\n render = render,\n\n pretty = pretty,\n\n pretty_print = pretty_print,\n}\n',"rom/modules/main/cc/require.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[- A pure Lua implementation of the builtin [`require`] function and\n[`package`] library.\n\nGenerally you do not need to use this module - it is injected into the every\nprogram\'s environment. However, it may be useful when building a custom shell or\nwhen running programs yourself.\n\n@module cc.require\n@since 1.88.0\n@see using_require For an introduction on how to use [`require`].\n@usage Construct the package and require function, and insert them into a\ncustom environment.\n\n local r = require "cc.require"\n local env = setmetatable({}, { __index = _ENV })\n env.require, env.package = r.make(env, "/")\n\n -- Now we have our own require function, separate to the original.\n local r2 = env.require "cc.require"\n print(r, r2)\n]]\n\nlocal expect = require and require("cc.expect") or dofile("rom/modules/main/cc/expect.lua")\nlocal expect = expect.expect\n\nlocal function preload(package)\n return function(name)\n if package.preload[name] then\n return package.preload[name]\n else\n return nil, "no field package.preload[\'" .. name .. "\']"\n end\n end\nend\n\nlocal function from_file(package, env)\n return function(name)\n local sPath, sError = package.searchpath(name, package.path)\n if not sPath then\n return nil, sError\n end\n local fnFile, sError = loadfile(sPath, nil, env)\n if fnFile then\n return fnFile, sPath\n else\n return nil, sError\n end\n end\nend\n\nlocal function make_searchpath(dir)\n return function(name, path, sep, rep)\n expect(1, name, "string")\n expect(2, path, "string")\n sep = expect(3, sep, "string", "nil") or "."\n rep = expect(4, rep, "string", "nil") or "/"\n\n local fname = string.gsub(name, sep:gsub("%.", "%%%."), rep)\n local sError = ""\n for pattern in string.gmatch(path, "[^;]+") do\n local sPath = string.gsub(pattern, "%?", fname)\n if sPath:sub(1, 1) ~= "/" then\n sPath = fs.combine(dir, sPath)\n end\n if fs.exists(sPath) and not fs.isDir(sPath) then\n return sPath\n else\n if #sError > 0 then\n sError = sError .. "\\n "\n end\n sError = sError .. "no file \'" .. sPath .. "\'"\n end\n end\n return nil, sError\n end\nend\n\nlocal function make_require(package)\n local sentinel = {}\n return function(name)\n expect(1, name, "string")\n\n if package.loaded[name] == sentinel then\n error("loop or previous error loading module \'" .. name .. "\'", 0)\n end\n\n if package.loaded[name] then\n return package.loaded[name]\n end\n\n local sError = "module \'" .. name .. "\' not found:"\n for _, searcher in ipairs(package.loaders) do\n local loader = table.pack(searcher(name))\n if loader[1] then\n package.loaded[name] = sentinel\n local result = loader[1](name, table.unpack(loader, 2, loader.n))\n if result == nil then result = true end\n\n package.loaded[name] = result\n return result\n else\n sError = sError .. "\\n " .. loader[2]\n end\n end\n error(sError, 2)\n end\nend\n\n--- Build an implementation of Lua\'s [`package`] library, and a [`require`]\n-- function to load modules within it.\n--\n-- @tparam table env The environment to load packages into.\n-- @tparam string dir The directory that relative packages are loaded from.\n-- @treturn function The new [`require`] function.\n-- @treturn table The new [`package`] library.\nlocal function make_package(env, dir)\n expect(1, env, "table")\n expect(2, dir, "string")\n\n local package = {}\n package.loaded = {\n _G = _G,\n bit32 = bit32,\n coroutine = coroutine,\n math = math,\n package = package,\n string = string,\n table = table,\n }\n package.path = "?;?.lua;?/init.lua;/rom/modules/main/?;/rom/modules/main/?.lua;/rom/modules/main/?/init.lua"\n if turtle then\n package.path = package.path .. ";/rom/modules/turtle/?;/rom/modules/turtle/?.lua;/rom/modules/turtle/?/init.lua"\n elseif commands then\n package.path = package.path .. ";/rom/modules/command/?;/rom/modules/command/?.lua;/rom/modules/command/?/init.lua"\n end\n package.config = "/\\n;\\n?\\n!\\n-"\n package.preload = {}\n package.loaders = { preload(package), from_file(package, env) }\n package.searchpath = make_searchpath(dir)\n\n return make_require(package), package\nend\n\nreturn { make = make_package }\n',"rom/modules/main/cc/shell/completion.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[- A collection of helper methods for working with shell completion.\n\nMost programs may be completed using the [`build`] helper method, rather than\nmanually switching on the argument index.\n\nNote, the helper functions within this module do not accept an argument index,\nand so are not directly usable with the [`shell.setCompletionFunction`]. Instead,\nwrap them using [`build`], or your own custom function.\n\n@module cc.shell.completion\n@since 1.85.0\n@see cc.completion For more general helpers, suitable for use with [`_G.read`].\n@see shell.setCompletionFunction\n\n@usage Register a completion handler for example.lua which prompts for a\nchoice of options, followed by a directory, and then multiple files.\n\n local completion = require "cc.shell.completion"\n local complete = completion.build(\n { completion.choice, { "get", "put" } },\n completion.dir,\n { completion.file, many = true }\n )\n shell.setCompletionFunction("example.lua", complete)\n read(nil, nil, shell.complete, "example ")\n]]\n\nlocal expect = require "cc.expect".expect\nlocal completion = require "cc.completion"\n\n--- Complete the name of a file relative to the current working directory.\n--\n-- @tparam table shell The shell we\'re completing in.\n-- @tparam string text Current text to complete.\n-- @treturn { string... } A list of suffixes of matching files.\nlocal function file(shell, text)\n return fs.complete(text, shell.dir(), {\n include_files = true,\n include_dirs = false,\n include_hidden = settings.get("shell.autocomplete_hidden"),\n })\nend\n\n--- Complete the name of a directory relative to the current working directory.\n--\n-- @tparam table shell The shell we\'re completing in.\n-- @tparam string text Current text to complete.\n-- @treturn { string... } A list of suffixes of matching directories.\nlocal function dir(shell, text)\n return fs.complete(text, shell.dir(), {\n include_files = false,\n include_dirs = true,\n include_hidden = settings.get("shell.autocomplete_hidden"),\n })\nend\n\n--- Complete the name of a file or directory relative to the current working\n-- directory.\n--\n-- @tparam table shell The shell we\'re completing in.\n-- @tparam string text Current text to complete.\n-- @tparam { string... } previous The shell arguments before this one.\n-- @tparam[opt] boolean add_space Whether to add a space after the completed item.\n-- @treturn { string... } A list of suffixes of matching files and directories.\nlocal function dirOrFile(shell, text, previous, add_space)\n local results = fs.complete(text, shell.dir(), {\n include_files = true,\n include_dirs = true,\n include_hidden = settings.get("shell.autocomplete_hidden"),\n })\n if add_space then\n for n = 1, #results do\n local result = results[n]\n if result:sub(-1) ~= "/" then\n results[n] = result .. " "\n end\n end\n end\n return results\nend\n\nlocal function wrap(func)\n return function(shell, text, previous, ...)\n return func(text, ...)\n end\nend\n\n--- Complete the name of a program.\n--\n-- @tparam table shell The shell we\'re completing in.\n-- @tparam string text Current text to complete.\n-- @treturn { string... } A list of suffixes of matching programs.\n-- @see shell.completeProgram\nlocal function program(shell, text)\n return shell.completeProgram(text)\nend\n\n--- Complete arguments of a program.\n--\n-- @tparam table shell The shell we\'re completing in.\n-- @tparam string text Current text to complete.\n-- @tparam { string... } previous The shell arguments before this one.\n-- @tparam number starting Which argument index this program and args start at.\n-- @treturn { string... } A list of suffixes of matching programs or arguments.\n-- @since 1.97.0\nlocal function programWithArgs(shell, text, previous, starting)\n if #previous + 1 == starting then\n local tCompletionInfo = shell.getCompletionInfo()\n if text:sub(-1) ~= "/" and tCompletionInfo[shell.resolveProgram(text)] then\n return { " " }\n else\n local results = shell.completeProgram(text)\n for n = 1, #results do\n local sResult = results[n]\n if sResult:sub(-1) ~= "/" and tCompletionInfo[shell.resolveProgram(text .. sResult)] then\n results[n] = sResult .. " "\n end\n end\n return results\n end\n else\n local program = previous[starting]\n local resolved = shell.resolveProgram(program)\n if not resolved then return end\n local tCompletion = shell.getCompletionInfo()[resolved]\n if not tCompletion then return end\n return tCompletion.fnComplete(shell, #previous - starting + 1, text, { program, table.unpack(previous, starting + 1, #previous) })\n end\nend\n\n--[[- A helper function for building shell completion arguments.\n\nThis accepts a series of single-argument completion functions, and combines\nthem into a function suitable for use with [`shell.setCompletionFunction`].\n\n@tparam nil|table|function ... Every argument to [`build`] represents an argument\nto the program you wish to complete. Each argument can be one of three types:\n\n - `nil`: This argument will not be completed.\n\n - A function: This argument will be completed with the given function. It is\n called with the [`shell`] object, the string to complete and the arguments\n before this one.\n\n - A table: This acts as a more powerful version of the function case. The table\n must have a function as the first item - this will be called with the shell,\n string and preceding arguments as above, but also followed by any additional\n items in the table. This provides a more convenient interface to pass\n options to your completion functions.\n\n If this table is the last argument, it may also set the `many` key to true,\n which states this function should be used to complete any remaining arguments.\n]]\nlocal function build(...)\n local arguments = table.pack(...)\n for i = 1, arguments.n do\n local arg = arguments[i]\n if arg ~= nil then\n expect(i, arg, "table", "function")\n if type(arg) == "function" then\n arg = { arg }\n arguments[i] = arg\n end\n\n if type(arg[1]) ~= "function" then\n error(("Bad table entry #1 at argument #%d (function expected, got %s)"):format(i, type(arg[1])), 2)\n end\n\n if arg.many and i < arguments.n then\n error(("Unexpected \'many\' field on argument #%d (should only occur on the last argument)"):format(i), 2)\n end\n end\n end\n\n return function(shell, index, text, previous)\n local arg = arguments[index]\n if not arg then\n if index <= arguments.n then return end\n\n arg = arguments[arguments.n]\n if not arg or not arg.many then return end\n end\n\n return arg[1](shell, text, previous, table.unpack(arg, 2))\n end\nend\n\nreturn {\n file = file,\n dir = dir,\n dirOrFile = dirOrFile,\n program = program,\n programWithArgs = programWithArgs,\n\n -- Re-export various other functions\n help = wrap(help.completeTopic), --- Wraps [`help.completeTopic`] as a [`build`] compatible function.\n choice = wrap(completion.choice), --- Wraps [`cc.completion.choice`] as a [`build`] compatible function.\n peripheral = wrap(completion.peripheral), --- Wraps [`cc.completion.peripheral`] as a [`build`] compatible function.\n side = wrap(completion.side), --- Wraps [`cc.completion.side`] as a [`build`] compatible function.\n setting = wrap(completion.setting), --- Wraps [`cc.completion.setting`] as a [`build`] compatible function.\n command = wrap(completion.command), --- Wraps [`cc.completion.command`] as a [`build`] compatible function.\n\n build = build,\n}\n',"rom/modules/main/cc/strings.lua":'-- SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\n--- Various utilities for working with strings and text.\n--\n-- @module cc.strings\n-- @since 1.95.0\n-- @see textutils For additional string related utilities.\n\nlocal expect = (require and require("cc.expect") or dofile("rom/modules/main/cc/expect.lua")).expect\n\n--[[- Wraps a block of text, so that each line fits within the given width.\n\nThis may be useful if you want to wrap text before displaying it to a\n[`monitor`] or [`printer`] without using [print][`_G.print`].\n\n@tparam string text The string to wrap.\n@tparam[opt] number width The width to constrain to, defaults to the width of\nthe terminal.\n@treturn { string... } The wrapped input string as a list of lines.\n@usage Wrap a string and write it to the terminal.\n\n term.clear()\n local lines = require "cc.strings".wrap("This is a long piece of text", 10)\n for i = 1, #lines do\n term.setCursorPos(1, i)\n term.write(lines[i])\n end\n]]\nlocal function wrap(text, width)\n expect(1, text, "string")\n expect(2, width, "number", "nil")\n width = width or term.getSize()\n\n\n local lines, lines_n, current_line = {}, 0, ""\n local function push_line()\n lines_n = lines_n + 1\n lines[lines_n] = current_line\n current_line = ""\n end\n\n local pos, length = 1, #text\n local sub, match = string.sub, string.match\n while pos <= length do\n local head = sub(text, pos, pos)\n if head == " " or head == "\\t" then\n local whitespace = match(text, "^[ \\t]+", pos)\n current_line = current_line .. whitespace\n pos = pos + #whitespace\n elseif head == "\\n" then\n push_line()\n pos = pos + 1\n else\n local word = match(text, "^[^ \\t\\n]+", pos)\n pos = pos + #word\n if #word > width then\n -- Print a multiline word\n while #word > 0 do\n local space_remaining = width - #current_line - 1\n if space_remaining <= 0 then\n push_line()\n space_remaining = width\n end\n\n current_line = current_line .. sub(word, 1, space_remaining)\n word = sub(word, space_remaining + 1)\n end\n else\n -- Print a word normally\n if width - #current_line < #word then push_line() end\n current_line = current_line .. word\n end\n end\n end\n\n push_line()\n\n -- Trim whitespace longer than width.\n for k, line in pairs(lines) do\n line = line:sub(1, width)\n lines[k] = line\n end\n\n return lines\nend\n\n--- Makes the input string a fixed width. This either truncates it, or pads it\n-- with spaces.\n--\n-- @tparam string line The string to normalise.\n-- @tparam[opt] number width The width to constrain to, defaults to the width of\n-- the terminal.\n--\n-- @treturn string The string with a specific width.\n-- @usage require "cc.strings".ensure_width("a short string", 20)\n-- @usage require "cc.strings".ensure_width("a rather long string which is truncated", 20)\nlocal function ensure_width(line, width)\n expect(1, line, "string")\n expect(2, width, "number", "nil")\n width = width or term.getSize()\n\n line = line:sub(1, width)\n if #line < width then\n line = line .. (" "):rep(width - #line)\n end\n\n return line\nend\n\nreturn {\n wrap = wrap,\n ensure_width = ensure_width,\n}\n',"rom/modules/turtle/.ignoreme":'--[[\nAlright then, don\'t ignore me. This file is to ensure the existence of the "modules/turtle" folder.\nYou can use this folder to add modules who can be loaded with require() to your Resourcepack.\n]]\n',"rom/motd.txt":'Please report bugs at https://github.com/cc-tweaked/CC-Tweaked. Thanks!\nView the documentation at https://tweaked.cc\nShow off your programs or ask for help at our forum: https://forums.computercraft.cc\nYou can disable these messages by running "set motd.enable false".\nUse "pastebin put" to upload a program to pastebin.\nUse the "edit" program to create and edit your programs.\nYou can use "wget" to download a file from the internet.\nOn an advanced computer you can use "fg" or "bg" to run multiple programs at the same time.\nUse an advanced computer to use colours and the mouse.\nWith a speaker you can play sounds.\nPrograms that are placed in the "startup" folder in the root of a computer are started on boot.\nUse a modem to connect with other computers.\nWith the "gps" program you can get the position of a computer.\nUse "monitor" to run a program on a attached monitor.\nDon\'t forget to label your computer with "label set".\nFeeling creative? Use a printer to print a book!\nFiles beginning with a "." are hidden from "list" by default.\nRunning "set" lists the current values of all settings.\nSome programs are only available on advanced computers, turtles, pocket computers or command computers.\nThe "equip" programs let you add upgrades to a turtle without crafting.\nYou can change the color of a disk by crafting or right clicking it with dye.\nYou can print on a printed page again to get multiple colors.\nHolding the Ctrl and T keys terminates the running program.\nYou can drag and drop files onto an open computer to upload them.\n',"rom/programs/about.lua":'-- SPDX-FileCopyrightText: 2021 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\nterm.setTextColor(colors.yellow)\nprint(os.version() .. " on " .. _HOST)\nterm.setTextColor(colors.white)\n',"rom/programs/advanced/bg.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif not shell.openTab then\n printError("Requires multishell")\n return\nend\n\nlocal tArgs = { ... }\nif #tArgs > 0 then\n shell.openTab(table.unpack(tArgs))\nelse\n shell.openTab("shell")\nend\n',"rom/programs/advanced/fg.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif not shell.openTab then\n printError("Requires multishell")\n return\nend\n\nlocal tArgs = { ... }\nif #tArgs > 0 then\n local nTask = shell.openTab(table.unpack(tArgs))\n if nTask then\n shell.switchTab(nTask)\n end\nelse\n local nTask = shell.openTab("shell")\n if nTask then\n shell.switchTab(nTask)\n end\nend\n',"rom/programs/advanced/multishell.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--- Multishell allows multiple programs to be run at the same time.\n--\n-- When multiple programs are running, it displays a tab bar at the top of the\n-- screen, which allows you to switch between programs. New programs can be\n-- launched using the `fg` or `bg` programs, or using the [`shell.openTab`] and\n-- [`multishell.launch`] functions.\n--\n-- Each process is identified by its ID, which corresponds to its position in\n-- the tab list. As tabs may be opened and closed, this ID is _not_ constant\n-- over a program\'s run. As such, be careful not to use stale IDs.\n--\n-- As with [`shell`], [`multishell`] is not a "true" API. Instead, it is a\n-- standard program, which launches a shell and injects its API into the shell\'s\n-- environment. This API is not available in the global environment, and so is\n-- not available to [APIs][`os.loadAPI`].\n--\n-- @module[module] multishell\n-- @since 1.6\n\nlocal expect = dofile("rom/modules/main/cc/expect.lua").expect\n\n-- Setup process switching\nlocal parentTerm = term.current()\nlocal w, h = parentTerm.getSize()\n\nlocal tProcesses = {}\nlocal nCurrentProcess = nil\nlocal nRunningProcess = nil\nlocal bShowMenu = false\nlocal bWindowsResized = false\nlocal nScrollPos = 1\nlocal bScrollRight = false\n\nlocal function selectProcess(n)\n if nCurrentProcess ~= n then\n if nCurrentProcess then\n local tOldProcess = tProcesses[nCurrentProcess]\n tOldProcess.window.setVisible(false)\n end\n nCurrentProcess = n\n if nCurrentProcess then\n local tNewProcess = tProcesses[nCurrentProcess]\n tNewProcess.window.setVisible(true)\n tNewProcess.bInteracted = true\n end\n end\nend\n\nlocal function setProcessTitle(n, sTitle)\n tProcesses[n].sTitle = sTitle\nend\n\nlocal function resumeProcess(nProcess, sEvent, ...)\n local tProcess = tProcesses[nProcess]\n local sFilter = tProcess.sFilter\n if sFilter == nil or sFilter == sEvent or sEvent == "terminate" then\n local nPreviousProcess = nRunningProcess\n nRunningProcess = nProcess\n term.redirect(tProcess.terminal)\n local ok, result = coroutine.resume(tProcess.co, sEvent, ...)\n tProcess.terminal = term.current()\n if ok then\n tProcess.sFilter = result\n else\n printError(result)\n end\n nRunningProcess = nPreviousProcess\n end\nend\n\nlocal function launchProcess(bFocus, tProgramEnv, sProgramPath, ...)\n local tProgramArgs = table.pack(...)\n local nProcess = #tProcesses + 1\n local tProcess = {}\n tProcess.sTitle = fs.getName(sProgramPath)\n if bShowMenu then\n tProcess.window = window.create(parentTerm, 1, 2, w, h - 1, false)\n else\n tProcess.window = window.create(parentTerm, 1, 1, w, h, false)\n end\n\n -- Restrict the public view of the window to normal redirect functions.\n tProcess.terminal = {}\n for k in pairs(term.native()) do tProcess.terminal[k] = tProcess.window[k] end\n\n tProcess.co = coroutine.create(function()\n os.run(tProgramEnv, sProgramPath, table.unpack(tProgramArgs, 1, tProgramArgs.n))\n if not tProcess.bInteracted then\n term.setCursorBlink(false)\n print("Press any key to continue")\n os.pullEvent("char")\n end\n end)\n tProcess.sFilter = nil\n tProcess.bInteracted = false\n tProcesses[nProcess] = tProcess\n if bFocus then\n selectProcess(nProcess)\n end\n resumeProcess(nProcess)\n return nProcess\nend\n\nlocal function cullProcess(nProcess)\n local tProcess = tProcesses[nProcess]\n if coroutine.status(tProcess.co) == "dead" then\n if nCurrentProcess == nProcess then\n selectProcess(nil)\n end\n table.remove(tProcesses, nProcess)\n if nCurrentProcess == nil then\n if nProcess > 1 then\n selectProcess(nProcess - 1)\n elseif #tProcesses > 0 then\n selectProcess(1)\n end\n end\n if nScrollPos ~= 1 then\n nScrollPos = nScrollPos - 1\n end\n return true\n end\n return false\nend\n\nlocal function cullProcesses()\n local culled = false\n for n = #tProcesses, 1, -1 do\n culled = culled or cullProcess(n)\n end\n return culled\nend\n\n-- Setup the main menu\nlocal menuMainTextColor, menuMainBgColor, menuOtherTextColor, menuOtherBgColor\nif parentTerm.isColor() then\n menuMainTextColor, menuMainBgColor = colors.yellow, colors.black\n menuOtherTextColor, menuOtherBgColor = colors.black, colors.gray\nelse\n menuMainTextColor, menuMainBgColor = colors.white, colors.black\n menuOtherTextColor, menuOtherBgColor = colors.black, colors.gray\nend\n\nlocal function redrawMenu()\n if bShowMenu then\n -- Draw menu\n parentTerm.setCursorPos(1, 1)\n parentTerm.setBackgroundColor(menuOtherBgColor)\n parentTerm.clearLine()\n local nCharCount = 0\n local nSize = parentTerm.getSize()\n if nScrollPos ~= 1 then\n parentTerm.setTextColor(menuOtherTextColor)\n parentTerm.setBackgroundColor(menuOtherBgColor)\n parentTerm.write("<")\n nCharCount = 1\n end\n for n = nScrollPos, #tProcesses do\n if n == nCurrentProcess then\n parentTerm.setTextColor(menuMainTextColor)\n parentTerm.setBackgroundColor(menuMainBgColor)\n else\n parentTerm.setTextColor(menuOtherTextColor)\n parentTerm.setBackgroundColor(menuOtherBgColor)\n end\n parentTerm.write(" " .. tProcesses[n].sTitle .. " ")\n nCharCount = nCharCount + #tProcesses[n].sTitle + 2\n end\n if nCharCount > nSize then\n parentTerm.setTextColor(menuOtherTextColor)\n parentTerm.setBackgroundColor(menuOtherBgColor)\n parentTerm.setCursorPos(nSize, 1)\n parentTerm.write(">")\n bScrollRight = true\n else\n bScrollRight = false\n end\n\n -- Put the cursor back where it should be\n local tProcess = tProcesses[nCurrentProcess]\n if tProcess then\n tProcess.window.restoreCursor()\n end\n end\nend\n\nlocal function resizeWindows()\n local windowY, windowHeight\n if bShowMenu then\n windowY = 2\n windowHeight = h - 1\n else\n windowY = 1\n windowHeight = h\n end\n for n = 1, #tProcesses do\n local tProcess = tProcesses[n]\n local x, y = tProcess.window.getCursorPos()\n if y > windowHeight then\n tProcess.window.scroll(y - windowHeight)\n tProcess.window.setCursorPos(x, windowHeight)\n end\n tProcess.window.reposition(1, windowY, w, windowHeight)\n end\n bWindowsResized = true\nend\n\nlocal function setMenuVisible(bVis)\n if bShowMenu ~= bVis then\n bShowMenu = bVis\n resizeWindows()\n redrawMenu()\n end\nend\n\nlocal multishell = {} --- @export\n\n--- Get the currently visible process. This will be the one selected on\n-- the tab bar.\n--\n-- Note, this is different to [`getCurrent`], which returns the process which is\n-- currently executing.\n--\n-- @treturn number The currently visible process\'s index.\n-- @see setFocus\nfunction multishell.getFocus()\n return nCurrentProcess\nend\n\n--- Change the currently visible process.\n--\n-- @tparam number n The process index to switch to.\n-- @treturn boolean If the process was changed successfully. This will\n-- return [`false`] if there is no process with this id.\n-- @see getFocus\nfunction multishell.setFocus(n)\n expect(1, n, "number")\n if n >= 1 and n <= #tProcesses then\n selectProcess(n)\n redrawMenu()\n return true\n end\n return false\nend\n\n--- Get the title of the given tab.\n--\n-- This starts as the name of the program, but may be changed using\n-- [`multishell.setTitle`].\n-- @tparam number n The process index.\n-- @treturn string|nil The current process title, or [`nil`] if the\n-- process doesn\'t exist.\nfunction multishell.getTitle(n)\n expect(1, n, "number")\n if n >= 1 and n <= #tProcesses then\n return tProcesses[n].sTitle\n end\n return nil\nend\n\n--- Set the title of the given process.\n--\n-- @tparam number n The process index.\n-- @tparam string title The new process title.\n-- @see getTitle\n-- @usage Change the title of the current process\n--\n-- multishell.setTitle(multishell.getCurrent(), "Hello")\nfunction multishell.setTitle(n, title)\n expect(1, n, "number")\n expect(2, title, "string")\n if n >= 1 and n <= #tProcesses then\n setProcessTitle(n, title)\n redrawMenu()\n end\nend\n\n--- Get the index of the currently running process.\n--\n-- @treturn number The currently running process.\nfunction multishell.getCurrent()\n return nRunningProcess\nend\n\n--- Start a new process, with the given environment, program and arguments.\n--\n-- The returned process index is not constant over the program\'s run. It can be\n-- safely used immediately after launching (for instance, to update the title or\n-- switch to that tab). However, after your program has yielded, it may no\n-- longer be correct.\n--\n-- @tparam table tProgramEnv The environment to load the path under.\n-- @tparam string sProgramPath The path to the program to run.\n-- @param ... Additional arguments to pass to the program.\n-- @treturn number The index of the created process.\n-- @see os.run\n-- @usage Run the "hello" program, and set its title to "Hello!"\n--\n-- local id = multishell.launch({}, "/rom/programs/fun/hello.lua")\n-- multishell.setTitle(id, "Hello!")\nfunction multishell.launch(tProgramEnv, sProgramPath, ...)\n expect(1, tProgramEnv, "table")\n expect(2, sProgramPath, "string")\n local previousTerm = term.current()\n setMenuVisible(#tProcesses + 1 >= 2)\n local nResult = launchProcess(false, tProgramEnv, sProgramPath, ...)\n redrawMenu()\n term.redirect(previousTerm)\n return nResult\nend\n\n--- Get the number of processes within this multishell.\n--\n-- @treturn number The number of processes.\nfunction multishell.getCount()\n return #tProcesses\nend\n\n-- Begin\nparentTerm.clear()\nsetMenuVisible(false)\nlaunchProcess(true, {\n ["shell"] = shell,\n ["multishell"] = multishell,\n}, "/rom/programs/shell.lua")\n\n-- Run processes\nwhile #tProcesses > 0 do\n -- Get the event\n local tEventData = table.pack(os.pullEventRaw())\n local sEvent = tEventData[1]\n if sEvent == "term_resize" then\n -- Resize event\n w, h = parentTerm.getSize()\n resizeWindows()\n redrawMenu()\n\n elseif sEvent == "char" or sEvent == "key" or sEvent == "key_up" or sEvent == "paste" or sEvent == "terminate" or sEvent == "file_transfer" then\n -- Basic input, just passthrough to current process\n resumeProcess(nCurrentProcess, table.unpack(tEventData, 1, tEventData.n))\n if cullProcess(nCurrentProcess) then\n setMenuVisible(#tProcesses >= 2)\n redrawMenu()\n end\n\n elseif sEvent == "mouse_click" then\n -- Click event\n local button, x, y = tEventData[2], tEventData[3], tEventData[4]\n if bShowMenu and y == 1 then\n -- Switch process\n if x == 1 and nScrollPos ~= 1 then\n nScrollPos = nScrollPos - 1\n redrawMenu()\n elseif bScrollRight and x == term.getSize() then\n nScrollPos = nScrollPos + 1\n redrawMenu()\n else\n local tabStart = 1\n if nScrollPos ~= 1 then\n tabStart = 2\n end\n for n = nScrollPos, #tProcesses do\n local tabEnd = tabStart + #tProcesses[n].sTitle + 1\n if x >= tabStart and x <= tabEnd then\n selectProcess(n)\n redrawMenu()\n break\n end\n tabStart = tabEnd + 1\n end\n end\n else\n -- Passthrough to current process\n resumeProcess(nCurrentProcess, sEvent, button, x, bShowMenu and y - 1 or y)\n if cullProcess(nCurrentProcess) then\n setMenuVisible(#tProcesses >= 2)\n redrawMenu()\n end\n end\n\n elseif sEvent == "mouse_drag" or sEvent == "mouse_up" or sEvent == "mouse_scroll" then\n -- Other mouse event\n local p1, x, y = tEventData[2], tEventData[3], tEventData[4]\n if bShowMenu and sEvent == "mouse_scroll" and y == 1 then\n if p1 == -1 and nScrollPos ~= 1 then\n nScrollPos = nScrollPos - 1\n redrawMenu()\n elseif bScrollRight and p1 == 1 then\n nScrollPos = nScrollPos + 1\n redrawMenu()\n end\n elseif not (bShowMenu and y == 1) then\n -- Passthrough to current process\n resumeProcess(nCurrentProcess, sEvent, p1, x, bShowMenu and y - 1 or y)\n if cullProcess(nCurrentProcess) then\n setMenuVisible(#tProcesses >= 2)\n redrawMenu()\n end\n end\n\n else\n -- Other event\n -- Passthrough to all processes\n local nLimit = #tProcesses -- Storing this ensures any new things spawned don\'t get the event\n for n = 1, nLimit do\n resumeProcess(n, table.unpack(tEventData, 1, tEventData.n))\n end\n if cullProcesses() then\n setMenuVisible(#tProcesses >= 2)\n redrawMenu()\n end\n end\n\n if bWindowsResized then\n -- Pass term_resize to all processes\n local nLimit = #tProcesses -- Storing this ensures any new things spawned don\'t get the event\n for n = 1, nLimit do\n resumeProcess(n, "term_resize")\n end\n bWindowsResized = false\n if cullProcesses() then\n setMenuVisible(#tProcesses >= 2)\n redrawMenu()\n end\n end\nend\n\n-- Shutdown\nterm.redirect(parentTerm)\n',"rom/programs/alias.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\nif #tArgs > 2 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <alias> <program>")\n return\nend\n\nlocal sAlias = tArgs[1]\nlocal sProgram = tArgs[2]\n\nif sAlias and sProgram then\n -- Set alias\n shell.setAlias(sAlias, sProgram)\nelseif sAlias then\n -- Clear alias\n shell.clearAlias(sAlias)\nelse\n -- List aliases\n local tAliases = shell.aliases()\n local tList = {}\n for sAlias, sCommand in pairs(tAliases) do\n table.insert(tList, sAlias .. ":" .. sCommand)\n end\n table.sort(tList)\n textutils.pagedTabulate(tList)\nend\n',"rom/programs/apis.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tApis = {}\nfor k, v in pairs(_G) do\n if type(k) == "string" and type(v) == "table" and k ~= "_G" then\n table.insert(tApis, k)\n end\nend\ntable.insert(tApis, "shell")\ntable.insert(tApis, "package")\nif multishell then\n table.insert(tApis, "multishell")\nend\ntable.sort(tApis)\n\ntextutils.pagedTabulate(tApis)\n',"rom/programs/cd.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\nif #tArgs < 1 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <path>")\n return\nend\n\nlocal sNewDir = shell.resolve(tArgs[1])\nif fs.isDir(sNewDir) then\n shell.setDir(sNewDir)\nelse\n print("Not a directory")\n return\nend\n',"rom/programs/clear.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\n\nlocal function printUsage()\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usages:")\n print(programName)\n print(programName .. " screen")\n print(programName .. " palette")\n print(programName .. " all")\nend\n\nlocal function clear()\n term.clear()\n term.setCursorPos(1, 1)\nend\n\nlocal function resetPalette()\n for i = 0, 15 do\n term.setPaletteColour(math.pow(2, i), term.nativePaletteColour(math.pow(2, i)))\n end\nend\n\nlocal sCommand = tArgs[1] or "screen"\nif sCommand == "screen" then\n clear()\nelseif sCommand == "palette" then\n resetPalette()\nelseif sCommand == "all" then\n clear()\n resetPalette()\nelse\n printUsage()\nend\n',"rom/programs/command/commands.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif not commands then\n printError("Requires a Command Computer.")\n return\nend\n\nlocal tCommands = commands.list()\ntable.sort(tCommands)\n\nif term.isColor() then\n term.setTextColor(colors.green)\nend\nprint("Available commands:")\nterm.setTextColor(colors.white)\n\ntextutils.pagedTabulate(tCommands)\n',"rom/programs/command/exec.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\nif not commands then\n printError("Requires a Command Computer.")\n return\nend\nif #tArgs == 0 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n printError("Usage: " .. programName .. " <command>")\n return\nend\n\nlocal function printSuccess(text)\n if term.isColor() then\n term.setTextColor(colors.green)\n end\n print(text)\n term.setTextColor(colors.white)\nend\n\nlocal sCommand = string.lower(tArgs[1])\nfor n = 2, #tArgs do\n sCommand = sCommand .. " " .. tArgs[n]\nend\n\nlocal bResult, tOutput = commands.exec(sCommand)\nif bResult then\n printSuccess("Success")\n if #tOutput > 0 then\n for n = 1, #tOutput do\n print(tOutput[n])\n end\n end\nelse\n printError("Failed")\n if #tOutput > 0 then\n for n = 1, #tOutput do\n print(tOutput[n])\n end\n end\nend\n',"rom/programs/copy.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\nif #tArgs < 2 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <source> <destination>")\n return\nend\n\nlocal sSource = shell.resolve(tArgs[1])\nlocal sDest = shell.resolve(tArgs[2])\nlocal tFiles = fs.find(sSource)\nif #tFiles > 0 then\n for _, sFile in ipairs(tFiles) do\n if fs.isDir(sDest) then\n fs.copy(sFile, fs.combine(sDest, fs.getName(sFile)))\n elseif #tFiles == 1 then\n if fs.exists(sDest) then\n printError("Destination exists")\n elseif fs.isReadOnly(sDest) then\n printError("Destination is read-only")\n elseif fs.getFreeSpace(sDest) < fs.getSize(sFile) then\n printError("Not enough space")\n else\n fs.copy(sFile, sDest)\n end\n else\n printError("Cannot overwrite file multiple times")\n return\n end\n end\nelse\n printError("No matching files")\nend\n',"rom/programs/delete.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal args = table.pack(...)\n\nif args.n < 1 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <paths>")\n return\nend\n\nfor i = 1, args.n do\n local files = fs.find(shell.resolve(args[i]))\n if #files > 0 then\n for _, file in ipairs(files) do\n if fs.isReadOnly(file) then\n printError("Cannot delete read-only file /" .. file)\n elseif fs.isDriveRoot(file) then\n printError("Cannot delete mount /" .. file)\n if fs.isDir(file) then\n print("To delete its contents run rm /" .. fs.combine(file, "*"))\n end\n else\n local ok, err = pcall(fs.delete, file)\n if not ok then\n printError((err:gsub("^pcall: ", "")))\n end\n end\n end\n else\n printError(args[i] .. ": No matching files")\n end\nend\n',"rom/programs/drive.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\n\n-- Get where a directory is mounted\nlocal sPath = shell.dir()\nif tArgs[1] ~= nil then\n sPath = shell.resolve(tArgs[1])\nend\n\nif fs.exists(sPath) then\n write(fs.getDrive(sPath) .. " (")\n local nSpace = fs.getFreeSpace(sPath)\n if nSpace >= 1000 * 1000 then\n print(math.floor(nSpace / (100 * 1000)) / 10 .. "MB remaining)")\n elseif nSpace >= 1000 then\n print(math.floor(nSpace / 100) / 10 .. "KB remaining)")\n else\n print(nSpace .. "B remaining)")\n end\nelse\n print("No such path")\nend\n',"rom/programs/edit.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n-- Get file to edit\nlocal tArgs = { ... }\nif #tArgs == 0 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <path>")\n return\nend\n\n-- Error checking\nlocal sPath = shell.resolve(tArgs[1])\nlocal bReadOnly = fs.isReadOnly(sPath)\nif fs.exists(sPath) and fs.isDir(sPath) then\n print("Cannot edit a directory.")\n return\nend\n\n-- Create .lua files by default\nif not fs.exists(sPath) and not string.find(sPath, "%.") then\n local sExtension = settings.get("edit.default_extension")\n if sExtension ~= "" and type(sExtension) == "string" then\n sPath = sPath .. "." .. sExtension\n end\nend\n\nlocal x, y = 1, 1\nlocal w, h = term.getSize()\nlocal scrollX, scrollY = 0, 0\n\nlocal tLines = {}\nlocal bRunning = true\n\n-- Colours\nlocal highlightColour, keywordColour, commentColour, textColour, bgColour, stringColour, errorColour\nif term.isColour() then\n bgColour = colours.black\n textColour = colours.white\n highlightColour = colours.yellow\n keywordColour = colours.yellow\n commentColour = colours.green\n stringColour = colours.red\n errorColour = colours.red\nelse\n bgColour = colours.black\n textColour = colours.white\n highlightColour = colours.white\n keywordColour = colours.white\n commentColour = colours.white\n stringColour = colours.white\n errorColour = colours.white\nend\n\nlocal runHandler = [[multishell.setTitle(multishell.getCurrent(), %q)\nlocal current = term.current()\nlocal contents, name = %q, %q\nlocal fn, err = load(contents, name, nil, _ENV)\nif fn then\n local exception = require "cc.internal.exception"\n local ok, err, co = exception.try(fn, ...)\n\n term.redirect(current)\n term.setTextColor(term.isColour() and colours.yellow or colours.white)\n term.setBackgroundColor(colours.black)\n term.setCursorBlink(false)\n\n if not ok then\n printError(err)\n exception.report(err, co, { [name] = contents })\n end\nelse\n local parser = require "cc.internal.syntax"\n if parser.parse_program(contents) then printError(err) end\nend\n\nlocal message = "Press any key to continue."\nif ok then message = "Program finished. " .. message end\nlocal _, y = term.getCursorPos()\nlocal w, h = term.getSize()\nlocal wrapped = require("cc.strings").wrap(message, w)\n\nlocal start_y = h - #wrapped + 1\nif y >= start_y then term.scroll(y - start_y + 1) end\nfor i = 1, #wrapped do\n term.setCursorPos(1, start_y + i - 1)\n term.write(wrapped[i])\nend\nos.pullEvent(\'key\')\n]]\n\n-- Menus\nlocal bMenu = false\nlocal nMenuItem = 1\nlocal tMenuItems = {}\nif not bReadOnly then\n table.insert(tMenuItems, "Save")\nend\nif shell.openTab then\n table.insert(tMenuItems, "Run")\nend\nif peripheral.find("printer") then\n table.insert(tMenuItems, "Print")\nend\ntable.insert(tMenuItems, "Exit")\n\nlocal status_ok, status_text\nlocal function set_status(text, ok)\n status_ok = ok ~= false\n status_text = text\nend\n\nif bReadOnly then\n set_status("File is read only", false)\nelseif fs.getFreeSpace(sPath) < 1024 then\n set_status("Disk is low on space", false)\nelse\n local message\n if term.isColour() then\n message = "Press Ctrl or click here to access menu"\n else\n message = "Press Ctrl to access menu"\n end\n\n if #message > w - 5 then\n message = "Press Ctrl for menu"\n end\n\n set_status(message)\nend\n\nlocal function load(_sPath)\n tLines = {}\n if fs.exists(_sPath) then\n local file = io.open(_sPath, "r")\n local sLine = file:read()\n while sLine do\n table.insert(tLines, sLine)\n sLine = file:read()\n end\n file:close()\n end\n\n if #tLines == 0 then\n table.insert(tLines, "")\n end\nend\n\nlocal function save(_sPath, fWrite)\n -- Create intervening folder\n local sDir = _sPath:sub(1, _sPath:len() - fs.getName(_sPath):len())\n if not fs.exists(sDir) then\n fs.makeDir(sDir)\n end\n\n -- Save\n local file, fileerr\n local function innerSave()\n file, fileerr = fs.open(_sPath, "w")\n if file then\n if file then\n fWrite(file)\n end\n else\n error("Failed to open " .. _sPath)\n end\n end\n\n local ok, err = pcall(innerSave)\n if file then\n file.close()\n end\n return ok, err, fileerr\nend\n\nlocal tKeywords = {\n ["and"] = true,\n ["break"] = true,\n ["do"] = true,\n ["else"] = true,\n ["elseif"] = true,\n ["end"] = true,\n ["false"] = true,\n ["for"] = true,\n ["function"] = true,\n ["if"] = true,\n ["in"] = true,\n ["local"] = true,\n ["nil"] = true,\n ["not"] = true,\n ["or"] = true,\n ["repeat"] = true,\n ["return"] = true,\n ["then"] = true,\n ["true"] = true,\n ["until"] = true,\n ["while"] = true,\n}\n\nlocal function tryWrite(sLine, regex, colour)\n local match = string.match(sLine, regex)\n if match then\n if type(colour) == "number" then\n term.setTextColour(colour)\n else\n term.setTextColour(colour(match))\n end\n term.write(match)\n term.setTextColour(textColour)\n return string.sub(sLine, #match + 1)\n end\n return nil\nend\n\nlocal function writeHighlighted(sLine)\n while #sLine > 0 do\n sLine =\n tryWrite(sLine, "^%-%-%[%[.-%]%]", commentColour) or\n tryWrite(sLine, "^%-%-.*", commentColour) or\n tryWrite(sLine, "^\\"\\"", stringColour) or\n tryWrite(sLine, "^\\".-[^\\\\]\\"", stringColour) or\n tryWrite(sLine, "^\\\'\\\'", stringColour) or\n tryWrite(sLine, "^\\\'.-[^\\\\]\\\'", stringColour) or\n tryWrite(sLine, "^%[%[.-%]%]", stringColour) or\n tryWrite(sLine, "^[%w_]+", function(match)\n if tKeywords[match] then\n return keywordColour\n end\n return textColour\n end) or\n tryWrite(sLine, "^[^%w_]", textColour)\n end\nend\n\nlocal tCompletions\nlocal nCompletion\n\nlocal tCompleteEnv = _ENV\nlocal function complete(sLine)\n if settings.get("edit.autocomplete") then\n local nStartPos = string.find(sLine, "[a-zA-Z0-9_%.:]+$")\n if nStartPos then\n sLine = string.sub(sLine, nStartPos)\n end\n if #sLine > 0 then\n return textutils.complete(sLine, tCompleteEnv)\n end\n end\n return nil\nend\n\nlocal function recomplete()\n local sLine = tLines[y]\n if not bMenu and not bReadOnly and x == #sLine + 1 then\n tCompletions = complete(sLine)\n if tCompletions and #tCompletions > 0 then\n nCompletion = 1\n else\n nCompletion = nil\n end\n else\n tCompletions = nil\n nCompletion = nil\n end\nend\n\nlocal function writeCompletion(sLine)\n if nCompletion then\n local sCompletion = tCompletions[nCompletion]\n term.setTextColor(colours.white)\n term.setBackgroundColor(colours.grey)\n term.write(sCompletion)\n term.setTextColor(textColour)\n term.setBackgroundColor(bgColour)\n end\nend\n\nlocal function redrawText()\n local cursorX, cursorY = x, y\n for y = 1, h - 1 do\n term.setCursorPos(1 - scrollX, y)\n term.clearLine()\n\n local sLine = tLines[y + scrollY]\n if sLine ~= nil then\n writeHighlighted(sLine)\n if cursorY == y and cursorX == #sLine + 1 then\n writeCompletion()\n end\n end\n end\n term.setCursorPos(x - scrollX, y - scrollY)\nend\n\nlocal function redrawLine(_nY)\n local sLine = tLines[_nY]\n if sLine then\n term.setCursorPos(1 - scrollX, _nY - scrollY)\n term.clearLine()\n writeHighlighted(sLine)\n if _nY == y and x == #sLine + 1 then\n writeCompletion()\n end\n term.setCursorPos(x - scrollX, _nY - scrollY)\n end\nend\n\nlocal function redrawMenu()\n -- Clear line\n term.setCursorPos(1, h)\n term.clearLine()\n\n -- Draw line numbers\n term.setCursorPos(w - #("Ln " .. y) + 1, h)\n term.setTextColour(highlightColour)\n term.write("Ln ")\n term.setTextColour(textColour)\n term.write(y)\n\n term.setCursorPos(1, h)\n if bMenu then\n -- Draw menu\n term.setTextColour(textColour)\n for nItem, sItem in pairs(tMenuItems) do\n if nItem == nMenuItem then\n term.setTextColour(highlightColour)\n term.write("[")\n term.setTextColour(textColour)\n term.write(sItem)\n term.setTextColour(highlightColour)\n term.write("]")\n term.setTextColour(textColour)\n else\n term.write(" " .. sItem .. " ")\n end\n end\n else\n -- Draw status\n term.setTextColour(status_ok and highlightColour or errorColour)\n term.write(status_text)\n term.setTextColour(textColour)\n end\n\n -- Reset cursor\n term.setCursorPos(x - scrollX, y - scrollY)\nend\n\nlocal tMenuFuncs = {\n Save = function()\n if bReadOnly then\n set_status("Access denied", false)\n else\n local ok, _, fileerr = save(sPath, function(file)\n for _, sLine in ipairs(tLines) do\n file.write(sLine .. "\\n")\n end\n end)\n if ok then\n set_status("Saved to " .. sPath)\n else\n if fileerr then\n set_status("Error saving: " .. fileerr, false)\n else\n set_status("Error saving to " .. sPath, false)\n end\n end\n end\n redrawMenu()\n end,\n Print = function()\n local printer = peripheral.find("printer")\n if not printer then\n set_status("No printer attached", false)\n return\n end\n\n local nPage = 0\n local sName = fs.getName(sPath)\n if printer.getInkLevel() < 1 then\n set_status("Printer out of ink", false)\n return\n elseif printer.getPaperLevel() < 1 then\n set_status("Printer out of paper", false)\n return\n end\n\n local screenTerminal = term.current()\n local printerTerminal = {\n getCursorPos = printer.getCursorPos,\n setCursorPos = printer.setCursorPos,\n getSize = printer.getPageSize,\n write = printer.write,\n }\n printerTerminal.scroll = function()\n if nPage == 1 then\n printer.setPageTitle(sName .. " (page " .. nPage .. ")")\n end\n\n while not printer.newPage() do\n if printer.getInkLevel() < 1 then\n set_status("Printer out of ink, please refill", false)\n elseif printer.getPaperLevel() < 1 then\n set_status("Printer out of paper, please refill", false)\n else\n set_status("Printer output tray full, please empty", false)\n end\n\n term.redirect(screenTerminal)\n redrawMenu()\n term.redirect(printerTerminal)\n\n sleep(0.5)\n end\n\n nPage = nPage + 1\n if nPage == 1 then\n printer.setPageTitle(sName)\n else\n printer.setPageTitle(sName .. " (page " .. nPage .. ")")\n end\n end\n\n bMenu = false\n term.redirect(printerTerminal)\n local ok, error = pcall(function()\n term.scroll()\n for _, sLine in ipairs(tLines) do\n print(sLine)\n end\n end)\n term.redirect(screenTerminal)\n if not ok then\n print(error)\n end\n\n while not printer.endPage() do\n set_status("Printer output tray full, please empty")\n redrawMenu()\n sleep(0.5)\n end\n bMenu = true\n\n if nPage > 1 then\n set_status("Printed " .. nPage .. " Pages")\n else\n set_status("Printed 1 Page")\n end\n redrawMenu()\n end,\n Exit = function()\n bRunning = false\n end,\n Run = function()\n local sTitle = fs.getName(sPath)\n if sTitle:sub(-4) == ".lua" then\n sTitle = sTitle:sub(1, -5)\n end\n local sTempPath = bReadOnly and ".temp." .. sTitle or fs.combine(fs.getDir(sPath), ".temp." .. sTitle)\n if fs.exists(sTempPath) then\n set_status("Error saving to " .. sTempPath, false)\n return\n end\n local ok = save(sTempPath, function(file)\n file.write(runHandler:format(sTitle, table.concat(tLines, "\\n"), "@/" .. sPath))\n end)\n if ok then\n local nTask = shell.openTab("/" .. sTempPath)\n if nTask then\n shell.switchTab(nTask)\n else\n set_status("Error starting Task", false)\n end\n fs.delete(sTempPath)\n else\n set_status("Error saving to " .. sTempPath, false)\n end\n redrawMenu()\n end,\n}\n\nlocal function doMenuItem(_n)\n tMenuFuncs[tMenuItems[_n]]()\n if bMenu then\n bMenu = false\n term.setCursorBlink(true)\n end\n redrawMenu()\nend\n\nlocal function setCursor(newX, newY)\n local _, oldY = x, y\n x, y = newX, newY\n local screenX = x - scrollX\n local screenY = y - scrollY\n\n local bRedraw = false\n if screenX < 1 then\n scrollX = x - 1\n screenX = 1\n bRedraw = true\n elseif screenX > w then\n scrollX = x - w\n screenX = w\n bRedraw = true\n end\n\n if screenY < 1 then\n scrollY = y - 1\n screenY = 1\n bRedraw = true\n elseif screenY > h - 1 then\n scrollY = y - (h - 1)\n screenY = h - 1\n bRedraw = true\n end\n\n recomplete()\n if bRedraw then\n redrawText()\n elseif y ~= oldY then\n redrawLine(oldY)\n redrawLine(y)\n else\n redrawLine(y)\n end\n term.setCursorPos(screenX, screenY)\n\n redrawMenu()\nend\n\n-- Actual program functionality begins\nload(sPath)\n\nterm.setBackgroundColour(bgColour)\nterm.clear()\nterm.setCursorPos(x, y)\nterm.setCursorBlink(true)\n\nrecomplete()\nredrawText()\nredrawMenu()\n\nlocal function acceptCompletion()\n if nCompletion then\n -- Append the completion\n local sCompletion = tCompletions[nCompletion]\n tLines[y] = tLines[y] .. sCompletion\n setCursor(x + #sCompletion , y)\n end\nend\n\n-- Handle input\nwhile bRunning do\n local sEvent, param, param2, param3 = os.pullEvent()\n if sEvent == "key" then\n if param == keys.up then\n -- Up\n if not bMenu then\n if nCompletion then\n -- Cycle completions\n nCompletion = nCompletion - 1\n if nCompletion < 1 then\n nCompletion = #tCompletions\n end\n redrawLine(y)\n\n elseif y > 1 then\n -- Move cursor up\n setCursor(\n math.min(x, #tLines[y - 1] + 1),\n y - 1\n )\n end\n end\n\n elseif param == keys.down then\n -- Down\n if not bMenu then\n -- Move cursor down\n if nCompletion then\n -- Cycle completions\n nCompletion = nCompletion + 1\n if nCompletion > #tCompletions then\n nCompletion = 1\n end\n redrawLine(y)\n\n elseif y < #tLines then\n -- Move cursor down\n setCursor(\n math.min(x, #tLines[y + 1] + 1),\n y + 1\n )\n end\n end\n\n elseif param == keys.tab then\n -- Tab\n if not bMenu and not bReadOnly then\n if nCompletion and x == #tLines[y] + 1 then\n -- Accept autocomplete\n acceptCompletion()\n else\n -- Indent line\n local sLine = tLines[y]\n tLines[y] = string.sub(sLine, 1, x - 1) .. " " .. string.sub(sLine, x)\n setCursor(x + 4, y)\n end\n end\n\n elseif param == keys.pageUp then\n -- Page Up\n if not bMenu then\n -- Move up a page\n local newY\n if y - (h - 1) >= 1 then\n newY = y - (h - 1)\n else\n newY = 1\n end\n setCursor(\n math.min(x, #tLines[newY] + 1),\n newY\n )\n end\n\n elseif param == keys.pageDown then\n -- Page Down\n if not bMenu then\n -- Move down a page\n local newY\n if y + (h - 1) <= #tLines then\n newY = y + (h - 1)\n else\n newY = #tLines\n end\n local newX = math.min(x, #tLines[newY] + 1)\n setCursor(newX, newY)\n end\n\n elseif param == keys.home then\n -- Home\n if not bMenu then\n -- Move cursor to the beginning\n if x > 1 then\n setCursor(1, y)\n end\n end\n\n elseif param == keys["end"] then\n -- End\n if not bMenu then\n -- Move cursor to the end\n local nLimit = #tLines[y] + 1\n if x < nLimit then\n setCursor(nLimit, y)\n end\n end\n\n elseif param == keys.left then\n -- Left\n if not bMenu then\n if x > 1 then\n -- Move cursor left\n setCursor(x - 1, y)\n elseif x == 1 and y > 1 then\n setCursor(#tLines[y - 1] + 1, y - 1)\n end\n else\n -- Move menu left\n nMenuItem = nMenuItem - 1\n if nMenuItem < 1 then\n nMenuItem = #tMenuItems\n end\n redrawMenu()\n end\n\n elseif param == keys.right then\n -- Right\n if not bMenu then\n local nLimit = #tLines[y] + 1\n if x < nLimit then\n -- Move cursor right\n setCursor(x + 1, y)\n elseif nCompletion and x == #tLines[y] + 1 then\n -- Accept autocomplete\n acceptCompletion()\n elseif x == nLimit and y < #tLines then\n -- Go to next line\n setCursor(1, y + 1)\n end\n else\n -- Move menu right\n nMenuItem = nMenuItem + 1\n if nMenuItem > #tMenuItems then\n nMenuItem = 1\n end\n redrawMenu()\n end\n\n elseif param == keys.delete then\n -- Delete\n if not bMenu and not bReadOnly then\n local nLimit = #tLines[y] + 1\n if x < nLimit then\n local sLine = tLines[y]\n tLines[y] = string.sub(sLine, 1, x - 1) .. string.sub(sLine, x + 1)\n recomplete()\n redrawLine(y)\n elseif y < #tLines then\n tLines[y] = tLines[y] .. tLines[y + 1]\n table.remove(tLines, y + 1)\n recomplete()\n redrawText()\n end\n end\n\n elseif param == keys.backspace then\n -- Backspace\n if not bMenu and not bReadOnly then\n if x > 1 then\n -- Remove character\n local sLine = tLines[y]\n if x > 4 and string.sub(sLine, x - 4, x - 1) == " " and not string.sub(sLine, 1, x - 1):find("%S") then\n tLines[y] = string.sub(sLine, 1, x - 5) .. string.sub(sLine, x)\n setCursor(x - 4, y)\n else\n tLines[y] = string.sub(sLine, 1, x - 2) .. string.sub(sLine, x)\n setCursor(x - 1, y)\n end\n elseif y > 1 then\n -- Remove newline\n local sPrevLen = #tLines[y - 1]\n tLines[y - 1] = tLines[y - 1] .. tLines[y]\n table.remove(tLines, y)\n setCursor(sPrevLen + 1, y - 1)\n redrawText()\n end\n end\n\n elseif param == keys.enter or param == keys.numPadEnter then\n -- Enter/Numpad Enter\n if not bMenu and not bReadOnly then\n -- Newline\n local sLine = tLines[y]\n local _, spaces = string.find(sLine, "^[ ]+")\n if not spaces then\n spaces = 0\n end\n tLines[y] = string.sub(sLine, 1, x - 1)\n table.insert(tLines, y + 1, string.rep(\' \', spaces) .. string.sub(sLine, x))\n setCursor(spaces + 1, y + 1)\n redrawText()\n\n elseif bMenu then\n -- Menu selection\n doMenuItem(nMenuItem)\n\n end\n\n elseif param == keys.leftCtrl or param == keys.rightCtrl then\n -- Menu toggle\n bMenu = not bMenu\n if bMenu then\n term.setCursorBlink(false)\n else\n term.setCursorBlink(true)\n end\n redrawMenu()\n elseif param == keys.rightAlt then\n if bMenu then\n bMenu = false\n term.setCursorBlink(true)\n redrawMenu()\n end\n end\n\n elseif sEvent == "char" then\n if not bMenu and not bReadOnly then\n -- Input text\n local sLine = tLines[y]\n tLines[y] = string.sub(sLine, 1, x - 1) .. param .. string.sub(sLine, x)\n setCursor(x + 1, y)\n\n elseif bMenu then\n -- Select menu items\n for n, sMenuItem in ipairs(tMenuItems) do\n if string.lower(string.sub(sMenuItem, 1, 1)) == string.lower(param) then\n doMenuItem(n)\n break\n end\n end\n end\n\n elseif sEvent == "paste" then\n if not bReadOnly then\n -- Close menu if open\n if bMenu then\n bMenu = false\n term.setCursorBlink(true)\n redrawMenu()\n end\n -- Input text\n local sLine = tLines[y]\n tLines[y] = string.sub(sLine, 1, x - 1) .. param .. string.sub(sLine, x)\n setCursor(x + #param , y)\n end\n\n elseif sEvent == "mouse_click" then\n local cx, cy = param2, param3\n if not bMenu then\n if param == 1 then\n -- Left click\n if cy < h then\n local newY = math.min(math.max(scrollY + cy, 1), #tLines)\n local newX = math.min(math.max(scrollX + cx, 1), #tLines[newY] + 1)\n setCursor(newX, newY)\n else\n bMenu = true\n redrawMenu()\n end\n end\n else\n if cy == h then\n local nMenuPosEnd = 1\n local nMenuPosStart = 1\n for n, sMenuItem in ipairs(tMenuItems) do\n nMenuPosEnd = nMenuPosEnd + #sMenuItem + 1\n if cx > nMenuPosStart and cx < nMenuPosEnd then\n doMenuItem(n)\n end\n nMenuPosEnd = nMenuPosEnd + 1\n nMenuPosStart = nMenuPosEnd\n end\n else\n bMenu = false\n term.setCursorBlink(true)\n redrawMenu()\n end\n end\n\n elseif sEvent == "mouse_scroll" then\n if not bMenu then\n if param == -1 then\n -- Scroll up\n if scrollY > 0 then\n -- Move cursor up\n scrollY = scrollY - 1\n redrawText()\n end\n\n elseif param == 1 then\n -- Scroll down\n local nMaxScroll = #tLines - (h - 1)\n if scrollY < nMaxScroll then\n -- Move cursor down\n scrollY = scrollY + 1\n redrawText()\n end\n\n end\n end\n\n elseif sEvent == "term_resize" then\n w, h = term.getSize()\n setCursor(x, y)\n redrawMenu()\n redrawText()\n\n end\nend\n\n-- Cleanup\nterm.clear()\nterm.setCursorBlink(false)\nterm.setCursorPos(1, 1)\n',"rom/programs/eject.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n-- Get arguments\nlocal tArgs = { ... }\nif #tArgs == 0 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <drive>")\n return\nend\n\nlocal sDrive = tArgs[1]\n\n-- Check the disk exists\nlocal bPresent = disk.isPresent(sDrive)\nif not bPresent then\n print("Nothing in " .. sDrive .. " drive")\n return\nend\n\ndisk.eject(sDrive)\n',"rom/programs/exit.lua":"-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nshell.exit()\n","rom/programs/fun/advanced/levels/0.dat":"0\n77 77\n718888887\n 8 8\n 8 8\n 8 8\n788888897\n77 77\n","rom/programs/fun/advanced/levels/1.dat":"1\n 777\n 7b7\n 787\n7777778777\n7188888887\n7777777777\n","rom/programs/fun/advanced/levels/10.dat":"5\n 777 77777\n 727777778837\n 788888878787\n 787777888887\n77877778777777\n7e8b7888b888e7\n7787787b777877\n 777887887887\n 7487807487\n 7777777777\n","rom/programs/fun/advanced/levels/11.dat":"4\n 777777777\n 727872787\n 787878787\n777787878787777\n7be888888888be7\n777787878787777\n 787878787\n 787478747\n 777777777\n","rom/programs/fun/advanced/levels/12.dat":"6\n77 777 77\n72888888897\n 8 8 8\n 8 8b888 8\n78 e8888 87\n78888788887\n78 8888e 87\n 8 888b8 8\n 8 8 8\n75888888807\n77 777 77\n","rom/programs/fun/advanced/levels/2.dat":"1\n777777777\n7888888b7\n787778887\n787 78777\n7877787\n7888887\n7777787\n 707\n 777\n","rom/programs/fun/advanced/levels/3.dat":"2\n 77777777\n777888188777\n7b78777787b7\n78787 78787\n78787 78787\n78887 78887\n777877778777\n 78838887\n 77777777\n","rom/programs/fun/advanced/levels/4.dat":"2\n 77777777\n777778888887\n788888777787\n7b77787 787\n787 787 787\n7b77787 787\n7888887 787\n7777707 707\n 777 777\n","rom/programs/fun/advanced/levels/5.dat":"3\n777777777\n788888887\n787787787\n787787787\n788888887\n787787787\n787787787\n78e748887\n777777777\n","rom/programs/fun/advanced/levels/6.dat":"4\n7777777777\n7288888837\n78 87\n788888b 87\n788888b 87\n788888b 87\n788888b 87\n78 87\n7188888807\n7777777777\n","rom/programs/fun/advanced/levels/7.dat":"3\n728777778b7\n78888888887\n78777877787\n787 787 787\n787 7877788\n787 7888889\n88777877777\ne888887\n7777887\n","rom/programs/fun/advanced/levels/8.dat":"4\n777777 7777\n7287b7 7867\n788787 7887\n77878777877\n 7888eb8887\n 77877787877\n 7887 787887\n 7487 7e7807\n 7777 777777\n","rom/programs/fun/advanced/levels/9.dat":"2\n 777 777\n 777877778777\n 788838888887\n7778bbbbbbbb8777\n7888b888888b8897\n7878be8888eb8787\n7588b888888b8887\n7778bbbbbbbb8777\n 788888818887\n 777877778777\n 777 777\n","rom/programs/fun/advanced/paint.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n-- Paint created by nitrogenfingers (edited by dan200)\n-- http://www.youtube.com/user/NitrogenFingers\n\n------------\n-- Fields --\n------------\n\n-- The width and height of the terminal\nlocal w, h = term.getSize()\n\n-- The selected colours on the left and right mouse button, and the colour of the canvas\nlocal leftColour, rightColour = colours.white, nil\nlocal canvasColour = colours.black\n\n-- The values stored in the canvas\nlocal canvas = {}\n\n-- The menu options\nlocal mChoices = { "Save", "Exit" }\n\n-- The message displayed in the footer bar\nlocal fMessage = "Press Ctrl or click here to access menu"\n\n-------------------------\n-- Initialisation --\n-------------------------\n\n-- Determine if we can even run this\nif not term.isColour() then\n print("Requires an Advanced Computer")\n return\nend\n\n-- Determines if the file exists, and can be edited on this computer\nlocal tArgs = { ... }\nif #tArgs == 0 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <path>")\n return\nend\nlocal sPath = shell.resolve(tArgs[1])\nlocal bReadOnly = fs.isReadOnly(sPath)\nif fs.exists(sPath) and fs.isDir(sPath) then\n print("Cannot edit a directory.")\n return\nend\n\n-- Create .nfp files by default\nif not fs.exists(sPath) and not string.find(sPath, "%.") then\n local sExtension = settings.get("paint.default_extension")\n if sExtension ~= "" and type(sExtension) == "string" then\n sPath = sPath .. "." .. sExtension\n end\nend\n\n\n---------------\n-- Functions --\n---------------\n\nlocal function getCanvasPixel(x, y)\n if canvas[y] then\n return canvas[y][x]\n end\n return nil\nend\n\n--[[\n Converts a colour value to a text character\n params: colour = the number to convert to a hex value\n returns: a string representing the chosen colour\n]]\nlocal function getCharOf(colour)\n -- Incorrect values always convert to nil\n if type(colour) == "number" then\n local value = math.floor(math.log(colour) / math.log(2)) + 1\n if value >= 1 and value <= 16 then\n return string.sub("0123456789abcdef", value, value)\n end\n end\n return " "\nend\n\n--[[\n Converts a text character to colour value\n params: char = the char (from string.byte) to convert to number\n returns: the colour number of the hex value\n]]\nlocal tColourLookup = {}\nfor n = 1, 16 do\n tColourLookup[string.byte("0123456789abcdef", n, n)] = 2 ^ (n - 1)\nend\nlocal function getColourOf(char)\n -- Values not in the hex table are transparent (canvas coloured)\n return tColourLookup[char]\nend\n\n--[[\n Loads the file into the canvas\n params: path = the path of the file to open\n returns: nil\n]]\nlocal function load(path)\n -- Load the file\n if fs.exists(path) then\n local file = fs.open(sPath, "r")\n local sLine = file.readLine()\n while sLine do\n local line = {}\n for x = 1, w - 2 do\n line[x] = getColourOf(string.byte(sLine, x, x))\n end\n table.insert(canvas, line)\n sLine = file.readLine()\n end\n file.close()\n end\nend\n\n--[[\n Saves the current canvas to file\n params: path = the path of the file to save\n returns: true if save was successful, false otherwise\n]]\nlocal function save(path)\n -- Open file\n local sDir = string.sub(sPath, 1, #sPath - #fs.getName(sPath))\n if not fs.exists(sDir) then\n fs.makeDir(sDir)\n end\n\n local file, err = fs.open(path, "w")\n if not file then\n return false, err\n end\n\n -- Encode (and trim)\n local tLines = {}\n local nLastLine = 0\n for y = 1, h - 1 do\n local sLine = ""\n local nLastChar = 0\n for x = 1, w - 2 do\n local c = getCharOf(getCanvasPixel(x, y))\n sLine = sLine .. c\n if c ~= " " then\n nLastChar = x\n end\n end\n sLine = string.sub(sLine, 1, nLastChar)\n tLines[y] = sLine\n if #sLine > 0 then\n nLastLine = y\n end\n end\n\n -- Save out\n for n = 1, nLastLine do\n file.writeLine(tLines[n])\n end\n file.close()\n return true\nend\n\n--[[\n Draws colour picker sidebar, the palette and the footer\n returns: nil\n]]\nlocal function drawInterface()\n -- Footer\n term.setCursorPos(1, h)\n term.setBackgroundColour(colours.black)\n term.setTextColour(colours.yellow)\n term.clearLine()\n term.write(fMessage)\n\n -- Colour Picker\n for i = 1, 16 do\n term.setCursorPos(w - 1, i)\n term.setBackgroundColour(2 ^ (i - 1))\n term.write(" ")\n end\n\n term.setCursorPos(w - 1, 17)\n term.setBackgroundColour(canvasColour)\n term.setTextColour(colours.grey)\n term.write("\\127\\127")\n\n -- Left and Right Selected Colours\n do\n term.setCursorPos(w - 1, 18)\n if leftColour ~= nil then\n term.setBackgroundColour(leftColour)\n term.write(" ")\n else\n term.setBackgroundColour(canvasColour)\n term.setTextColour(colours.grey)\n term.write("\\127")\n end\n if rightColour ~= nil then\n term.setBackgroundColour(rightColour)\n term.write(" ")\n else\n term.setBackgroundColour(canvasColour)\n term.setTextColour(colours.grey)\n term.write("\\127")\n end\n end\n\n -- Padding\n term.setBackgroundColour(canvasColour)\n for i = 20, h - 1 do\n term.setCursorPos(w - 1, i)\n term.write(" ")\n end\nend\n\n--[[\n Converts a single pixel of a single line of the canvas and draws it\n returns: nil\n]]\nlocal function drawCanvasPixel(x, y)\n local pixel = getCanvasPixel(x, y)\n if pixel then\n term.setBackgroundColour(pixel or canvasColour)\n term.setCursorPos(x, y)\n term.write(" ")\n else\n term.setBackgroundColour(canvasColour)\n term.setTextColour(colours.grey)\n term.setCursorPos(x, y)\n term.write("\\127")\n end\nend\n\nlocal color_hex_lookup = {}\nfor i = 0, 15 do\n color_hex_lookup[2 ^ i] = string.format("%x", i)\nend\n\n--[[\n Converts each colour in a single line of the canvas and draws it\n returns: nil\n]]\nlocal function drawCanvasLine(y)\n local text, fg, bg = "", "", ""\n for x = 1, w - 2 do\n local pixel = getCanvasPixel(x, y)\n if pixel then\n text = text .. " "\n fg = fg .. "0"\n bg = bg .. color_hex_lookup[pixel or canvasColour]\n else\n text = text .. "\\127"\n fg = fg .. color_hex_lookup[colours.grey]\n bg = bg .. color_hex_lookup[canvasColour]\n end\n end\n\n term.setCursorPos(1, y)\n term.blit(text, fg, bg)\nend\n\n--[[\n Converts each colour in the canvas and draws it\n returns: nil\n]]\nlocal function drawCanvas()\n for y = 1, h - 1 do\n drawCanvasLine(y)\n end\nend\n\nlocal function termResize()\n w, h = term.getSize()\n drawCanvas()\n drawInterface()\nend\n\nlocal menu_choices = {\n Save = function()\n if bReadOnly then\n fMessage = "Access denied"\n return false\n end\n local success, err = save(sPath)\n if success then\n fMessage = "Saved to " .. sPath\n else\n if err then\n fMessage = "Error saving to " .. err\n else\n fMessage = "Error saving to " .. sPath\n end\n end\n return false\n end,\n Exit = function()\n sleep(0) -- Super janky, but consumes stray "char" events from pressing Ctrl then E separately.\n return true\n end,\n}\n\n--[[\n Draws menu options and handles input from within the menu.\n returns: true if the program is to be exited; false otherwise\n]]\nlocal function accessMenu()\n -- Selected menu option\n local selection = 1\n\n term.setBackgroundColour(colours.black)\n\n while true do\n -- Draw the menu\n term.setCursorPos(1, h)\n term.clearLine()\n term.setTextColour(colours.white)\n for k, v in pairs(mChoices) do\n if selection == k then\n term.setTextColour(colours.yellow)\n term.write("[")\n term.setTextColour(colours.white)\n term.write(v)\n term.setTextColour(colours.yellow)\n term.write("]")\n term.setTextColour(colours.white)\n else\n term.write(" " .. v .. " ")\n end\n end\n\n -- Handle input in the menu\n local id, param1, param2, param3 = os.pullEvent()\n if id == "key" then\n local key = param1\n\n -- Handle menu shortcuts.\n for _, menu_item in ipairs(mChoices) do\n local k = keys[menu_item:sub(1, 1):lower()]\n if k and k == key then\n return menu_choices[menu_item]()\n end\n end\n\n if key == keys.right then\n -- Move right\n selection = selection + 1\n if selection > #mChoices then\n selection = 1\n end\n\n elseif key == keys.left and selection > 1 then\n -- Move left\n selection = selection - 1\n if selection < 1 then\n selection = #mChoices\n end\n\n elseif key == keys.enter or key == keys.numPadEnter then\n -- Select an option\n return menu_choices[mChoices[selection]]()\n elseif key == keys.leftCtrl or keys == keys.rightCtrl then\n -- Cancel the menu\n return false\n end\n elseif id == "mouse_click" then\n local cx, cy = param2, param3\n if cy ~= h then return false end -- Exit the menu\n\n local nMenuPosEnd = 1\n local nMenuPosStart = 1\n for _, sMenuItem in ipairs(mChoices) do\n nMenuPosEnd = nMenuPosEnd + #sMenuItem + 1\n if cx > nMenuPosStart and cx < nMenuPosEnd then\n return menu_choices[sMenuItem]()\n end\n nMenuPosEnd = nMenuPosEnd + 1\n nMenuPosStart = nMenuPosEnd\n end\n elseif id == "term_resize" then\n termResize()\n end\n end\nend\n\n--[[\n Runs the main thread of execution. Draws the canvas and interface, and handles\n mouse and key events.\n returns: nil\n]]\nlocal function handleEvents()\n local programActive = true\n while programActive do\n local id, p1, p2, p3 = os.pullEvent()\n if id == "mouse_click" or id == "mouse_drag" then\n if p2 >= w - 1 and p3 >= 1 and p3 <= 17 then\n if id ~= "mouse_drag" then\n -- Selecting an items in the colour picker\n if p3 <= 16 then\n if p1 == 1 then\n leftColour = 2 ^ (p3 - 1)\n else\n rightColour = 2 ^ (p3 - 1)\n end\n else\n if p1 == 1 then\n leftColour = nil\n else\n rightColour = nil\n end\n end\n --drawCanvas()\n drawInterface()\n end\n elseif p2 < w - 1 and p3 <= h - 1 then\n -- Clicking on the canvas\n local paintColour = nil\n if p1 == 1 then\n paintColour = leftColour\n elseif p1 == 2 then\n paintColour = rightColour\n end\n if not canvas[p3] then\n canvas[p3] = {}\n end\n canvas[p3][p2] = paintColour\n\n drawCanvasPixel(p2, p3)\n elseif p3 == h and id == "mouse_click" then\n -- Open menu\n programActive = not accessMenu()\n drawInterface()\n end\n elseif id == "key" then\n if p1 == keys.leftCtrl or p1 == keys.rightCtrl then\n programActive = not accessMenu()\n drawInterface()\n end\n elseif id == "term_resize" then\n termResize()\n end\n end\nend\n\n-- Init\nload(sPath)\ndrawCanvas()\ndrawInterface()\n\n-- Main loop\nhandleEvents()\n\n-- Shutdown\nterm.setBackgroundColour(colours.black)\nterm.setTextColour(colours.white)\nterm.clear()\nterm.setCursorPos(1, 1)\n',"rom/programs/fun/advanced/redirection.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--CCRedirection by : RamiLego4Game and Dan200--\n--Based on Redirection by Dan200: http://www.redirectiongame.com--\n--Clearing Screen--\n\n--Vars--\nlocal TermW, TermH = term.getSize()\n\nlocal sLevelTitle\nlocal tScreen\nlocal oScreen\nlocal SizeW, SizeH\nlocal aExits\nlocal fExit\nlocal nSpeed\nlocal Speed\nlocal fSpeed\nlocal fSpeedS\nlocal bPaused\nlocal Tick\nlocal Blocks\nlocal XOrgin, YOrgin\nlocal fLevel\n\nlocal function reset()\n sLevelTitle = ""\n tScreen = {}\n oScreen = {}\n SizeW, SizeH = TermW, TermH\n aExits = 0\n fExit = "nop"\n nSpeed = 0.6\n Speed = nSpeed\n fSpeed = 0.2\n fSpeedS = false\n bPaused = false\n Tick = os.startTimer(Speed)\n Blocks = 0\n XOrgin, YOrgin = 1, 1\n\n term.setBackgroundColor(colors.black)\n term.setTextColor(colors.white)\n term.clear()\nend\n\nlocal InterFace = {}\nInterFace.cExit = colors.red\nInterFace.cSpeedD = colors.white\nInterFace.cSpeedA = colors.red\nInterFace.cTitle = colors.red\n\nlocal cG = colors.lightGray\nlocal cW = colors.gray\nlocal cS = colors.black\nlocal cR1 = colors.blue\nlocal cR2 = colors.red\nlocal cR3 = colors.green\nlocal cR4 = colors.yellow\n\nlocal tArgs = { ... }\n\n--Functions--\nlocal function printCentred(yc, stg)\n local xc = math.floor((TermW - #stg) / 2) + 1\n term.setCursorPos(xc, yc)\n term.write(stg)\nend\n\nlocal function centerOrgin()\n XOrgin = math.floor(TermW / 2 - SizeW / 2)\n YOrgin = math.floor(TermH / 2 - SizeH / 2)\nend\n\nlocal function reMap()\n tScreen = nil\n tScreen = {}\n for x = 1, SizeW do\n tScreen[x] = {}\n for y = 1, SizeH do\n tScreen[x][y] = { space = true, wall = false, ground = false, robot = "zz", start = "zz", exit = "zz" }\n end\n end\nend\n\nlocal function tablecopy(t)\n local t2 = {}\n for k, v in pairs(t) do\n t2[k] = v\n end\n return t2\nend\n\nlocal function buMap()\n oScreen = nil\n oScreen = {}\n for x = 1, SizeW do\n oScreen[x] = {}\n for y = 1, SizeH do\n oScreen[x][y] = tablecopy(tScreen[x][y])\n end\n end\nend\n\nlocal function addRobot(x, y, side, color)\n local obj = tScreen[x][y]\n local data = side .. color\n if obj.wall == nil and obj.robot == nil then\n tScreen[x][y].robot = data\n else\n obj.wall = nil\n obj.robot = "zz"\n tScreen[x][y].robot = data\n end\nend\n\nlocal function addStart(x, y, side, color)\n local obj = tScreen[x][y]\n local data = side .. color\n if obj.wall == nil and obj.space == nil then\n tScreen[x][y].start = data\n else\n obj.wall = nil\n obj.space = nil\n tScreen[x][y].start = data\n end\n aExits = aExits + 1\nend\n\nlocal function addGround(x, y)\n local obj = tScreen[x][y]\n if obj.space == nil and obj.exit == nil and obj.wall == nil and obj.robot == nil and obj.start == nil then\n tScreen[x][y].ground = true\n else\n obj.space = nil\n obj.exit = "zz"\n obj.wall = nil\n obj.robot = "zz"\n obj.start = "zz"\n tScreen[x][y].ground = true\n end\nend\n\nlocal function addExit(x, y, cl)\n local obj = tScreen[x][y]\n if obj.space == nil and obj.ground == nil and obj.wall == nil and obj.robot == nil and obj.start == nil then\n tScreen[x][y].exit = cl\n else\n obj.space = nil\n obj.ground = nil\n obj.wall = nil\n obj.robot = "zz"\n obj.start = "zz"\n tScreen[x][y].exit = cl\n end\nend\n\nlocal function addWall(x, y)\n local obj = tScreen[x][y]\n if obj == nil then\n return error("Here X" .. x .. " Y" .. y)\n end\n if obj.space == nil and obj.exit == nil and obj.ground == nil and obj.robot == nil and obj.start == nil then\n tScreen[x][y].wall = true\n else\n obj.space = nil\n obj.exit = nil\n obj.ground = nil\n obj.robot = nil\n obj.start = nil\n tScreen[x][y].wall = true\n end\nend\n\nlocal function loadLevel(nNum)\n sLevelTitle = "Level " .. nNum\n if nNum == nil then return error("nNum == nil") end\n local sDir = fs.getDir(shell.getRunningProgram())\n local sLevelD = sDir .. "/levels/" .. tostring(nNum) .. ".dat"\n if not (fs.exists(sLevelD) or fs.isDir(sLevelD)) then return error("Level Not Exists : " .. sLevelD) end\n fLevel = fs.open(sLevelD, "r")\n local wl = true\n Blocks = tonumber(string.sub(fLevel.readLine(), 1, 1))\n local xSize = #fLevel.readLine() + 2\n local Lines = 3\n while wl do\n local wLine = fLevel.readLine()\n if wLine == nil then\n fLevel.close()\n wl = false\n else\n xSize = math.max(#wLine + 2, xSize)\n Lines = Lines + 1\n end\n end\n SizeW, SizeH = xSize, Lines\n reMap()\n fLevel = fs.open(sLevelD, "r")\n fLevel.readLine()\n for Line = 2, Lines - 1 do\n local sLine = fLevel.readLine()\n local chars = #sLine\n for char = 1, chars do\n local el = string.sub(sLine, char, char)\n if el == "8" then\n addGround(char + 1, Line)\n elseif el == "0" then\n addStart(char + 1, Line, "a", "a")\n elseif el == "1" then\n addStart(char + 1, Line, "b", "a")\n elseif el == "2" then\n addStart(char + 1, Line, "c", "a")\n elseif el == "3" then\n addStart(char + 1, Line, "d", "a")\n elseif el == "4" then\n addStart(char + 1, Line, "a", "b")\n elseif el == "5" then\n addStart(char + 1, Line, "b", "b")\n elseif el == "6" then\n addStart(char + 1, Line, "c", "b")\n elseif el == "9" then\n addStart(char + 1, Line, "d", "b")\n elseif el == "b" then\n addExit(char + 1, Line, "a")\n elseif el == "e" then\n addExit(char + 1, Line, "b")\n elseif el == "7" then\n addWall(char + 1, Line)\n end\n end\n end\n fLevel.close()\nend\n\nlocal function drawStars()\n --CCR Background By : RamiLego--\n local cStar, cStarG, crStar, crStarB = colors.lightGray, colors.gray, ".", "*"\n local DStar, BStar, nStar, gStar = 14, 10, 16, 3\n local TermW, TermH = term.getSize()\n\n term.clear()\n term.setCursorPos(1, 1)\n for x = 1, TermW do\n for y = 1, TermH do\n local StarT = math.random(1, 30)\n if StarT == DStar then\n term.setCursorPos(x, y)\n term.setTextColor(cStar)\n write(crStar)\n elseif StarT == BStar then\n term.setCursorPos(x, y)\n term.setTextColor(cStar)\n write(crStarB)\n elseif StarT == nStar then\n term.setCursorPos(x, y)\n term.setTextColor(cStarG)\n write(crStar)\n elseif StarT == gStar then\n term.setCursorPos(x, y)\n term.setTextColor(cStarG)\n write(crStarB)\n end\n end\n end\nend\n\nlocal function drawMap()\n for x = 1, SizeW do\n for y = 1, SizeH do\n\n local obj = tScreen[x][y]\n if obj.ground == true then\n paintutils.drawPixel(XOrgin + x, YOrgin + y + 1, cG)\n end\n if obj.wall == true then\n paintutils.drawPixel(XOrgin + x, YOrgin + y + 1, cW)\n end\n\n local ex = tostring(tScreen[x][y].exit)\n if not(ex == "zz" or ex == "nil") then\n if ex == "a" then\n ex = cR1\n elseif ex == "b" then\n ex = cR2\n elseif ex == "c" then\n ex = cR3\n elseif ex == "d" then\n ex = cR4\n else\n return error("Exit Color Out")\n end\n term.setBackgroundColor(cG)\n term.setTextColor(ex)\n term.setCursorPos(XOrgin + x, YOrgin + y + 1)\n print("X")\n end\n\n local st = tostring(tScreen[x][y].start)\n if not(st == "zz" or st == "nil") then\n local Cr = string.sub(st, 2, 2)\n if Cr == "a" then\n Cr = cR1\n elseif Cr == "b" then\n Cr = cR2\n elseif Cr == "c" then\n Cr = cR3\n elseif Cr == "d" then\n Cr = cR4\n else\n return error("Start Color Out")\n end\n\n term.setTextColor(Cr)\n term.setBackgroundColor(cG)\n term.setCursorPos(XOrgin + x, YOrgin + y + 1)\n\n local sSide = string.sub(st, 1, 1)\n if sSide == "a" then\n print("^")\n elseif sSide == "b" then\n print(">")\n elseif sSide == "c" then\n print("v")\n elseif sSide == "d" then\n print("<")\n else\n print("@")\n end\n end\n\n if obj.space == true then\n paintutils.drawPixel(XOrgin + x, YOrgin + y + 1, cS)\n end\n\n local rb = tostring(tScreen[x][y].robot)\n if not(rb == "zz" or rb == "nil") then\n local Cr = string.sub(rb, 2, 2)\n if Cr == "a" then\n Cr = cR1\n elseif Cr == "b" then\n Cr = cR2\n elseif Cr == "c" then\n Cr = cR3\n elseif Cr == "d" then\n Cr = cR4\n else\n Cr = colors.white\n end\n term.setBackgroundColor(Cr)\n term.setTextColor(colors.white)\n term.setCursorPos(XOrgin + x, YOrgin + y + 1)\n local sSide = string.sub(rb, 1, 1)\n if sSide == "a" then\n print("^")\n elseif sSide == "b" then\n print(">")\n elseif sSide == "c" then\n print("v")\n elseif sSide == "d" then\n print("<")\n else\n print("@")\n end\n end\n end\n end\nend\n\nlocal function isBrick(x, y)\n local brb = tostring(tScreen[x][y].robot)\n local bobj = oScreen[x][y]\n if (brb == "zz" or brb == "nil") and not bobj.wall == true then\n return false\n else\n return true\n end\nend\n\nlocal function gRender(sContext)\n if sContext == "start" then\n for x = 1, SizeW do\n for y = 1, SizeH do\n local st = tostring(tScreen[x][y].start)\n if not(st == "zz" or st == "nil") then\n local Cr = string.sub(st, 2, 2)\n local sSide = string.sub(st, 1, 1)\n addRobot(x, y, sSide, Cr)\n end\n end\n end\n elseif sContext == "tick" then\n buMap()\n for x = 1, SizeW do\n for y = 1, SizeH do\n local rb = tostring(oScreen[x][y].robot)\n if not(rb == "zz" or rb == "nil") then\n local Cr = string.sub(rb, 2, 2)\n local sSide = string.sub(rb, 1, 1)\n local sobj = oScreen[x][y]\n if sobj.space == true then\n tScreen[x][y].robot = "zz"\n if not sSide == "g" then\n addRobot(x, y, "g", Cr)\n end\n elseif sobj.exit == Cr then\n if sSide == "a" or sSide == "b" or sSide == "c" or sSide == "d" then\n tScreen[x][y].robot = "zz"\n addRobot(x, y, "g", Cr)\n aExits = aExits - 1\n end\n elseif sSide == "a" then\n local obj = isBrick(x, y - 1)\n tScreen[x][y].robot = "zz"\n if not obj == true then\n addRobot(x, y - 1, sSide, Cr)\n else\n local obj2 = isBrick(x - 1, y)\n local obj3 = isBrick(x + 1, y)\n if not obj2 == true and not obj3 == true then\n if Cr == "a" then\n addRobot(x, y, "d", Cr)\n elseif Cr == "b" then\n addRobot(x, y, "b", Cr)\n end\n elseif obj == true and obj2 == true and obj3 == true then\n addRobot(x, y, "c", Cr)\n else\n if obj3 == true then\n addRobot(x, y, "d", Cr)\n elseif obj2 == true then\n addRobot(x, y, "b", Cr)\n end\n end\n end\n elseif sSide == "b" then\n local obj = isBrick(x + 1, y)\n tScreen[x][y].robot = "zz"\n if not obj == true then\n addRobot(x + 1, y, sSide, Cr)\n else\n local obj2 = isBrick(x, y - 1)\n local obj3 = isBrick(x, y + 1)\n if not obj2 == true and not obj3 == true then\n if Cr == "a" then\n addRobot(x, y, "a", Cr)\n elseif Cr == "b" then\n addRobot(x, y, "c", Cr)\n end\n elseif obj == true and obj2 == true and obj3 == true then\n addRobot(x, y, "d", Cr)\n else\n if obj3 == true then\n addRobot(x, y, "a", Cr)\n elseif obj2 == true then\n addRobot(x, y, "c", Cr)\n end\n end\n end\n elseif sSide == "c" then\n local obj = isBrick(x, y + 1)\n tScreen[x][y].robot = "zz"\n if not obj == true then\n addRobot(x, y + 1, sSide, Cr)\n else\n local obj2 = isBrick(x - 1, y)\n local obj3 = isBrick(x + 1, y)\n if not obj2 == true and not obj3 == true then\n if Cr == "a" then\n addRobot(x, y, "b", Cr)\n elseif Cr == "b" then\n addRobot(x, y, "d", Cr)\n end\n elseif obj == true and obj2 == true and obj3 == true then\n addRobot(x, y, "a", Cr)\n else\n if obj3 == true then\n addRobot(x, y, "d", Cr)\n elseif obj2 == true then\n addRobot(x, y, "b", Cr)\n end\n end\n end\n elseif sSide == "d" then\n local obj = isBrick(x - 1, y)\n tScreen[x][y].robot = "zz"\n if not obj == true then\n addRobot(x - 1, y, sSide, Cr)\n else\n local obj2 = isBrick(x, y - 1)\n local obj3 = isBrick(x, y + 1)\n if not obj2 == true and not obj3 == true then\n if Cr == "a" then\n addRobot(x, y, "c", Cr)\n elseif Cr == "b" then\n addRobot(x, y, "a", Cr)\n end\n elseif obj == true and obj2 == true and obj3 == true then\n addRobot(x, y, "b", Cr)\n else\n if obj3 == true then\n addRobot(x, y, "a", Cr)\n elseif obj2 == true then\n addRobot(x, y, "c", Cr)\n end\n end\n end\n else\n addRobot(x, y, sSide, "g")\n end\n end\n end\n end\n end\nend\n\nfunction InterFace.drawBar()\n term.setBackgroundColor(colors.black)\n term.setTextColor(InterFace.cTitle)\n printCentred(1, " " .. sLevelTitle .. " ")\n\n term.setCursorPos(1, 1)\n term.setBackgroundColor(cW)\n write(" ")\n term.setBackgroundColor(colors.black)\n write(" x " .. tostring(Blocks) .. " ")\n\n term.setCursorPos(TermW - 8, TermH)\n term.setBackgroundColor(colors.black)\n term.setTextColour(InterFace.cSpeedD)\n write(" <<")\n if bPaused then\n term.setTextColour(InterFace.cSpeedA)\n else\n term.setTextColour(InterFace.cSpeedD)\n end\n write(" ||")\n if fSpeedS then\n term.setTextColour(InterFace.cSpeedA)\n else\n term.setTextColour(InterFace.cSpeedD)\n end\n write(" >>")\n\n term.setCursorPos(TermW - 1, 1)\n term.setBackgroundColor(colors.black)\n term.setTextColour(InterFace.cExit)\n write(" X")\n term.setBackgroundColor(colors.black)\nend\n\nfunction InterFace.render()\n local id, p1, p2, p3 = os.pullEvent()\n if id == "mouse_click" then\n if p3 == 1 and p2 == TermW then\n return "end"\n elseif p3 == TermH and p2 >= TermW - 7 and p2 <= TermW - 6 then\n return "retry"\n elseif p3 == TermH and p2 >= TermW - 4 and p2 <= TermW - 3 then\n bPaused = not bPaused\n fSpeedS = false\n Speed = bPaused and 0 or nSpeed\n if Speed > 0 then\n Tick = os.startTimer(Speed)\n else\n Tick = nil\n end\n InterFace.drawBar()\n elseif p3 == TermH and p2 >= TermW - 1 then\n bPaused = false\n fSpeedS = not fSpeedS\n Speed = fSpeedS and fSpeed or nSpeed\n Tick = os.startTimer(Speed)\n InterFace.drawBar()\n elseif p3 - 1 < YOrgin + SizeH + 1 and p3 - 1 > YOrgin and\n p2 < XOrgin + SizeW + 1 and p2 > XOrgin then\n local eobj = tScreen[p2 - XOrgin][p3 - YOrgin - 1]\n local erobj = tostring(tScreen[p2 - XOrgin][p3 - YOrgin - 1].robot)\n if (erobj == "zz" or erobj == "nil") and not eobj.wall == true and not eobj.space == true and Blocks > 0 then\n addWall(p2 - XOrgin, p3 - YOrgin - 1)\n Blocks = Blocks - 1\n InterFace.drawBar()\n drawMap()\n end\n end\n elseif id == "timer" and p1 == Tick then\n gRender("tick")\n drawMap()\n if Speed > 0 then\n Tick = os.startTimer(Speed)\n else\n Tick = nil\n end\n end\nend\n\nlocal function startG(LevelN)\n drawStars()\n loadLevel(LevelN)\n centerOrgin()\n drawMap()\n InterFace.drawBar()\n gRender("start")\n drawMap()\n\n local NExit = true\n if aExits == 0 then\n NExit = false\n end\n\n while true do\n local isExit = InterFace.render()\n if isExit == "end" then\n return nil\n elseif isExit == "retry" then\n return LevelN\n elseif fExit == "yes" then\n if fs.exists(fs.getDir(shell.getRunningProgram()) .. "/levels/" .. tostring(LevelN + 1) .. ".dat") then\n return LevelN + 1\n else\n return nil\n end\n end\n if aExits == 0 and NExit == true then\n fExit = "yes"\n end\n end\nend\n\nlocal ok, err = true, nil\n\n--Menu--\nlocal sStartLevel = tArgs[1]\nif ok and not sStartLevel then\n ok, err = pcall(function()\n term.setTextColor(colors.white)\n term.setBackgroundColor(colors.black)\n term.clear()\n drawStars()\n term.setTextColor(colors.red)\n printCentred(TermH / 2 - 1, " REDIRECTION ")\n printCentred(TermH / 2 - 0, " ComputerCraft Edition ")\n term.setTextColor(colors.yellow)\n printCentred(TermH / 2 + 2, " Click to Begin ")\n os.pullEvent("mouse_click")\n end)\nend\n\n--Game--\nif ok then\n ok, err = pcall(function()\n local nLevel\n if sStartLevel then\n nLevel = tonumber(sStartLevel)\n else\n nLevel = 1\n end\n while nLevel do\n reset()\n nLevel = startG(nLevel)\n end\n end)\nend\n\n--Upsell screen--\nif ok then\n ok, err = pcall(function()\n term.setTextColor(colors.white)\n term.setBackgroundColor(colors.black)\n term.clear()\n drawStars()\n term.setTextColor(colors.red)\n if TermW >= 40 then\n printCentred(TermH / 2 - 1, " Thank you for playing Redirection ")\n printCentred(TermH / 2 - 0, " ComputerCraft Edition ")\n printCentred(TermH / 2 + 2, " Check out the full game: ")\n term.setTextColor(colors.yellow)\n printCentred(TermH / 2 + 3, " http://www.redirectiongame.com ")\n else\n printCentred(TermH / 2 - 2, " Thank you for ")\n printCentred(TermH / 2 - 1, " playing Redirection ")\n printCentred(TermH / 2 - 0, " ComputerCraft Edition ")\n printCentred(TermH / 2 + 2, " Check out the full game: ")\n term.setTextColor(colors.yellow)\n printCentred(TermH / 2 + 3, " www.redirectiongame.com ")\n end\n parallel.waitForAll(\n function() sleep(2) end,\n function() os.pullEvent("mouse_click") end\n )\n end)\nend\n\n--Clear and exit--\nterm.setCursorPos(1, 1)\nterm.setTextColor(colors.white)\nterm.setBackgroundColor(colors.black)\nterm.clear()\nif not ok then\n if err == "Terminated" then\n print("Check out the full version of Redirection:")\n print("http://www.redirectiongame.com")\n else\n printError(err)\n end\nend\n',"rom/programs/fun/adventure.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tBiomes = {\n "in a forest",\n "in a pine forest",\n "knee deep in a swamp",\n "in a mountain range",\n "in a desert",\n "in a grassy plain",\n "in frozen tundra",\n}\n\nlocal function hasTrees(_nBiome)\n return _nBiome <= 3\nend\n\nlocal function hasStone(_nBiome)\n return _nBiome == 4\nend\n\nlocal function hasRivers(_nBiome)\n return _nBiome ~= 3 and _nBiome ~= 5\nend\n\nlocal items = {\n ["no tea"] = {\n droppable = false,\n desc = "Pull yourself together man.",\n },\n ["a pig"] = {\n heavy = true,\n creature = true,\n drops = { "some pork" },\n aliases = { "pig" },\n desc = "The pig has a square nose.",\n },\n ["a cow"] = {\n heavy = true,\n creature = true,\n aliases = { "cow" },\n desc = "The cow stares at you blankly.",\n },\n ["a sheep"] = {\n heavy = true,\n creature = true,\n hitDrops = { "some wool" },\n aliases = { "sheep" },\n desc = "The sheep is fluffy.",\n },\n ["a chicken"] = {\n heavy = true,\n creature = true,\n drops = { "some chicken" },\n aliases = { "chicken" },\n desc = "The chicken looks delicious.",\n },\n ["a creeper"] = {\n heavy = true,\n creature = true,\n monster = true,\n aliases = { "creeper" },\n desc = "The creeper needs a hug.",\n },\n ["a skeleton"] = {\n heavy = true,\n creature = true,\n monster = true,\n aliases = { "skeleton" },\n nocturnal = true,\n desc = "The head bone\'s connected to the neck bone, the neck bone\'s connected to the chest bone, the chest bone\'s connected to the arm bone, the arm bone\'s connected to the bow, and the bow is pointed at you.",\n },\n ["a zombie"] = {\n heavy = true,\n creature = true,\n monster = true,\n aliases = { "zombie" },\n nocturnal = true,\n desc = "All he wants to do is eat your brains.",\n },\n ["a spider"] = {\n heavy = true,\n creature = true,\n monster = true,\n aliases = { "spider" },\n desc = "Dozens of eyes stare back at you.",\n },\n ["a cave entrance"] = {\n heavy = true,\n aliases = { "cave entance", "cave", "entrance" },\n desc = "The entrance to the cave is dark, but it looks like you can climb down.",\n },\n ["an exit to the surface"] = {\n heavy = true,\n aliases = { "exit to the surface", "exit", "opening" },\n desc = "You can just see the sky through the opening.",\n },\n ["a river"] = {\n heavy = true,\n aliases = { "river" },\n desc = "The river flows majestically towards the horizon. It doesn\'t do anything else.",\n },\n ["some wood"] = {\n aliases = { "wood" },\n material = true,\n desc = "You could easily craft this wood into planks.",\n },\n ["some planks"] = {\n aliases = { "planks", "wooden planks", "wood planks" },\n desc = "You could easily craft these planks into sticks.",\n },\n ["some sticks"] = {\n aliases = { "sticks", "wooden sticks", "wood sticks" },\n desc = "A perfect handle for torches or a pickaxe.",\n },\n ["a crafting table"] = {\n aliases = { "crafting table", "craft table", "work bench", "workbench", "crafting bench", "table" },\n desc = "It\'s a crafting table. I shouldn\'t tell you this, but these don\'t actually do anything in this game, you can craft tools whenever you like.",\n },\n ["a furnace"] = {\n aliases = { "furnace" },\n desc = "It\'s a furnace. Between you and me, these don\'t actually do anything in this game.",\n },\n ["a wooden pickaxe"] = {\n aliases = { "pickaxe", "pick", "wooden pick", "wooden pickaxe", "wood pick", "wood pickaxe" },\n tool = true,\n toolLevel = 1,\n toolType = "pick",\n desc = "The pickaxe looks good for breaking stone and coal.",\n },\n ["a stone pickaxe"] = {\n aliases = { "pickaxe", "pick", "stone pick", "stone pickaxe" },\n tool = true,\n toolLevel = 2,\n toolType = "pick",\n desc = "The pickaxe looks good for breaking iron.",\n },\n ["an iron pickaxe"] = {\n aliases = { "pickaxe", "pick", "iron pick", "iron pickaxe" },\n tool = true,\n toolLevel = 3,\n toolType = "pick",\n desc = "The pickaxe looks strong enough to break diamond.",\n },\n ["a diamond pickaxe"] = {\n aliases = { "pickaxe", "pick", "diamond pick", "diamond pickaxe" },\n tool = true,\n toolLevel = 4,\n toolType = "pick",\n desc = "Best. Pickaxe. Ever.",\n },\n ["a wooden sword"] = {\n aliases = { "sword", "wooden sword", "wood sword" },\n tool = true,\n toolLevel = 1,\n toolType = "sword",\n desc = "Flimsy, but better than nothing.",\n },\n ["a stone sword"] = {\n aliases = { "sword", "stone sword" },\n tool = true,\n toolLevel = 2,\n toolType = "sword",\n desc = "A pretty good sword.",\n },\n ["an iron sword"] = {\n aliases = { "sword", "iron sword" },\n tool = true,\n toolLevel = 3,\n toolType = "sword",\n desc = "This sword can slay any enemy.",\n },\n ["a diamond sword"] = {\n aliases = { "sword", "diamond sword" },\n tool = true,\n toolLevel = 4,\n toolType = "sword",\n desc = "Best. Sword. Ever.",\n },\n ["a wooden shovel"] = {\n aliases = { "shovel", "wooden shovel", "wood shovel" },\n tool = true,\n toolLevel = 1,\n toolType = "shovel",\n desc = "Good for digging holes.",\n },\n ["a stone shovel"] = {\n aliases = { "shovel", "stone shovel" },\n tool = true,\n toolLevel = 2,\n toolType = "shovel",\n desc = "Good for digging holes.",\n },\n ["an iron shovel"] = {\n aliases = { "shovel", "iron shovel" },\n tool = true,\n toolLevel = 3,\n toolType = "shovel",\n desc = "Good for digging holes.",\n },\n ["a diamond shovel"] = {\n aliases = { "shovel", "diamond shovel" },\n tool = true,\n toolLevel = 4,\n toolType = "shovel",\n desc = "Good for digging holes.",\n },\n ["some coal"] = {\n aliases = { "coal" },\n ore = true,\n toolLevel = 1,\n toolType = "pick",\n desc = "That coal looks useful for building torches, if only you had a pickaxe to mine it.",\n },\n ["some dirt"] = {\n aliases = { "dirt" },\n material = true,\n desc = "Why not build a mud hut?",\n },\n ["some stone"] = {\n aliases = { "stone", "cobblestone" },\n material = true,\n ore = true,\n infinite = true,\n toolLevel = 1,\n toolType = "pick",\n desc = "Stone is useful for building things, and making stone pickaxes.",\n },\n ["some iron"] = {\n aliases = { "iron" },\n material = true,\n ore = true,\n toolLevel = 2,\n toolType = "pick",\n desc = "That iron looks mighty strong, you\'ll need a stone pickaxe to mine it.",\n },\n ["some diamond"] = {\n aliases = { "diamond", "diamonds" },\n material = true,\n ore = true,\n toolLevel = 3,\n toolType = "pick",\n desc = "Sparkly, rare, and impossible to mine without an iron pickaxe.",\n },\n ["some torches"] = {\n aliases = { "torches", "torch" },\n desc = "These won\'t run out for a while.",\n },\n ["a torch"] = {\n aliases = { "torch" },\n desc = "Fire, fire, burn so bright, won\'t you light my cave tonight?",\n },\n ["some wool"] = {\n aliases = { "wool" },\n material = true,\n desc = "Soft and good for building.",\n },\n ["some pork"] = {\n aliases = { "pork", "porkchops" },\n food = true,\n desc = "Delicious and nutritious.",\n },\n ["some chicken"] = {\n aliases = { "chicken" },\n food = true,\n desc = "Finger licking good.",\n },\n}\n\nlocal tAnimals = {\n "a pig", "a cow", "a sheep", "a chicken",\n}\n\nlocal tMonsters = {\n "a creeper", "a skeleton", "a zombie", "a spider",\n}\n\nlocal tRecipes = {\n ["some planks"] = { "some wood" },\n ["some sticks"] = { "some planks" },\n ["a crafting table"] = { "some planks" },\n ["a furnace"] = { "some stone" },\n ["some torches"] = { "some sticks", "some coal" },\n\n ["a wooden pickaxe"] = { "some planks", "some sticks" },\n ["a stone pickaxe"] = { "some stone", "some sticks" },\n ["an iron pickaxe"] = { "some iron", "some sticks" },\n ["a diamond pickaxe"] = { "some diamond", "some sticks" },\n\n ["a wooden sword"] = { "some planks", "some sticks" },\n ["a stone sword"] = { "some stone", "some sticks" },\n ["an iron sword"] = { "some iron", "some sticks" },\n ["a diamond sword"] = { "some diamond", "some sticks" },\n\n ["a wooden shovel"] = { "some planks", "some sticks" },\n ["a stone shovel"] = { "some stone", "some sticks" },\n ["an iron shovel"] = { "some iron", "some sticks" },\n ["a diamond shovel"] = { "some diamond", "some sticks" },\n}\n\nlocal tGoWest = {\n "(life is peaceful there)",\n "(lots of open air)",\n "(to begin life anew)",\n "(this is what we\'ll do)",\n "(sun in winter time)",\n "(we will do just fine)",\n "(where the skies are blue)",\n "(this and more we\'ll do)",\n}\nlocal nGoWest = 0\n\nlocal bRunning = true\nlocal tMap = { { {} } }\nlocal x, y, z = 0, 0, 0\nlocal inventory = {\n ["no tea"] = items["no tea"],\n}\n\nlocal nTurn = 0\nlocal nTimeInRoom = 0\nlocal bInjured = false\n\nlocal tDayCycle = {\n "It is daytime.",\n "It is daytime.",\n "It is daytime.",\n "It is daytime.",\n "It is daytime.",\n "It is daytime.",\n "It is daytime.",\n "It is daytime.",\n "The sun is setting.",\n "It is night.",\n "It is night.",\n "It is night.",\n "It is night.",\n "It is night.",\n "The sun is rising.",\n}\n\nlocal function getTimeOfDay()\n return math.fmod(math.floor(nTurn / 3), #tDayCycle) + 1\nend\n\nlocal function isSunny()\n return getTimeOfDay() < 10\nend\n\nlocal function getRoom(x, y, z, dontCreate)\n tMap[x] = tMap[x] or {}\n tMap[x][y] = tMap[x][y] or {}\n if not tMap[x][y][z] and dontCreate ~= true then\n local room = {\n items = {},\n exits = {},\n nMonsters = 0,\n }\n tMap[x][y][z] = room\n\n if y == 0 then\n -- Room is above ground\n\n -- Pick biome\n room.nBiome = math.random(1, #tBiomes)\n room.trees = hasTrees(room.nBiome)\n\n -- Add animals\n if math.random(1, 3) == 1 then\n for _ = 1, math.random(1, 2) do\n local sAnimal = tAnimals[math.random(1, #tAnimals)]\n room.items[sAnimal] = items[sAnimal]\n end\n end\n\n -- Add surface ore\n if math.random(1, 5) == 1 or hasStone(room.nBiome) then\n room.items["some stone"] = items["some stone"]\n end\n if math.random(1, 8) == 1 then\n room.items["some coal"] = items["some coal"]\n end\n if math.random(1, 8) == 1 and hasRivers(room.nBiome) then\n room.items["a river"] = items["a river"]\n end\n\n -- Add exits\n room.exits = {\n ["north"] = true,\n ["south"] = true,\n ["east"] = true,\n ["west"] = true,\n }\n if math.random(1, 8) == 1 then\n room.exits.down = true\n room.items["a cave entrance"] = items["a cave entrance"]\n end\n\n else\n -- Room is underground\n -- Add exits\n local function tryExit(sDir, sOpp, x, y, z)\n local adj = getRoom(x, y, z, true)\n if adj then\n if adj.exits[sOpp] then\n room.exits[sDir] = true\n end\n else\n if math.random(1, 3) == 1 then\n room.exits[sDir] = true\n end\n end\n end\n\n if y == -1 then\n local above = getRoom(x, y + 1, z)\n if above.exits.down then\n room.exits.up = true\n room.items["an exit to the surface"] = items["an exit to the surface"]\n end\n else\n tryExit("up", "down", x, y + 1, z)\n end\n\n if y > -3 then\n tryExit("down", "up", x, y - 1, z)\n end\n\n tryExit("east", "west", x - 1, y, z)\n tryExit("west", "east", x + 1, y, z)\n tryExit("north", "south", x, y, z + 1)\n tryExit("south", "north", x, y, z - 1)\n\n -- Add ores\n room.items["some stone"] = items["some stone"]\n if math.random(1, 3) == 1 then\n room.items["some coal"] = items["some coal"]\n end\n if math.random(1, 8) == 1 then\n room.items["some iron"] = items["some iron"]\n end\n if y == -3 and math.random(1, 15) == 1 then\n room.items["some diamond"] = items["some diamond"]\n end\n\n -- Turn out the lights\n room.dark = true\n end\n end\n return tMap[x][y][z]\nend\n\nlocal function itemize(t)\n local item = next(t)\n if item == nil then\n return "nothing"\n end\n\n local text = ""\n while item do\n text = text .. item\n\n local nextItem = next(t, item)\n if nextItem ~= nil then\n local nextNextItem = next(t, nextItem)\n if nextNextItem == nil then\n text = text .. " and "\n else\n text = text .. ", "\n end\n end\n item = nextItem\n end\n return text\nend\n\nlocal function findItem(_tList, _sQuery)\n for sItem, tItem in pairs(_tList) do\n if sItem == _sQuery then\n return sItem\n end\n if tItem.aliases ~= nil then\n for _, sAlias in pairs(tItem.aliases) do\n if sAlias == _sQuery then\n return sItem\n end\n end\n end\n end\n return nil\nend\n\nlocal tMatches = {\n ["wait"] = {\n "wait",\n },\n ["look"] = {\n "look at the ([%a ]+)",\n "look at ([%a ]+)",\n "look",\n "inspect ([%a ]+)",\n "inspect the ([%a ]+)",\n "inspect",\n },\n ["inventory"] = {\n "check self",\n "check inventory",\n "inventory",\n "i",\n },\n ["go"] = {\n "go (%a+)",\n "travel (%a+)",\n "walk (%a+)",\n "run (%a+)",\n "go",\n },\n ["dig"] = {\n "dig (%a+) using ([%a ]+)",\n "dig (%a+) with ([%a ]+)",\n "dig (%a+)",\n "dig",\n },\n ["take"] = {\n "pick up the ([%a ]+)",\n "pick up ([%a ]+)",\n "pickup ([%a ]+)",\n "take the ([%a ]+)",\n "take ([%a ]+)",\n "take",\n },\n ["drop"] = {\n "put down the ([%a ]+)",\n "put down ([%a ]+)",\n "drop the ([%a ]+)",\n "drop ([%a ]+)",\n "drop",\n },\n ["place"] = {\n "place the ([%a ]+)",\n "place ([%a ]+)",\n "place",\n },\n ["cbreak"] = {\n "punch the ([%a ]+)",\n "punch ([%a ]+)",\n "punch",\n "break the ([%a ]+) with the ([%a ]+)",\n "break ([%a ]+) with ([%a ]+) ",\n "break the ([%a ]+)",\n "break ([%a ]+)",\n "break",\n },\n ["mine"] = {\n "mine the ([%a ]+) with the ([%a ]+)",\n "mine ([%a ]+) with ([%a ]+)",\n "mine ([%a ]+)",\n "mine",\n },\n ["attack"] = {\n "attack the ([%a ]+) with the ([%a ]+)",\n "attack ([%a ]+) with ([%a ]+)",\n "attack ([%a ]+)",\n "attack",\n "kill the ([%a ]+) with the ([%a ]+)",\n "kill ([%a ]+) with ([%a ]+)",\n "kill ([%a ]+)",\n "kill",\n "hit the ([%a ]+) with the ([%a ]+)",\n "hit ([%a ]+) with ([%a ]+)",\n "hit ([%a ]+)",\n "hit",\n },\n ["craft"] = {\n "craft a ([%a ]+)",\n "craft some ([%a ]+)",\n "craft ([%a ]+)",\n "craft",\n "make a ([%a ]+)",\n "make some ([%a ]+)",\n "make ([%a ]+)",\n "make",\n },\n ["build"] = {\n "build ([%a ]+) out of ([%a ]+)",\n "build ([%a ]+) from ([%a ]+)",\n "build ([%a ]+)",\n "build",\n },\n ["eat"] = {\n "eat a ([%a ]+)",\n "eat the ([%a ]+)",\n "eat ([%a ]+)",\n "eat",\n },\n ["help"] = {\n "help me",\n "help",\n },\n ["exit"] = {\n "exit",\n "quit",\n "goodbye",\n "good bye",\n "bye",\n "farewell",\n },\n}\n\nlocal commands = {}\nlocal function doCommand(text)\n if text == "" then\n commands.noinput()\n return\n end\n\n for sCommand, t in pairs(tMatches) do\n for _, sMatch in pairs(t) do\n local tCaptures = { string.match(text, "^" .. sMatch .. "$") }\n if #tCaptures ~= 0 then\n local fnCommand = commands[sCommand]\n if #tCaptures == 1 and tCaptures[1] == sMatch then\n fnCommand()\n else\n fnCommand(table.unpack(tCaptures))\n end\n return\n end\n end\n end\n commands.badinput()\nend\n\nfunction commands.wait()\n print("Time passes...")\nend\n\nfunction commands.look(_sTarget)\n local room = getRoom(x, y, z)\n if room.dark then\n print("It is pitch dark.")\n return\n end\n\n if _sTarget == nil then\n -- Look at the world\n if y == 0 then\n io.write("You are standing " .. tBiomes[room.nBiome] .. ". ")\n print(tDayCycle[getTimeOfDay()])\n else\n io.write("You are underground. ")\n if next(room.exits) ~= nil then\n print("You can travel " .. itemize(room.exits) .. ".")\n else\n print()\n end\n end\n if next(room.items) ~= nil then\n print("There is " .. itemize(room.items) .. " here.")\n end\n if room.trees then\n print("There are trees here.")\n end\n\n else\n -- Look at stuff\n if room.trees and (_sTarget == "tree" or _sTarget == "trees") then\n print("The trees look easy to break.")\n elseif _sTarget == "self" or _sTarget == "myself" then\n print("Very handsome.")\n else\n local tItem = nil\n local sItem = findItem(room.items, _sTarget)\n if sItem then\n tItem = room.items[sItem]\n else\n sItem = findItem(inventory, _sTarget)\n if sItem then\n tItem = inventory[sItem]\n end\n end\n\n if tItem then\n print(tItem.desc or "You see nothing special about " .. sItem .. ".")\n else\n print("You don\'t see any " .. _sTarget .. " here.")\n end\n end\n end\nend\n\nfunction commands.go(_sDir)\n local room = getRoom(x, y, z)\n if _sDir == nil then\n print("Go where?")\n return\n end\n\n if nGoWest ~= nil then\n if _sDir == "west" then\n nGoWest = nGoWest + 1\n if nGoWest > #tGoWest then\n nGoWest = 1\n end\n print(tGoWest[nGoWest])\n else\n if nGoWest > 0 or nTurn > 6 then\n nGoWest = nil\n end\n end\n end\n\n if room.exits[_sDir] == nil then\n print("You can\'t go that way.")\n return\n end\n\n if _sDir == "north" then\n z = z + 1\n elseif _sDir == "south" then\n z = z - 1\n elseif _sDir == "east" then\n x = x - 1\n elseif _sDir == "west" then\n x = x + 1\n elseif _sDir == "up" then\n y = y + 1\n elseif _sDir == "down" then\n y = y - 1\n else\n print("I don\'t understand that direction.")\n return\n end\n\n nTimeInRoom = 0\n doCommand("look")\nend\n\nfunction commands.dig(_sDir, _sTool)\n local room = getRoom(x, y, z)\n if _sDir == nil then\n print("Dig where?")\n return\n end\n\n local sTool = nil\n local tTool = nil\n if _sTool ~= nil then\n sTool = findItem(inventory, _sTool)\n if not sTool then\n print("You\'re not carrying a " .. _sTool .. ".")\n return\n end\n tTool = inventory[sTool]\n end\n\n local bActuallyDigging = room.exits[_sDir] ~= true\n if bActuallyDigging then\n if sTool == nil or tTool.toolType ~= "pick" then\n print("You need to use a pickaxe to dig through stone.")\n return\n end\n end\n\n if _sDir == "north" then\n room.exits.north = true\n z = z + 1\n getRoom(x, y, z).exits.south = true\n\n elseif _sDir == "south" then\n room.exits.south = true\n z = z - 1\n getRoom(x, y, z).exits.north = true\n\n elseif _sDir == "east" then\n room.exits.east = true\n x = x - 1\n getRoom(x, y, z).exits.west = true\n\n elseif _sDir == "west" then\n room.exits.west = true\n x = x + 1\n getRoom(x, y, z).exits.east = true\n\n elseif _sDir == "up" then\n if y == 0 then\n print("You can\'t dig that way.")\n return\n end\n\n room.exits.up = true\n if y == -1 then\n room.items["an exit to the surface"] = items["an exit to the surface"]\n end\n y = y + 1\n\n room = getRoom(x, y, z)\n room.exits.down = true\n if y == 0 then\n room.items["a cave entrance"] = items["a cave entrance"]\n end\n\n elseif _sDir == "down" then\n if y <= -3 then\n print("You hit bedrock.")\n return\n end\n\n room.exits.down = true\n if y == 0 then\n room.items["a cave entrance"] = items["a cave entrance"]\n end\n y = y - 1\n\n room = getRoom(x, y, z)\n room.exits.up = true\n if y == -1 then\n room.items["an exit to the surface"] = items["an exit to the surface"]\n end\n\n else\n print("I don\'t understand that direction.")\n return\n end\n\n --\n if bActuallyDigging then\n if _sDir == "down" and y == -1 or\n _sDir == "up" and y == 0 then\n inventory["some dirt"] = items["some dirt"]\n inventory["some stone"] = items["some stone"]\n print("You dig " .. _sDir .. " using " .. sTool .. " and collect some dirt and stone.")\n else\n inventory["some stone"] = items["some stone"]\n print("You dig " .. _sDir .. " using " .. sTool .. " and collect some stone.")\n end\n end\n\n nTimeInRoom = 0\n doCommand("look")\nend\n\nfunction commands.inventory()\n print("You are carrying " .. itemize(inventory) .. ".")\nend\n\nfunction commands.drop(_sItem)\n if _sItem == nil then\n print("Drop what?")\n return\n end\n\n local room = getRoom(x, y, z)\n local sItem = findItem(inventory, _sItem)\n if sItem then\n local tItem = inventory[sItem]\n if tItem.droppable == false then\n print("You can\'t drop that.")\n else\n room.items[sItem] = tItem\n inventory[sItem] = nil\n print("Dropped.")\n end\n else\n print("You don\'t have a " .. _sItem .. ".")\n end\nend\n\nfunction commands.place(_sItem)\n if _sItem == nil then\n print("Place what?")\n return\n end\n\n if _sItem == "torch" or _sItem == "a torch" then\n local room = getRoom(x, y, z)\n if inventory["some torches"] or inventory["a torch"] then\n inventory["a torch"] = nil\n room.items["a torch"] = items["a torch"]\n if room.dark then\n print("The cave lights up under the torchflame.")\n room.dark = false\n elseif y == 0 and not isSunny() then\n print("The night gets a little brighter.")\n else\n print("Placed.")\n end\n else\n print("You don\'t have torches.")\n end\n return\n end\n\n commands.drop(_sItem)\nend\n\nfunction commands.take(_sItem)\n if _sItem == nil then\n print("Take what?")\n return\n end\n\n local room = getRoom(x, y, z)\n local sItem = findItem(room.items, _sItem)\n if sItem then\n local tItem = room.items[sItem]\n if tItem.heavy == true then\n print("You can\'t carry " .. sItem .. ".")\n elseif tItem.ore == true then\n print("You need to mine this ore.")\n else\n if tItem.infinite ~= true then\n room.items[sItem] = nil\n end\n inventory[sItem] = tItem\n\n if inventory["some torches"] and inventory["a torch"] then\n inventory["a torch"] = nil\n end\n if sItem == "a torch" and y < 0 then\n room.dark = true\n print("The cave plunges into darkness.")\n else\n print("Taken.")\n end\n end\n else\n print("You don\'t see a " .. _sItem .. " here.")\n end\nend\n\nfunction commands.mine(_sItem, _sTool)\n if _sItem == nil then\n print("Mine what?")\n return\n end\n if _sTool == nil then\n print("Mine " .. _sItem .. " with what?")\n return\n end\n commands.cbreak(_sItem, _sTool)\nend\n\nfunction commands.attack(_sItem, _sTool)\n if _sItem == nil then\n print("Attack what?")\n return\n end\n commands.cbreak(_sItem, _sTool)\nend\n\nfunction commands.cbreak(_sItem, _sTool)\n if _sItem == nil then\n print("Break what?")\n return\n end\n\n local sTool = nil\n if _sTool ~= nil then\n sTool = findItem(inventory, _sTool)\n if sTool == nil then\n print("You\'re not carrying a " .. _sTool .. ".")\n return\n end\n end\n\n local room = getRoom(x, y, z)\n if _sItem == "tree" or _sItem == "trees" or _sItem == "a tree" then\n print("The tree breaks into blocks of wood, which you pick up.")\n inventory["some wood"] = items["some wood"]\n return\n elseif _sItem == "self" or _sItem == "myself" then\n if term.isColour() then\n term.setTextColour(colours.red)\n end\n print("You have died.")\n print("Score: &e0")\n term.setTextColour(colours.white)\n bRunning = false\n return\n end\n\n local sItem = findItem(room.items, _sItem)\n if sItem then\n local tItem = room.items[sItem]\n if tItem.ore == true then\n -- Breaking ore\n if not sTool then\n print("You need a tool to break this ore.")\n return\n end\n local tTool = inventory[sTool]\n if tTool.tool then\n if tTool.toolLevel < tItem.toolLevel then\n print(sTool .. " is not strong enough to break this ore.")\n elseif tTool.toolType ~= tItem.toolType then\n print("You need a different kind of tool to break this ore.")\n else\n print("The ore breaks, dropping " .. sItem .. ", which you pick up.")\n inventory[sItem] = items[sItem]\n if tItem.infinite ~= true then\n room.items[sItem] = nil\n end\n end\n else\n print("You can\'t break " .. sItem .. " with " .. sTool .. ".")\n end\n\n elseif tItem.creature == true then\n -- Fighting monsters (or pigs)\n local toolLevel = 0\n local tTool = nil\n if sTool then\n tTool = inventory[sTool]\n if tTool.toolType == "sword" then\n toolLevel = tTool.toolLevel\n end\n end\n\n local tChances = { 0.2, 0.4, 0.55, 0.8, 1 }\n if math.random() <= tChances[toolLevel + 1] then\n room.items[sItem] = nil\n print("The " .. tItem.aliases[1] .. " dies.")\n\n if tItem.drops then\n for _, sDrop in pairs(tItem.drops) do\n if not room.items[sDrop] then\n print("The " .. tItem.aliases[1] .. " dropped " .. sDrop .. ".")\n room.items[sDrop] = items[sDrop]\n end\n end\n end\n\n if tItem.monster then\n room.nMonsters = room.nMonsters - 1\n end\n else\n print("The " .. tItem.aliases[1] .. " is injured by your blow.")\n end\n\n if tItem.hitDrops then\n for _, sDrop in pairs(tItem.hitDrops) do\n if not room.items[sDrop] then\n print("The " .. tItem.aliases[1] .. " dropped " .. sDrop .. ".")\n room.items[sDrop] = items[sDrop]\n end\n end\n end\n\n else\n print("You can\'t break " .. sItem .. ".")\n end\n else\n print("You don\'t see a " .. _sItem .. " here.")\n end\nend\n\nfunction commands.craft(_sItem)\n if _sItem == nil then\n print("Craft what?")\n return\n end\n\n if _sItem == "computer" or _sItem == "a computer" then\n print("By creating a computer in a computer in a computer, you tear a hole in the spacetime continuum from which no mortal being can escape.")\n if term.isColour() then\n term.setTextColour(colours.red)\n end\n print("You have died.")\n print("Score: &e0")\n term.setTextColour(colours.white)\n bRunning = false\n return\n end\n\n local sItem = findItem(items, _sItem)\n local tRecipe = sItem and tRecipes[sItem] or nil\n if tRecipe then\n for _, sReq in ipairs(tRecipe) do\n if inventory[sReq] == nil then\n print("You don\'t have the items you need to craft " .. sItem .. ".")\n return\n end\n end\n\n for _, sReq in ipairs(tRecipe) do\n inventory[sReq] = nil\n end\n inventory[sItem] = items[sItem]\n if inventory["some torches"] and inventory["a torch"] then\n inventory["a torch"] = nil\n end\n print("Crafted.")\n else\n print("You don\'t know how to make " .. (sItem or _sItem) .. ".")\n end\nend\n\nfunction commands.build(_sThing, _sMaterial)\n if _sThing == nil then\n print("Build what?")\n return\n end\n\n local sMaterial = nil\n if _sMaterial == nil then\n for sItem, tItem in pairs(inventory) do\n if tItem.material then\n sMaterial = sItem\n break\n end\n end\n if sMaterial == nil then\n print("You don\'t have any building materials.")\n return\n end\n else\n sMaterial = findItem(inventory, _sMaterial)\n if not sMaterial then\n print("You don\'t have any " .. _sMaterial)\n return\n end\n\n if inventory[sMaterial].material ~= true then\n print(sMaterial .. " is not a good building material.")\n return\n end\n end\n\n local alias = nil\n if string.sub(_sThing, 1, 1) == "a" then\n alias = string.match(_sThing, "a ([%a ]+)")\n end\n\n local room = getRoom(x, y, z)\n inventory[sMaterial] = nil\n room.items[_sThing] = {\n heavy = true,\n aliases = { alias },\n desc = "As you look at your creation (made from " .. sMaterial .. "), you feel a swelling sense of pride.",\n }\n\n print("Your construction is complete.")\nend\n\nfunction commands.help()\n local sText =\n "Welcome to adventure, the greatest text adventure game on CraftOS. " ..\n "To get around the world, type actions, and the adventure will " ..\n "be read back to you. The actions available to you are go, look, inspect, inventory, " ..\n "take, drop, place, punch, attack, mine, dig, craft, build, eat and exit."\n print(sText)\nend\n\nfunction commands.eat(_sItem)\n if _sItem == nil then\n print("Eat what?")\n return\n end\n\n local sItem = findItem(inventory, _sItem)\n if not sItem then\n print("You don\'t have any " .. _sItem .. ".")\n return\n end\n\n local tItem = inventory[sItem]\n if tItem.food then\n print("That was delicious!")\n inventory[sItem] = nil\n\n if bInjured then\n print("You are no longer injured.")\n bInjured = false\n end\n else\n print("You can\'t eat " .. sItem .. ".")\n end\nend\n\nfunction commands.exit()\n bRunning = false\nend\n\nfunction commands.badinput()\n local tResponses = {\n "I don\'t understand.",\n "I don\'t understand you.",\n "You can\'t do that.",\n "Nope.",\n "Huh?",\n "Say again?",\n "That\'s crazy talk.",\n "Speak clearly.",\n "I\'ll think about it.",\n "Let me get back to you on that one.",\n "That doesn\'t make any sense.",\n "What?",\n }\n print(tResponses[math.random(1, #tResponses)])\nend\n\nfunction commands.noinput()\n local tResponses = {\n "Speak up.",\n "Enunciate.",\n "Project your voice.",\n "Don\'t be shy.",\n "Use your words.",\n }\n print(tResponses[math.random(1, #tResponses)])\nend\n\nlocal function simulate()\n local bNewMonstersThisRoom = false\n\n -- Spawn monsters in nearby rooms\n for sx = -2, 2 do\n for sy = -1, 1 do\n for sz = -2, 2 do\n local h = y + sy\n if h >= -3 and h <= 0 then\n local room = getRoom(x + sx, h, z + sz)\n\n -- Spawn monsters\n if room.nMonsters < 2 and\n (h == 0 and not isSunny() and not room.items["a torch"] or room.dark) and\n math.random(1, 6) == 1 then\n\n local sMonster = tMonsters[math.random(1, #tMonsters)]\n if room.items[sMonster] == nil then\n room.items[sMonster] = items[sMonster]\n room.nMonsters = room.nMonsters + 1\n\n if sx == 0 and sy == 0 and sz == 0 and not room.dark then\n print("From the shadows, " .. sMonster .. " appears.")\n bNewMonstersThisRoom = true\n end\n end\n end\n\n -- Burn monsters\n if h == 0 and isSunny() then\n for _, sMonster in ipairs(tMonsters) do\n if room.items[sMonster] and items[sMonster].nocturnal then\n room.items[sMonster] = nil\n if sx == 0 and sy == 0 and sz == 0 and not room.dark then\n print("With the sun high in the sky, the " .. items[sMonster].aliases[1] .. " bursts into flame and dies.")\n end\n room.nMonsters = room.nMonsters - 1\n end\n end\n end\n end\n end\n end\n end\n\n -- Make monsters attack\n local room = getRoom(x, y, z)\n if nTimeInRoom >= 2 and not bNewMonstersThisRoom then\n for _, sMonster in ipairs(tMonsters) do\n if room.items[sMonster] then\n if math.random(1, 4) == 1 and\n not (y == 0 and isSunny() and sMonster == "a spider") then\n if sMonster == "a creeper" then\n if room.dark then\n print("A creeper explodes.")\n else\n print("The creeper explodes.")\n end\n room.items[sMonster] = nil\n room.nMonsters = room.nMonsters - 1\n else\n if room.dark then\n print("A " .. items[sMonster].aliases[1] .. " attacks you.")\n else\n print("The " .. items[sMonster].aliases[1] .. " attacks you.")\n end\n end\n\n if bInjured then\n if term.isColour() then\n term.setTextColour(colours.red)\n end\n print("You have died.")\n print("Score: &e0")\n term.setTextColour(colours.white)\n bRunning = false\n return\n else\n bInjured = true\n end\n\n break\n end\n end\n end\n end\n\n -- Always print this\n if bInjured then\n if term.isColour() then\n term.setTextColour(colours.red)\n end\n print("You are injured.")\n term.setTextColour(colours.white)\n end\n\n -- Advance time\n nTurn = nTurn + 1\n nTimeInRoom = nTimeInRoom + 1\nend\n\ndoCommand("look")\nsimulate()\n\nlocal tCommandHistory = {}\nwhile bRunning do\n if term.isColour() then\n term.setTextColour(colours.yellow)\n end\n write("? ")\n term.setTextColour(colours.white)\n\n local sRawLine = read(nil, tCommandHistory)\n table.insert(tCommandHistory, sRawLine)\n\n local sLine = nil\n for match in string.gmatch(sRawLine, "%a+") do\n if sLine then\n sLine = sLine .. " " .. string.lower(match)\n else\n sLine = string.lower(match)\n end\n end\n\n doCommand(sLine or "")\n if bRunning then\n simulate()\n end\nend\n',"rom/programs/fun/dj.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\n\nlocal function printUsage()\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usages:")\n print(programName .. " play")\n print(programName .. " play <drive>")\n print(programName .. " stop")\nend\n\nif #tArgs > 2 then\n printUsage()\n return\nend\n\nlocal sCommand = tArgs[1]\nif sCommand == "stop" then\n -- Stop audio\n disk.stopAudio()\n\nelseif sCommand == "play" or sCommand == nil then\n -- Play audio\n local sName = tArgs[2]\n if sName == nil then\n -- No disc specified, pick one at random\n local tNames = {}\n for _, sName in ipairs(peripheral.getNames()) do\n if disk.isPresent(sName) and disk.hasAudio(sName) then\n table.insert(tNames, sName)\n end\n end\n if #tNames == 0 then\n print("No Music Discs in attached disk drives")\n return\n end\n sName = tNames[math.random(1, #tNames)]\n end\n\n -- Play the disc\n if disk.isPresent(sName) and disk.hasAudio(sName) then\n print("Playing " .. disk.getAudioTitle(sName))\n disk.playAudio(sName)\n else\n print("No Music Disc in disk drive: " .. sName)\n return\n end\n\nelse\n printUsage()\n\nend\n',"rom/programs/fun/hello.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif term.isColour() then\n term.setTextColour(2 ^ math.random(0, 15))\nend\ntextutils.slowPrint("Hello World!")\nterm.setTextColour(colours.white)\n',"rom/programs/fun/speaker.lua":'-- SPDX-FileCopyrightText: 2021 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\nlocal function get_speakers(name)\n if name then\n local speaker = peripheral.wrap(name)\n if speaker == nil then\n error(("Speaker %q does not exist"):format(name), 0)\n return\n elseif not peripheral.hasType(name, "speaker") then\n error(("%q is not a speaker"):format(name), 0)\n end\n\n return { speaker }\n else\n local speakers = { peripheral.find("speaker") }\n if #speakers == 0 then\n error("No speakers attached", 0)\n end\n return speakers\n end\nend\n\nlocal function pcm_decoder(chunk)\n local buffer = {}\n for i = 1, #chunk do\n buffer[i] = chunk:byte(i) - 128\n end\n return buffer\nend\n\nlocal function report_invalid_format(format)\n printError(("speaker cannot play %s files."):format(format))\n local pp = require "cc.pretty"\n pp.print("Run \'" .. pp.text("help speaker", colours.lightGrey) .. "\' for information on supported formats.")\nend\n\n\nlocal cmd = ...\nif cmd == "stop" then\n local _, name = ...\n for _, speaker in pairs(get_speakers(name)) do speaker.stop() end\nelseif cmd == "play" then\n local _, file, name = ...\n local speaker = get_speakers(name)[1]\n\n local handle, err\n if http and file:match("^https?://") then\n print("Downloading...")\n handle, err = http.get{ url = file, binary = true }\n else\n handle, err = fs.open(file, "rb")\n end\n\n if not handle then\n printError("Could not play audio:")\n error(err, 0)\n end\n\n local start = handle.read(4)\n local pcm = false\n local size = 16 * 1024 - 4\n if start == "RIFF" then\n handle.read(4)\n if handle.read(8) ~= "WAVEfmt " then\n handle.close()\n error("Could not play audio: Unsupported WAV file", 0)\n end\n\n local fmtsize = ("<I4"):unpack(handle.read(4))\n local fmt = handle.read(fmtsize)\n local format, channels, rate, _, _, bits = ("<I2I2I4I4I2I2"):unpack(fmt)\n if not ((format == 1 and bits == 8) or (format == 0xFFFE and bits == 1)) then\n handle.close()\n error("Could not play audio: Unsupported WAV file", 0)\n end\n if channels ~= 1 or rate ~= 48000 then\n print("Warning: Only 48 kHz mono WAV files are supported. This file may not play correctly.")\n end\n if format == 0xFFFE then\n local guid = fmt:sub(25)\n if guid ~= "\\x3A\\xC1\\xFA\\x38\\x81\\x1D\\x43\\x61\\xA4\\x0D\\xCE\\x53\\xCA\\x60\\x7C\\xD1" then -- DFPWM format GUID\n handle.close()\n error("Could not play audio: Unsupported WAV file", 0)\n end\n size = size + 4\n else\n pcm = true\n size = 16 * 1024 * 8\n end\n\n repeat\n local chunk = handle.read(4)\n if chunk == nil then\n handle.close()\n error("Could not play audio: Invalid WAV file", 0)\n elseif chunk ~= "data" then -- Ignore extra chunks\n local size = ("<I4"):unpack(handle.read(4))\n handle.read(size)\n end\n until chunk == "data"\n\n handle.read(4)\n start = nil\n -- Detect several other common audio files.\n elseif start == "OggS" then return report_invalid_format("Ogg")\n elseif start == "fLaC" then return report_invalid_format("FLAC")\n elseif start:sub(1, 3) == "ID3" then return report_invalid_format("MP3")\n elseif start == "<!DO" --[[<!DOCTYPE]] then return report_invalid_format("HTML")\n end\n\n print("Playing " .. file)\n\n local decoder = pcm and pcm_decoder or require "cc.audio.dfpwm".make_decoder()\n while true do\n local chunk = handle.read(size)\n if not chunk then break end\n if start then\n chunk, start = start .. chunk, nil\n size = size + 4\n end\n\n local buffer = decoder(chunk)\n while not speaker.playAudio(buffer) do\n os.pullEvent("speaker_audio_empty")\n end\n end\n\n handle.close()\nelse\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage:")\n print(programName .. " play <file or url> [speaker]")\n print(programName .. " stop [speaker]")\nend\n',"rom/programs/fun/worm.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n-- Display the start screen\nlocal w, h = term.getSize()\n\nlocal headingColour, textColour, wormColour, fruitColour\nif term.isColour() then\n headingColour = colours.yellow\n textColour = colours.white\n wormColour = colours.green\n fruitColour = colours.red\nelse\n headingColour = colours.white\n textColour = colours.white\n wormColour = colours.white\n fruitColour = colours.white\nend\n\nlocal function printCentred(y, s)\n local x = math.floor((w - #s) / 2)\n term.setCursorPos(x, y)\n --term.clearLine()\n term.write(s)\nend\n\nlocal xVel, yVel = 1, 0\nlocal xPos, yPos = math.floor(w / 2), math.floor(h / 2)\nlocal pxVel, pyVel = nil, nil\nlocal nExtraLength = 6\nlocal bRunning = true\n\nlocal tailX, tailY = xPos, yPos\nlocal nScore = 0\nlocal nDifficulty = 2\nlocal nSpeed, nInterval\n\n-- Setup the screen\nlocal screen = {}\nfor x = 1, w do\n screen[x] = {}\n for y = 1, h do\n screen[x][y] = {}\n end\nend\nscreen[xPos][yPos] = { snake = true }\n\nlocal nFruit = 1\nlocal tFruits = {\n "A", "B", "C", "D", "E", "F", "G", "H",\n "I", "J", "K", "L", "M", "N", "O", "P",\n "Q", "R", "S", "T", "U", "V", "W", "X",\n "Y", "Z",\n "a", "b", "c", "d", "e", "f", "g", "h",\n "i", "j", "k", "l", "m", "n", "o", "p",\n "q", "r", "s", "t", "u", "v", "w", "x",\n "y", "z",\n "1", "2", "3", "4", "5", "6", "7", "8", "9", "0",\n "@", "$", "%", "#", "&", "!", "?", "+", "*", "~",\n}\n\nlocal function addFruit()\n while true do\n local x = math.random(1, w)\n local y = math.random(2, h)\n local fruit = screen[x][y]\n if fruit.snake == nil and fruit.wall == nil and fruit.fruit == nil then\n screen[x][y] = { fruit = true }\n term.setCursorPos(x, y)\n term.setBackgroundColour(fruitColour)\n term.write(" ")\n term.setBackgroundColour(colours.black)\n break\n end\n end\n\n nFruit = nFruit + 1\n if nFruit > #tFruits then\n nFruit = 1\n end\nend\n\nlocal function drawMenu()\n term.setTextColour(headingColour)\n term.setCursorPos(1, 1)\n term.write("SCORE ")\n\n term.setTextColour(textColour)\n term.setCursorPos(7, 1)\n term.write(tostring(nScore))\n\n term.setTextColour(headingColour)\n term.setCursorPos(w - 11, 1)\n term.write("DIFFICULTY ")\n\n term.setTextColour(textColour)\n term.setCursorPos(w, 1)\n term.write(tostring(nDifficulty or "?"))\n\n term.setTextColour(colours.white)\nend\n\nlocal function update( )\n if pxVel and pyVel then\n xVel, yVel = pxVel, pyVel\n pxVel, pyVel = nil, nil\n end\n\n -- Remove the tail\n if nExtraLength == 0 then\n local tail = screen[tailX][tailY]\n screen[tailX][tailY] = {}\n term.setCursorPos(tailX, tailY)\n term.write(" ")\n tailX = tail.nextX\n tailY = tail.nextY\n else\n nExtraLength = nExtraLength - 1\n end\n\n -- Update the head\n local head = screen[xPos][yPos]\n local newXPos = xPos + xVel\n local newYPos = yPos + yVel\n if newXPos < 1 then\n newXPos = w\n elseif newXPos > w then\n newXPos = 1\n end\n if newYPos < 2 then\n newYPos = h\n elseif newYPos > h then\n newYPos = 2\n end\n\n local newHead = screen[newXPos][newYPos]\n if newHead.snake == true or newHead.wall == true then\n bRunning = false\n\n else\n if newHead.fruit == true then\n nScore = nScore + 10\n nExtraLength = nExtraLength + 1\n addFruit()\n end\n xPos = newXPos\n yPos = newYPos\n head.nextX = newXPos\n head.nextY = newYPos\n screen[newXPos][newYPos] = { snake = true }\n\n end\n\n term.setCursorPos(xPos, yPos)\n term.setBackgroundColour(wormColour)\n term.write(" ")\n term.setBackgroundColour(colours.black)\n\n drawMenu()\nend\n\n-- Display the frontend\nterm.clear()\nlocal function drawFrontend()\n --term.setTextColour( titleColour )\n --printCentred( math.floor(h/2) - 4, " W O R M " )\n\n term.setTextColour(headingColour)\n printCentred(math.floor(h / 2) - 3, "")\n printCentred(math.floor(h / 2) - 2, " SELECT DIFFICULTY ")\n printCentred(math.floor(h / 2) - 1, "")\n\n printCentred(math.floor(h / 2) + 0, " ")\n printCentred(math.floor(h / 2) + 1, " ")\n printCentred(math.floor(h / 2) + 2, " ")\n printCentred(math.floor(h / 2) - 1 + nDifficulty, " [ ] ")\n\n term.setTextColour(textColour)\n printCentred(math.floor(h / 2) + 0, "EASY")\n printCentred(math.floor(h / 2) + 1, "MEDIUM")\n printCentred(math.floor(h / 2) + 2, "HARD")\n printCentred(math.floor(h / 2) + 3, "")\n\n term.setTextColour(colours.white)\nend\n\ndrawMenu()\ndrawFrontend()\nwhile true do\n local _, key = os.pullEvent("key")\n if key == keys.up or key == keys.w then\n -- Up\n if nDifficulty > 1 then\n nDifficulty = nDifficulty - 1\n drawMenu()\n drawFrontend()\n end\n elseif key == keys.down or key == keys.s then\n -- Down\n if nDifficulty < 3 then\n nDifficulty = nDifficulty + 1\n drawMenu()\n drawFrontend()\n end\n elseif key == keys.enter or key == keys.numPadEnter then\n -- Enter/Numpad Enter\n break\n end\nend\n\nlocal tSpeeds = { 5, 10, 25 }\nnSpeed = tSpeeds[nDifficulty]\nnInterval = 1 / nSpeed\n\n-- Grow the snake to its intended size\nterm.clear()\ndrawMenu()\nscreen[tailX][tailY].snake = true\nwhile nExtraLength > 0 do\n update()\nend\naddFruit()\naddFruit()\n\n-- Play the game\nlocal timer = os.startTimer(0)\nwhile bRunning do\n local event, p1 = os.pullEvent()\n if event == "timer" and p1 == timer then\n timer = os.startTimer(nInterval)\n update(false)\n\n elseif event == "key" then\n local key = p1\n if key == keys.up or key == keys.w then\n -- Up\n if yVel == 0 then\n pxVel, pyVel = 0, -1\n end\n elseif key == keys.down or key == keys.s then\n -- Down\n if yVel == 0 then\n pxVel, pyVel = 0, 1\n end\n elseif key == keys.left or key == keys.a then\n -- Left\n if xVel == 0 then\n pxVel, pyVel = -1, 0\n end\n\n elseif key == keys.right or key == keys.d then\n -- Right\n if xVel == 0 then\n pxVel, pyVel = 1, 0\n end\n\n end\n end\nend\n\n-- Display the gameover screen\nterm.setTextColour(headingColour)\nprintCentred(math.floor(h / 2) - 2, " ")\nprintCentred(math.floor(h / 2) - 1, " G A M E O V E R ")\n\nterm.setTextColour(textColour)\nprintCentred(math.floor(h / 2) + 0, " ")\nprintCentred(math.floor(h / 2) + 1, " FINAL SCORE " .. nScore .. " ")\nprintCentred(math.floor(h / 2) + 2, " ")\nterm.setTextColour(colours.white)\n\nlocal timer = os.startTimer(2.5)\nrepeat\n local e, p = os.pullEvent()\n if e == "timer" and p == timer then\n term.setTextColour(textColour)\n printCentred(math.floor(h / 2) + 2, " PRESS ANY KEY ")\n printCentred(math.floor(h / 2) + 3, " ")\n term.setTextColour(colours.white)\n end\nuntil e == "char"\n\nterm.clear()\nterm.setCursorPos(1, 1)\n',"rom/programs/gps.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal function printUsage()\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usages:")\n print(programName .. " host")\n print(programName .. " host <x> <y> <z>")\n print(programName .. " locate")\nend\n\nlocal tArgs = { ... }\nif #tArgs < 1 then\n printUsage()\n return\nend\n\n local sCommand = tArgs[1]\nif sCommand == "locate" then\n -- "gps locate"\n -- Just locate this computer (this will print the results)\n gps.locate(2, true)\n\nelseif sCommand == "host" then\n -- "gps host"\n -- Act as a GPS host\n if pocket then\n print("GPS Hosts must be stationary")\n return\n end\n\n -- Find a modem\n local sModemSide = nil\n for _, sSide in ipairs(rs.getSides()) do\n if peripheral.getType(sSide) == "modem" and peripheral.call(sSide, "isWireless") then\n sModemSide = sSide\n break\n end\n end\n\n if sModemSide == nil then\n print("No wireless modems found. 1 required.")\n return\n end\n\n -- Determine position\n local x, y, z\n if #tArgs >= 4 then\n -- Position is manually specified\n x = tonumber(tArgs[2])\n y = tonumber(tArgs[3])\n z = tonumber(tArgs[4])\n if x == nil or y == nil or z == nil then\n printUsage()\n return\n end\n print("Position is " .. x .. "," .. y .. "," .. z)\n else\n -- Position is to be determined using locate\n x, y, z = gps.locate(2, true)\n if x == nil then\n print("Run \\"gps host <x> <y> <z>\\" to set position manually")\n return\n end\n end\n\n -- Open a channel\n local modem = peripheral.wrap(sModemSide)\n print("Opening channel on modem " .. sModemSide)\n modem.open(gps.CHANNEL_GPS)\n\n -- Serve requests indefinitely\n local nServed = 0\n while true do\n local e, p1, p2, p3, p4, p5 = os.pullEvent("modem_message")\n if e == "modem_message" then\n -- We received a message from a modem\n local sSide, sChannel, sReplyChannel, sMessage, nDistance = p1, p2, p3, p4, p5\n if sSide == sModemSide and sChannel == gps.CHANNEL_GPS and sMessage == "PING" and nDistance then\n -- We received a ping message on the GPS channel, send a response\n modem.transmit(sReplyChannel, gps.CHANNEL_GPS, { x, y, z })\n\n -- Print the number of requests handled\n nServed = nServed + 1\n if nServed > 1 then\n local _, y = term.getCursorPos()\n term.setCursorPos(1, y - 1)\n end\n print(nServed .. " GPS requests served")\n end\n end\n end\nelse\n -- "gps somethingelse"\n -- Error\n printUsage()\nend\n',"rom/programs/help.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\nlocal sTopic\nif #tArgs > 0 then\n sTopic = tArgs[1]\nelse\n sTopic = "intro"\nend\n\nif sTopic == "index" then\n print("Help topics available:")\n local tTopics = help.topics()\n textutils.pagedTabulate(tTopics)\n return\nend\n\nlocal strings = require "cc.strings"\n\nlocal function min_of(a, b, default)\n if not a and not b then return default end\n if not a then return b end\n if not b then return a end\n return math.min(a, b)\nend\n\n--[[- Parse a markdown string, extracting headings and highlighting some basic\nconstructs.\n\nThe implementation of this is horrible. SquidDev shouldn\'t be allowed to write\nparsers, especially ones they think might be "performance critical".\n]]\nlocal function parse_markdown(text)\n local len = #text\n local oob = len + 1\n\n -- Some patterns to match headers and bullets on the start of lines.\n -- The `%f[^\\n\\0]` is some wonderful logic to match the start of a line /or/\n -- the start of the document.\n local heading = "%f[^\\n\\0](#+ +)([^\\n]*)"\n local bullet = "%f[^\\n\\0]( *)[.*]( +)"\n local code = "`([^`]+)`"\n\n local new_text, fg, bg = "", "", ""\n local function append(txt, fore, back)\n new_text = new_text .. txt\n fg = fg .. (fore or "0"):rep(#txt)\n bg = bg .. (back or "f"):rep(#txt)\n end\n\n local next_header = text:find(heading)\n local next_bullet = text:find(bullet)\n local next_block = min_of(next_header, next_bullet, oob)\n\n local next_code, next_code_end = text:find(code)\n\n local sections = {}\n\n local start = 1\n while start <= len do\n if start == next_block then\n if start == next_header then\n local _, fin, head, content = text:find(heading, start)\n sections[#new_text + 1] = content\n append(head .. content, "4", "f")\n start = fin + 1\n\n next_header = text:find(heading, start)\n else\n local _, fin, space, content = text:find(bullet, start)\n append(space .. "\\7" .. content)\n start = fin + 1\n\n next_bullet = text:find(bullet, start)\n end\n\n next_block = min_of(next_header, next_bullet, oob)\n elseif next_code and next_code_end < next_block then\n -- Basic inline code blocks\n if start < next_code then append(text:sub(start, next_code - 1)) end\n local content = text:match(code, next_code)\n append(content, "0", "7")\n\n start = next_code_end + 1\n next_code, next_code_end = text:find(code, start)\n else\n -- Normal text\n append(text:sub(start, next_block - 1))\n start = next_block\n\n -- Rescan for a new code block\n if next_code then next_code, next_code_end = text:find(code, start) end\n end\n end\n\n return new_text, fg, bg, sections\nend\n\nlocal function word_wrap_basic(text, width)\n local lines, fg, bg = strings.wrap(text, width), {}, {}\n local fg_line, bg_line = ("0"):rep(width), ("f"):rep(width)\n\n -- Normalise the strings suitable for use with blit. We could skip this and\n -- just use term.write, but saves us a clearLine call.\n for k, line in pairs(lines) do\n lines[k] = strings.ensure_width(line, width)\n fg[k] = fg_line\n bg[k] = bg_line\n end\n\n return lines, fg, bg, {}\nend\n\nlocal function word_wrap_markdown(text, width)\n -- Add in styling for Markdown-formatted text.\n local text, fg, bg, sections = parse_markdown(text)\n\n local lines = strings.wrap(text, width)\n local fglines, bglines, section_list, section_n = {}, {}, {}, 1\n\n -- Normalise the strings suitable for use with blit. We could skip this and\n -- just use term.write, but saves us a clearLine call.\n local start = 1\n for k, line in pairs(lines) do\n -- I hate this with a burning passion, but it works!\n local pos = text:find(line, start, true)\n lines[k], fglines[k], bglines[k] =\n strings.ensure_width(line, width),\n strings.ensure_width(fg:sub(pos, pos + #line), width),\n strings.ensure_width(bg:sub(pos, pos + #line), width)\n\n if sections[pos] then\n section_list[section_n], section_n = { content = sections[pos], offset = k - 1 }, section_n + 1\n end\n\n start = pos + 1\n end\n\n return lines, fglines, bglines, section_list\nend\n\nlocal sFile = help.lookup(sTopic)\nlocal file = sFile ~= nil and io.open(sFile) or nil\nif not file then\n printError("No help available")\n return\nend\n\nlocal contents = file:read("*a")\nfile:close()\n-- Trim trailing newlines from the file to avoid displaying a blank line.\nif contents:sub(-1) == "\\n" then contents:sub(1, -2) end\n\nlocal word_wrap = sFile:sub(-3) == ".md" and word_wrap_markdown or word_wrap_basic\nlocal width, height = term.getSize()\nlocal content_height = height - 1 -- Height of the content box.\nlocal lines, fg, bg, sections = word_wrap(contents, width)\nlocal print_height = #lines\n\n-- If we fit within the screen, just display without pagination.\nif print_height <= content_height then\n local _, y = term.getCursorPos()\n for i = 1, print_height do\n if y + i - 1 > height then\n term.scroll(1)\n term.setCursorPos(1, height)\n else\n term.setCursorPos(1, y + i - 1)\n end\n\n term.blit(lines[i], fg[i], bg[i])\n end\n return\nend\n\nlocal current_section = nil\nlocal offset = 0\n\n--- Find the currently visible section, or nil if this document has no sections.\n--\n-- This could potentially be a binary search, but right now it\'s not worth it.\nlocal function find_section()\n for i = #sections, 1, -1 do\n if sections[i].offset <= offset then\n return i\n end\n end\nend\n\nlocal function draw_menu()\n term.setTextColor(colors.yellow)\n term.setCursorPos(1, height)\n term.clearLine()\n\n local tag = "Help: " .. sTopic\n if current_section then\n tag = tag .. (" (%s)"):format(sections[current_section].content)\n end\n term.write(tag)\n\n if width >= #tag + 16 then\n term.setCursorPos(width - 14, height)\n term.write("Press Q to exit")\n end\nend\n\n\nlocal function draw()\n for y = 1, content_height do\n term.setCursorPos(1, y)\n if y + offset > print_height then\n -- Should only happen if we resize the terminal to a larger one\n -- than actually needed for the current text.\n term.clearLine()\n else\n term.blit(lines[y + offset], fg[y + offset], bg[y + offset])\n end\n end\n\n local new_section = find_section()\n if new_section ~= current_section then\n current_section = new_section\n draw_menu()\n end\nend\n\ndraw()\ndraw_menu()\n\nwhile true do\n local event, param = os.pullEventRaw()\n if event == "key" then\n if param == keys.up and offset > 0 then\n offset = offset - 1\n draw()\n elseif param == keys.down and offset < print_height - content_height then\n offset = offset + 1\n draw()\n elseif param == keys.pageUp and offset > 0 then\n offset = math.max(offset - content_height + 1, 0)\n draw()\n elseif param == keys.pageDown and offset < print_height - content_height then\n offset = math.min(offset + content_height - 1, print_height - content_height)\n draw()\n elseif param == keys.home then\n offset = 0\n draw()\n elseif param == keys.left and current_section and current_section > 1 then\n offset = sections[current_section - 1].offset\n draw()\n elseif param == keys.right and current_section and current_section < #sections then\n offset = sections[current_section + 1].offset\n draw()\n elseif param == keys["end"] then\n offset = print_height - content_height\n draw()\n elseif param == keys.q then\n sleep(0) -- Super janky, but consumes stray "char" events.\n break\n end\n elseif event == "mouse_scroll" then\n if param < 0 and offset > 0 then\n offset = offset - 1\n draw()\n elseif param > 0 and offset <= print_height - content_height then\n offset = offset + 1\n draw()\n end\n elseif event == "term_resize" then\n local new_width, new_height = term.getSize()\n\n if new_width ~= width then\n lines, fg, bg = word_wrap(contents, new_width)\n print_height = #lines\n end\n\n width, height = new_width, new_height\n content_height = height - 1\n offset = math.max(math.min(offset, print_height - content_height), 0)\n draw()\n draw_menu()\n elseif event == "terminate" then\n break\n end\nend\n\nterm.setCursorPos(1, 1)\nterm.clear()\n',"rom/programs/http/pastebin.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal function printUsage()\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usages:")\n print(programName .. " put <filename>")\n print(programName .. " get <code> <filename>")\n print(programName .. " run <code> <arguments>")\nend\n\nlocal tArgs = { ... }\nif #tArgs < 2 then\n printUsage()\n return\nend\n\nif not http then\n printError("Pastebin requires the http API, but it is not enabled")\n printError("Set http.enabled to true in CC: Tweaked\'s server config")\n return\nend\n\n--- Attempts to guess the pastebin ID from the given code or URL\nlocal function extractId(paste)\n local patterns = {\n "^([%a%d]+)$",\n "^https?://pastebin.com/([%a%d]+)$",\n "^pastebin.com/([%a%d]+)$",\n "^https?://pastebin.com/raw/([%a%d]+)$",\n "^pastebin.com/raw/([%a%d]+)$",\n }\n\n for i = 1, #patterns do\n local code = paste:match(patterns[i])\n if code then return code end\n end\n\n return nil\nend\n\nlocal function get(url)\n local paste = extractId(url)\n if not paste then\n io.stderr:write("Invalid pastebin code.\\n")\n io.write("The code is the ID at the end of the pastebin.com URL.\\n")\n return\n end\n\n write("Connecting to pastebin.com... ")\n -- Add a cache buster so that spam protection is re-checked\n local cacheBuster = ("%x"):format(math.random(0, 2 ^ 30))\n local response, err = http.get(\n "https://pastebin.com/raw/" .. textutils.urlEncode(paste) .. "?cb=" .. cacheBuster\n )\n\n if response then\n -- If spam protection is activated, we get redirected to /paste with Content-Type: text/html\n local headers = response.getResponseHeaders()\n if not headers["Content-Type"] or not headers["Content-Type"]:find("^text/plain") then\n io.stderr:write("Failed.\\n")\n print("Pastebin blocked the download due to spam protection. Please complete the captcha in a web browser: https://pastebin.com/" .. textutils.urlEncode(paste))\n return\n end\n\n print("Success.")\n\n local sResponse = response.readAll()\n response.close()\n return sResponse\n else\n io.stderr:write("Failed.\\n")\n print(err)\n end\nend\n\nlocal sCommand = tArgs[1]\nif sCommand == "put" then\n -- Upload a file to pastebin.com\n -- Determine file to upload\n local sFile = tArgs[2]\n local sPath = shell.resolve(sFile)\n if not fs.exists(sPath) or fs.isDir(sPath) then\n print("No such file")\n return\n end\n\n -- Read in the file\n local sName = fs.getName(sPath)\n local file = fs.open(sPath, "r")\n local sText = file.readAll()\n file.close()\n\n -- POST the contents to pastebin\n write("Connecting to pastebin.com... ")\n local key = "0ec2eb25b6166c0c27a394ae118ad829"\n local response = http.post(\n "https://pastebin.com/api/api_post.php",\n "api_option=paste&" ..\n "api_dev_key=" .. key .. "&" ..\n "api_paste_format=lua&" ..\n "api_paste_name=" .. textutils.urlEncode(sName) .. "&" ..\n "api_paste_code=" .. textutils.urlEncode(sText)\n )\n\n if response then\n print("Success.")\n\n local sResponse = response.readAll()\n response.close()\n\n local sCode = string.match(sResponse, "[^/]+$")\n print("Uploaded as " .. sResponse)\n print("Run \\"pastebin get " .. sCode .. "\\" to download anywhere")\n\n else\n print("Failed.")\n end\n\nelseif sCommand == "get" then\n -- Download a file from pastebin.com\n if #tArgs < 3 then\n printUsage()\n return\n end\n\n -- Determine file to download\n local sCode = tArgs[2]\n local sFile = tArgs[3]\n local sPath = shell.resolve(sFile)\n if fs.exists(sPath) then\n print("File already exists")\n return\n end\n\n -- GET the contents from pastebin\n local res = get(sCode)\n if res then\n local file = fs.open(sPath, "w")\n file.write(res)\n file.close()\n\n print("Downloaded as " .. sFile)\n end\nelseif sCommand == "run" then\n local sCode = tArgs[2]\n\n local res = get(sCode)\n if res then\n local func, err = load(res, sCode, "t", _ENV)\n if not func then\n printError(err)\n return\n end\n local success, msg = pcall(func, select(3, ...))\n if not success then\n printError(msg)\n end\n end\nelse\n printUsage()\n return\nend\n',"rom/programs/http/wget.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal function printUsage()\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage:")\n print(programName .. " <url> [filename]")\n print(programName .. " run <url>")\nend\n\nlocal tArgs = { ... }\n\nlocal run = false\nif tArgs[1] == "run" then\n table.remove(tArgs, 1)\n run = true\nend\n\nif #tArgs < 1 then\n printUsage()\n return\nend\n\nlocal url = table.remove(tArgs, 1)\n\nif not http then\n printError("wget requires the http API, but it is not enabled")\n printError("Set http.enabled to true in CC: Tweaked\'s server config")\n return\nend\n\nlocal function getFilename(sUrl)\n sUrl = sUrl:gsub("[#?].*" , ""):gsub("/+$" , "")\n return sUrl:match("/([^/]+)$")\nend\n\nlocal function get(sUrl)\n -- Check if the URL is valid\n local ok, err = http.checkURL(url)\n if not ok then\n printError(err or "Invalid URL.")\n return\n end\n\n write("Connecting to " .. sUrl .. "... ")\n\n local response = http.get(sUrl , nil , true)\n if not response then\n print("Failed.")\n return nil\n end\n\n print("Success.")\n\n local sResponse = response.readAll()\n response.close()\n return sResponse or ""\nend\n\nif run then\n local res = get(url)\n if not res then return end\n\n local func, err = load(res, getFilename(url), "t", _ENV)\n if not func then\n printError(err)\n return\n end\n\n local ok, err = pcall(func, table.unpack(tArgs))\n if not ok then\n printError(err)\n end\nelse\n local sFile = tArgs[1] or getFilename(url) or url\n local sPath = shell.resolve(sFile)\n if fs.exists(sPath) then\n print("File already exists")\n return\n end\n\n local res = get(url)\n if not res then return end\n\n local file, err = fs.open(sPath, "wb")\n if not file then\n printError("Cannot save file: " .. err)\n return\n end\n\n file.write(res)\n file.close()\n\n print("Downloaded as " .. sFile)\nend\n',"rom/programs/id.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal sDrive = nil\nlocal tArgs = { ... }\nif #tArgs > 0 then\n sDrive = tostring(tArgs[1])\nend\n\nif sDrive == nil then\n print("This is computer #" .. os.getComputerID())\n\n local label = os.getComputerLabel()\n if label then\n print("This computer is labelled \\"" .. label .. "\\"")\n end\n\nelse\n if disk.hasAudio(sDrive) then\n local title = disk.getAudioTitle(sDrive)\n if title then\n print("Has audio track \\"" .. title .. "\\"")\n else\n print("Has untitled audio")\n end\n return\n end\n\n if not disk.hasData(sDrive) then\n print("No disk in drive " .. sDrive)\n return\n end\n\n local id = disk.getID(sDrive)\n if id then\n print("The disk is #" .. id)\n else\n print("Non-disk data source")\n end\n\n local label = disk.getLabel(sDrive)\n if label then\n print("Labelled \\"" .. label .. "\\"")\n end\nend\n',"rom/programs/import.lua":'-- SPDX-FileCopyrightText: 2022 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\nrequire "cc.completion"\n\nprint("Drop files to transfer them to this computer")\n\nlocal files\nwhile true do\n local event, arg = os.pullEvent()\n if event == "file_transfer" then\n files = arg.getFiles()\n break\n elseif event == "key" and arg == keys.q then\n return\n end\nend\n\nif #files == 0 then\n printError("No files to transfer")\n return\nend\n\nlocal ok, err = require("cc.internal.import")(files)\nif not ok and err then printError(err) end\n',"rom/programs/label.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal function printUsage()\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usages:")\n print(programName .. " get")\n print(programName .. " get <drive>")\n print(programName .. " set <text>")\n print(programName .. " set <drive> <text>")\n print(programName .. " clear")\n print(programName .. " clear <drive>")\nend\n\nlocal function checkDrive(sDrive)\n if peripheral.getType(sDrive) == "drive" then\n -- Check the disk exists\n local bData = disk.hasData(sDrive)\n if not bData then\n print("No disk in " .. sDrive .. " drive")\n return false\n end\n else\n print("No disk drive named " .. sDrive)\n return false\n end\n return true\nend\n\nlocal function get(sDrive)\n if sDrive ~= nil then\n if checkDrive(sDrive) then\n local sLabel = disk.getLabel(sDrive)\n if sLabel then\n print("Disk label is \\"" .. sLabel .. "\\"")\n else\n print("No Disk label")\n end\n end\n else\n local sLabel = os.getComputerLabel()\n if sLabel then\n print("Computer label is \\"" .. sLabel .. "\\"")\n else\n print("No Computer label")\n end\n end\nend\n\nlocal function set(sDrive, sText)\n if sDrive ~= nil then\n if checkDrive(sDrive) then\n disk.setLabel(sDrive, sText)\n local sLabel = disk.getLabel(sDrive)\n if sLabel then\n print("Disk label set to \\"" .. sLabel .. "\\"")\n else\n print("Disk label cleared")\n end\n end\n else\n os.setComputerLabel(sText)\n local sLabel = os.getComputerLabel()\n if sLabel then\n print("Computer label set to \\"" .. sLabel .. "\\"")\n else\n print("Computer label cleared")\n end\n end\nend\n\nlocal tArgs = { ... }\nlocal sCommand = tArgs[1]\nif sCommand == "get" then\n -- Get a label\n if #tArgs == 1 then\n get(nil)\n elseif #tArgs == 2 then\n get(tArgs[2])\n else\n printUsage()\n end\nelseif sCommand == "set" then\n -- Set a label\n if #tArgs == 2 then\n set(nil, tArgs[2])\n elseif #tArgs == 3 then\n set(tArgs[2], tArgs[3])\n else\n printUsage()\n end\nelseif sCommand == "clear" then\n -- Clear a label\n if #tArgs == 1 then\n set(nil, nil)\n elseif #tArgs == 2 then\n set(tArgs[2], nil)\n else\n printUsage()\n end\nelse\n printUsage()\nend\n',"rom/programs/list.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\n\n-- Get all the files in the directory\nlocal sDir = shell.dir()\nif tArgs[1] ~= nil then\n sDir = shell.resolve(tArgs[1])\nend\n\nif not fs.isDir(sDir) then\n printError("Not a directory")\n return\nend\n\n-- Sort into dirs/files, and calculate column count\nlocal tAll = fs.list(sDir)\nlocal tFiles = {}\nlocal tDirs = {}\n\nlocal bShowHidden = settings.get("list.show_hidden")\nfor _, sItem in pairs(tAll) do\n if bShowHidden or string.sub(sItem, 1, 1) ~= "." then\n local sPath = fs.combine(sDir, sItem)\n if fs.isDir(sPath) then\n table.insert(tDirs, sItem)\n else\n table.insert(tFiles, sItem)\n end\n end\nend\ntable.sort(tDirs)\ntable.sort(tFiles)\n\nif term.isColour() then\n textutils.pagedTabulate(colors.green, tDirs, colors.white, tFiles)\nelse\n textutils.pagedTabulate(colors.lightGray, tDirs, colors.white, tFiles)\nend\n',"rom/programs/lua.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\nif #tArgs > 0 then\n print("This is an interactive Lua prompt.")\n print("To run a lua program, just type its name.")\n return\nend\n\nlocal pretty = require "cc.pretty"\nlocal exception = require "cc.internal.exception"\n\nlocal running = true\nlocal tCommandHistory = {}\nlocal tEnv = {\n ["exit"] = setmetatable({}, {\n __tostring = function() return "Call exit() to exit." end,\n __call = function() running = false end,\n }),\n ["_echo"] = function(...)\n return ...\n end,\n}\nsetmetatable(tEnv, { __index = _ENV })\n\n-- Replace our require with new instance that loads from the current directory\n-- rather than from /rom/programs. This makes it more friendly to use and closer\n-- to what you\'d expect.\ndo\n local make_package = require "cc.require".make\n local dir = shell.dir()\n _ENV.require, _ENV.package = make_package(_ENV, dir)\nend\n\nif term.isColour() then\n term.setTextColour(colours.yellow)\nend\nprint("Interactive Lua prompt.")\nprint("Call exit() to exit.")\nterm.setTextColour(colours.white)\n\nlocal chunk_idx, chunk_map = 1, {}\nwhile running do\n --if term.isColour() then\n -- term.setTextColour( colours.yellow )\n --end\n write("lua> ")\n --term.setTextColour( colours.white )\n\n local input = read(nil, tCommandHistory, function(sLine)\n if settings.get("lua.autocomplete") then\n local nStartPos = string.find(sLine, "[a-zA-Z0-9_%.:]+$")\n if nStartPos then\n sLine = string.sub(sLine, nStartPos)\n end\n if #sLine > 0 then\n return textutils.complete(sLine, tEnv)\n end\n end\n return nil\n end)\n if input:match("%S") and tCommandHistory[#tCommandHistory] ~= input then\n table.insert(tCommandHistory, input)\n end\n if settings.get("lua.warn_against_use_of_local") and input:match("^%s*local%s+") then\n if term.isColour() then\n term.setTextColour(colours.yellow)\n end\n print("To access local variables in later inputs, remove the local keyword.")\n term.setTextColour(colours.white)\n end\n\n local name, offset = "=lua[" .. chunk_idx .. "]", 0\n\n local func, err = load(input, name, "t", tEnv)\n if load("return " .. input) then\n -- We wrap the expression with a call to _echo(...), which prevents tail\n -- calls (and thus confusing errors). Note we check this is a valid\n -- expression separately, to avoid accepting inputs like `)--` (which are\n -- parsed as `_echo()--)`.\n func = load("return _echo(" .. input .. "\\n)", name, "t", tEnv)\n offset = 13\n end\n\n if func then\n chunk_map[name] = { contents = input, offset = offset }\n chunk_idx = chunk_idx + 1\n\n local results = table.pack(exception.try(func))\n if results[1] then\n for i = 2, results.n do\n local value = results[i]\n local ok, serialised = pcall(pretty.pretty, value, {\n function_args = settings.get("lua.function_args"),\n function_source = settings.get("lua.function_source"),\n })\n if ok then\n pretty.print(serialised)\n else\n print(tostring(value))\n end\n end\n else\n printError(results[2])\n require "cc.internal.exception".report(results[2], results[3], chunk_map)\n end\n else\n local parser = require "cc.internal.syntax"\n if parser.parse_repl(input) then printError(err) end\n end\n\nend\n',"rom/programs/mkdir.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\n\nif #tArgs < 1 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <paths>")\n return\nend\n\nfor _, v in ipairs(tArgs) do\n local sNewDir = shell.resolve(v)\n if fs.exists(sNewDir) and not fs.isDir(sNewDir) then\n printError(v .. ": Destination exists")\n elseif fs.isReadOnly(sNewDir) then\n printError(v .. ": Access denied")\n else\n fs.makeDir(sNewDir)\n end\nend\n',"rom/programs/monitor.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal function printUsage()\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage:")\n print(" " .. programName .. " <name> <program> <arguments>")\n print(" " .. programName .. " scale <name> <scale>")\n return\nend\n\nlocal tArgs = { ... }\nif #tArgs < 2 or tArgs[1] == "scale" and #tArgs < 3 then\n printUsage()\n return\nend\n\nif tArgs[1] == "scale" then\n local sName = tArgs[2]\n if peripheral.getType(sName) ~= "monitor" then\n print("No monitor named " .. sName)\n return\n end\n\n local nRes = tonumber(tArgs[3])\n if nRes == nil or nRes < 0.5 or nRes > 5 then\n print("Invalid scale: " .. tArgs[3])\n return\n end\n\n peripheral.call(sName, "setTextScale", nRes)\n return\nend\n\nlocal sName = tArgs[1]\nif peripheral.getType(sName) ~= "monitor" then\n print("No monitor named " .. sName)\n return\nend\n\nlocal sProgram = tArgs[2]\nlocal sPath = shell.resolveProgram(sProgram)\nif sPath == nil then\n print("No such program: " .. sProgram)\n return\nend\n\nprint("Running " .. sProgram .. " on monitor " .. sName)\n\nlocal monitor = peripheral.wrap(sName)\nlocal previousTerm = term.redirect(monitor)\n\nlocal co = coroutine.create(function()\n (shell.execute or shell.run)(sProgram, table.unpack(tArgs, 3))\nend)\n\nlocal function resume(...)\n local ok, param = coroutine.resume(co, ...)\n if not ok then\n printError(param)\n end\n return param\nend\n\nlocal timers = {}\n\nlocal ok, param = pcall(function()\n local sFilter = resume()\n while coroutine.status(co) ~= "dead" do\n local tEvent = table.pack(os.pullEventRaw())\n if sFilter == nil or tEvent[1] == sFilter or tEvent[1] == "terminate" then\n sFilter = resume(table.unpack(tEvent, 1, tEvent.n))\n end\n if coroutine.status(co) ~= "dead" and (sFilter == nil or sFilter == "mouse_click") then\n if tEvent[1] == "monitor_touch" and tEvent[2] == sName then\n timers[os.startTimer(0.1)] = { tEvent[3], tEvent[4] }\n sFilter = resume("mouse_click", 1, table.unpack(tEvent, 3, tEvent.n))\n end\n end\n if coroutine.status(co) ~= "dead" and (sFilter == nil or sFilter == "term_resize") then\n if tEvent[1] == "monitor_resize" and tEvent[2] == sName then\n sFilter = resume("term_resize")\n end\n end\n if coroutine.status(co) ~= "dead" and (sFilter == nil or sFilter == "mouse_up") then\n if tEvent[1] == "timer" and timers[tEvent[2]] then\n sFilter = resume("mouse_up", 1, table.unpack(timers[tEvent[2]], 1, 2))\n timers[tEvent[2]] = nil\n end\n end\n end\nend)\n\nterm.redirect(previousTerm)\nif not ok then\n printError(param)\nend\n',"rom/programs/motd.lua":'-- SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\nlocal date = os.date("*t")\nif date.month == 1 and date.day == 1 then\n print("Happy new year!")\nelseif date.month == 12 and date.day == 24 then\n print("Merry X-mas!")\nelseif date.month == 10 and date.day == 31 then\n print("OOoooOOOoooo! Spooky!")\nelseif date.month == 4 and date.day == 28 then\n print("Ed Balls")\nelse\n local tMotd = {}\n\n for sPath in string.gmatch(settings.get("motd.path"), "[^:]+") do\n if fs.exists(sPath) then\n for sLine in io.lines(sPath) do\n table.insert(tMotd, sLine)\n end\n end\n end\n\n if #tMotd == 0 then\n print("missingno")\n else\n print(tMotd[math.random(1, #tMotd)])\n end\nend\n',"rom/programs/move.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\nif #tArgs < 2 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <source> <destination>")\n return\nend\n\nlocal sSource = shell.resolve(tArgs[1])\nlocal sDest = shell.resolve(tArgs[2])\nlocal tFiles = fs.find(sSource)\n\nlocal function sanity_checks(source, dest)\n if fs.exists(dest) then\n printError("Destination exists")\n return false\n elseif fs.isReadOnly(dest) then\n printError("Destination is read-only")\n return false\n elseif fs.isDriveRoot(source) then\n printError("Cannot move mount /" .. source)\n return false\n elseif fs.isReadOnly(source) then\n printError("Cannot move read-only file /" .. source)\n return false\n end\n return true\nend\n\nif #tFiles > 0 then\n for _, sFile in ipairs(tFiles) do\n if fs.isDir(sDest) then\n local dest = fs.combine(sDest, fs.getName(sFile))\n if sanity_checks(sFile, dest) then\n fs.move(sFile, dest)\n end\n elseif #tFiles == 1 then\n if sanity_checks(sFile, sDest) then\n fs.move(sFile, sDest)\n end\n else\n printError("Cannot overwrite file multiple times")\n return\n end\n end\nelse\n printError("No matching files")\nend\n',"rom/programs/peripherals.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tPeripherals = peripheral.getNames()\nprint("Attached Peripherals:")\nif #tPeripherals > 0 then\n for n = 1, #tPeripherals do\n local sPeripheral = tPeripherals[n]\n print(sPeripheral .. " (" .. table.concat({ peripheral.getType(sPeripheral) }, ", ") .. ")")\n end\nelse\n print("None")\nend\n',"rom/programs/pocket/equip.lua":'-- SPDX-FileCopyrightText: 2017 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\nif not pocket then\n printError("Requires a Pocket Computer")\n return\nend\n\nlocal ok, err = pocket.equipBack()\nif not ok then\n printError(err)\nelse\n print("Item equipped")\nend\n',"rom/programs/pocket/falling.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[\nFalling - Based on Tetris by Alexey Pajitnov\nThis version written by Gopher, at the request of Dan200, for\nComputerCraft v1.6. No particular rights are reserved.\n--]]\n\nlocal function colorass(c, bw)\n return term.isColor() and c or bw\nend\n\nlocal block_s1 = {\n {\n { 1, 0, 0, 0 },\n { 1, 1, 0, 0 },\n { 0, 1, 0, 0 },\n { 0, 0, 0, 0 },\n },\n {\n { 0, 0, 0, 0 },\n { 0, 1, 1, 0 },\n { 1, 1, 0, 0 },\n { 0, 0, 0, 0 },\n },\n ch = colorass(" ", "{}"),\n fg = colorass(colors.blue, colors.black),\n bg = colorass(colors.cyan, colors.white),\n }\nlocal block_s2 = {\n {\n { 0, 1, 0, 0 },\n { 1, 1, 0, 0 },\n { 1, 0, 0, 0 },\n { 0, 0, 0, 0 },\n },\n {\n { 0, 0, 0, 0 },\n { 1, 1, 0, 0 },\n { 0, 1, 1, 0 },\n { 0, 0, 0, 0 },\n },\n ch = colorass(" ", "{}"),\n fg = colorass(colors.green, colors.black),\n bg = colorass(colors.lime, colors.white),\n }\nlocal block_line = {\n {\n { 0, 1, 0, 0 },\n { 0, 1, 0, 0 },\n { 0, 1, 0, 0 },\n { 0, 1, 0, 0 },\n },\n {\n { 0, 0, 0, 0 },\n { 1, 1, 1, 1 },\n { 0, 0, 0, 0 },\n { 0, 0, 0, 0 },\n },\n ch = colorass(" ", "[]"),\n fg = colorass(colors.pink, colors.black),\n bg = colorass(colors.red, colors.white),\n }\nlocal block_square = {\n {\n { 1, 1, 0, 0 },\n { 1, 1, 0, 0 },\n { 0, 0, 0, 0 },\n { 0, 0, 0, 0 },\n },\n ch = colorass(" ", "[]"),\n fg = colorass(colors.lightBlue, colors.black),\n bg = colorass(colors.blue, colors.white),\n }\nlocal block_L1 = {\n {\n { 1, 1, 0, 0 },\n { 0, 1, 0, 0 },\n { 0, 1, 0, 0 },\n { 0, 0, 0, 0 },\n },\n {\n { 0, 0, 0, 0 },\n { 1, 1, 1, 0 },\n { 1, 0, 0, 0 },\n { 0, 0, 0, 0 },\n },\n {\n { 0, 1, 0, 0 },\n { 0, 1, 0, 0 },\n { 0, 1, 1, 0 },\n { 0, 0, 0, 0 },\n },\n {\n { 0, 0, 1, 0 },\n { 1, 1, 1, 0 },\n { 0, 0, 0, 0 },\n { 0, 0, 0, 0 },\n },\n ch = colorass(" ", "()"),\n fg = colorass(colors.orange, colors.black),\n bg = colorass(colors.yellow, colors.white),\n }\nlocal block_L2 = {\n {\n { 0, 1, 0, 0 },\n { 0, 1, 0, 0 },\n { 1, 1, 0, 0 },\n { 0, 0, 0, 0 },\n },\n {\n { 0, 0, 0, 0 },\n { 1, 1, 1, 0 },\n { 0, 0, 1, 0 },\n { 0, 0, 0, 0 },\n },\n {\n { 0, 1, 1, 0 },\n { 0, 1, 0, 0 },\n { 0, 1, 0, 0 },\n { 0, 0, 0, 0 },\n },\n {\n { 1, 0, 0, 0 },\n { 1, 1, 1, 0 },\n { 0, 0, 0, 0 },\n { 0, 0, 0, 0 },\n },\n ch = colorass(" ", "()"),\n fg = colorass(colors.brown, colors.black),\n bg = colorass(colors.orange, colors.white),\n }\nlocal block_T = {\n {\n { 0, 1, 0, 0 },\n { 1, 1, 0, 0 },\n { 0, 1, 0, 0 },\n { 0, 0, 0, 0 },\n },\n {\n { 0, 0, 0, 0 },\n { 1, 1, 1, 0 },\n { 0, 1, 0, 0 },\n { 0, 0, 0, 0 },\n },\n {\n { 0, 1, 0, 0 },\n { 0, 1, 1, 0 },\n { 0, 1, 0, 0 },\n { 0, 0, 0, 0 },\n },\n {\n { 0, 1, 0, 0 },\n { 1, 1, 1, 0 },\n { 0, 0, 0, 0 },\n { 0, 0, 0, 0 },\n },\n ch = colorass(" ", "<>"),\n fg = colorass(colors.cyan, colors.black),\n bg = colorass(colors.purple, colors.white),\n }\n\nlocal blocks = { block_line, block_square, block_s1, block_s2, block_L1, block_L2, block_T }\n\nlocal points = { 4, 10, 30, 120 }\n\nlocal function lpad(text, amt)\n text = tostring(text)\n return string.rep(" ", amt - #text) .. text\nend\n\nlocal width, height = term.getSize()\n\nif height < 19 or width < 26 then\n print("Your screen is too small to play :(")\n return\nend\n\n\nlocal speedsByLevel = {\n 1.2,\n 1.0,\n .8,\n .65,\n .5,\n .4,\n .3,\n .25,\n .2,\n .15,\n .1,\n .05, }\n\nlocal level = 1\n\nlocal function playGame()\n local score = 0\n local lines = 0\n local initialLevel = level\n local next = blocks[math.random(1, #blocks)]\n\n local pit = {}\n\n\n local heightAdjust = 0\n\n if height <= 19 then\n heightAdjust = 1\n end\n\n\n\n local function drawScreen()\n term.setTextColor(colors.white)\n term.setBackgroundColor(colors.black)\n term.clear()\n\n term.setTextColor(colors.black)\n term.setBackgroundColor(colorass(colors.lightGray, colors.white))\n term.setCursorPos(22, 2)\n term.write("Score") --score\n term.setCursorPos(22, 5)\n term.write("Level") --level\n term.setCursorPos(22, 8)\n term.write("Lines") --lines\n term.setCursorPos(22, 12)\n term.write("Next") --next\n\n term.setCursorPos(21, 1)\n term.write(" ")\n term.setCursorPos(21, 2)\n term.write(" ") --score\n term.setCursorPos(21, 3)\n term.write(" ")\n term.setCursorPos(21, 4)\n term.write(" ")\n term.setCursorPos(21, 5)\n term.write(" ") --level\n term.setCursorPos(21, 6)\n term.write(" ")\n term.setCursorPos(21, 7)\n term.write(" ")\n term.setCursorPos(21, 8)\n term.write(" ") --lines\n term.setCursorPos(21, 9)\n term.write(" ")\n term.setCursorPos(21, 10)\n term.write(" ")\n term.setCursorPos(21, 11)\n term.write(" ")\n term.setCursorPos(21, 12)\n term.write(" ") --next\n term.setCursorPos(26, 12)\n term.write(" ") --next\n term.setCursorPos(21, 13)\n term.write(" ")\n term.setCursorPos(21, 14)\n term.write(" ")\n term.setCursorPos(21, 15)\n term.write(" ")\n term.setCursorPos(21, 16)\n term.write(" ")\n term.setCursorPos(21, 17)\n term.write(" ")\n term.setCursorPos(21, 18)\n term.write(" ")\n term.setCursorPos(21, 19)\n term.write(" ")\n term.setCursorPos(21, 20)\n term.write(" ")\n end\n\n local function updateNumbers()\n term.setTextColor(colors.white)\n term.setBackgroundColor(colors.black)\n\n term.setCursorPos(22, 3)\n term.write(lpad(score, 5)) --score\n term.setCursorPos(22, 6)\n term.write(lpad(level, 5)) --level\n term.setCursorPos(22, 9)\n term.write(lpad(lines, 5)) --lines\n end\n\n local function drawBlockAt(block, xp, yp, rot)\n term.setTextColor(block.fg)\n term.setBackgroundColor(block.bg)\n for y = 1, 4 do\n for x = 1, 4 do\n if block[rot][y][x] == 1 then\n term.setCursorPos((xp + x) * 2 - 3, yp + y - 1 - heightAdjust)\n term.write(block.ch)\n end\n end\n end\n end\n\n local function eraseBlockAt(block, xp, yp, rot)\n term.setTextColor(colors.white)\n term.setBackgroundColor(colors.black)\n for y = 1, 4 do\n for x = 1, 4 do\n if block[rot][y][x] == 1 then\n term.setCursorPos((xp + x) * 2 - 3, yp + y - 1 - heightAdjust)\n term.write(" ")\n end\n end\n end\n end\n\n local function testBlockAt(block, xp, yp, rot)\n for y = 1, 4 do\n local ty = yp + y - 1\n for x = 1, 4 do\n local tx = xp + x - 1\n if block[rot][y][x] == 1 then\n if tx > 10 or tx < 1 or ty > 20 or pit[ty][tx] ~= 0 then\n return true\n end\n end\n end\n end\n end\n\n local function pitBlock(block, xp, yp, rot)\n for y = 1, 4 do\n for x = 1, 4 do\n if block[rot][y][x] == 1 then\n pit[yp + y - 1][xp + x - 1] = block\n end\n end\n end\n end\n\n\n local function clearPit()\n for row = 1, 20 do\n pit[row] = {}\n for col = 1, 10 do\n pit[row][col] = 0\n end\n end\n end\n\n\n\n drawScreen()\n updateNumbers()\n\n --declare & init the pit\n clearPit()\n\n\n\n local halt = false\n local dropSpeed = speedsByLevel[math.min(level, 12)]\n\n\n local curBlock = next\n next = blocks[math.random(1, 7)]\n\n local curX, curY, curRot = 4, 1, 1\n local dropTimer = os.startTimer(dropSpeed)\n\n drawBlockAt(next, 11.5, 15 + heightAdjust, 1)\n drawBlockAt(curBlock, curX, curY, curRot)\n\n local function redrawPit()\n for r = 1 + heightAdjust, 20 do\n term.setCursorPos(1, r - heightAdjust)\n for c = 1, 10 do\n if pit[r][c] == 0 then\n term.setTextColor(colors.black)\n term.setBackgroundColor(colors.black)\n term.write(" ")\n else\n term.setTextColor(pit[r][c].fg)\n term.setBackgroundColor(pit[r][c].bg)\n term.write(pit[r][c].ch)\n end\n end\n end\n end\n\n local function hidePit()\n for r = 1 + heightAdjust, 20 do\n term.setCursorPos(1, r - heightAdjust)\n term.setTextColor(colors.black)\n term.setBackgroundColor(colors.black)\n term.write(" ")\n end\n end\n\n local function msgBox(message)\n local x = math.floor((17 - #message) / 2)\n term.setBackgroundColor(colorass(colors.lightGray, colors.white))\n term.setTextColor(colors.black)\n term.setCursorPos(x, 9)\n term.write("+" .. string.rep("-", #message + 2) .. "+")\n term.setCursorPos(x, 10)\n term.write("|")\n term.setCursorPos(x + #message + 3, 10)\n term.write("|")\n term.setCursorPos(x, 11)\n term.write("+" .. string.rep("-", #message + 2) .. "+")\n term.setTextColor(colors.white)\n term.setBackgroundColor(colors.black)\n term.setCursorPos(x + 1, 10)\n term.write(" " .. message .. " ")\n end\n\n local function clearRows()\n local rows = {}\n for r = 1, 20 do\n local count = 0\n for c = 1, 10 do\n if pit[r][c] ~= 0 then\n count = count + 1\n else\n break\n end\n end\n if count == 10 then\n rows[#rows + 1] = r\n end\n end\n\n if #rows > 0 then\n for _ = 1, 4 do\n sleep(.1)\n for r = 1, #rows do\n r = rows[r]\n term.setCursorPos(1, r - heightAdjust)\n for c = 1, 10 do\n term.setTextColor(pit[r][c].bg)\n term.setBackgroundColor(pit[r][c].fg)\n term.write(pit[r][c].ch)\n end\n end\n sleep(.1)\n for r = 1, #rows do\n r = rows[r]\n term.setCursorPos(1, r - heightAdjust)\n for c = 1, 10 do\n term.setTextColor(pit[r][c].fg)\n term.setBackgroundColor(pit[r][c].bg)\n term.write(pit[r][c].ch)\n end\n end\n end\n --now remove the rows and drop everything else\n term.setBackgroundColor(colors.black)\n for r = 1, #rows do\n r = rows[r]\n term.setCursorPos(1, r - heightAdjust)\n term.write(" ")\n end\n sleep(.25)\n for r = 1, #rows do\n table.remove(pit, rows[r])\n table.insert(pit, 1, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 })\n end\n redrawPit()\n lines = lines + #rows\n score = score + points[#rows] * math.min(level, 20)\n level = math.floor(lines / 10) + initialLevel\n dropSpeed = speedsByLevel[math.min(level, 12)]\n updateNumbers()\n end\n sleep(.25)\n end\n\n local function blockFall()\n if testBlockAt(curBlock, curX, curY + 1, curRot) then\n pitBlock(curBlock, curX, curY, curRot)\n --detect rows that clear\n clearRows()\n\n curBlock = next\n curX = 4\n curY = 1\n curRot = 1\n if testBlockAt(curBlock, curX, curY, curRot) then\n halt = true\n end\n drawBlockAt(curBlock, curX, curY, curRot)\n eraseBlockAt(next, 11.5, 15 + heightAdjust, 1)\n next = blocks[math.random(1, 7)]\n drawBlockAt(next, 11.5, 15 + heightAdjust, 1)\n return true\n else\n eraseBlockAt(curBlock, curX, curY, curRot)\n curY = curY + 1\n drawBlockAt(curBlock, curX, curY, curRot)\n return false\n end\n end\n\n\n while not halt do\n local e = { os.pullEvent() }\n if e[1] == "timer" then\n if e[2] == dropTimer then\n blockFall()\n dropTimer = os.startTimer(dropSpeed)\n end\n elseif e[1] == "key" then\n local key = e[2]\n local dx, dy, dr = 0, 0, 0\n if key == keys.left or key == keys.a then\n dx = -1\n elseif key == keys.right or key == keys.d then\n dx = 1\n elseif key == keys.up or key == keys.w then\n dr = 1\n elseif key == keys.down or key == keys.s then\n while not blockFall() do end\n dropTimer = os.startTimer(dropSpeed)\n elseif key == keys.space then\n hidePit()\n msgBox("Paused")\n while ({ os.pullEvent("key") })[2] ~= keys.space do end\n redrawPit()\n drawBlockAt(curBlock, curX, curY, curRot)\n dropTimer = os.startTimer(dropSpeed)\n end\n if dx + dr ~= 0 then\n if not testBlockAt(curBlock, curX + dx, curY + dy, dr > 0 and curRot % #curBlock + dr or curRot) then\n eraseBlockAt(curBlock, curX, curY, curRot)\n curX = curX + dx\n curY = curY + dy\n curRot = dr == 0 and curRot or curRot % #curBlock + dr\n drawBlockAt(curBlock, curX, curY, curRot)\n end\n end\n elseif e[1] == "term_resize" then\n local _, h = term.getSize()\n if h == 20 then\n heightAdjust = 0\n else\n heightAdjust = 1\n end\n redrawPit()\n drawBlockAt(curBlock, curX, curY, curRot)\n end\n end\n\n msgBox("Game Over!")\n while true do\n local _, k = os.pullEvent("key")\n if k == keys.space or k == keys.enter or k == keys.numPadEnter then\n break\n end\n end\n\n level = math.min(level, 9)\nend\n\n\nlocal selected = 1\nlocal playersDetected = false\n\nlocal function drawMenu()\n term.setBackgroundColor(colors.black)\n term.setTextColor(colorass(colors.red, colors.white))\n term.clear()\n\n local cx, cy = math.floor(width / 2), math.floor(height / 2)\n\n term.setCursorPos(cx - 6, cy - 2)\n term.write("F A L L I N G")\n\n if playersDetected then\n if selected == 0 then\n term.setTextColor(colorass(colors.blue, colors.black))\n term.setBackgroundColor(colorass(colors.gray, colors.white))\n else\n term.setTextColor(colorass(colors.lightBlue, colors.white))\n term.setBackgroundColor(colors.black)\n end\n term.setCursorPos(cx - 12, cy)\n term.write(" Play head-to-head game! ")\n end\n\n term.setCursorPos(cx - 10, cy + 1)\n if selected == 1 then\n term.setTextColor(colorass(colors.blue, colors.black))\n term.setBackgroundColor(colorass(colors.lightGray, colors.white))\n else\n term.setTextColor(colorass(colors.lightBlue, colors.white))\n term.setBackgroundColor(colors.black)\n end\n term.write(" Play from level: <" .. level .. "> ")\n\n term.setCursorPos(cx - 3, cy + 3)\n if selected == 2 then\n term.setTextColor(colorass(colors.blue, colors.black))\n term.setBackgroundColor(colorass(colors.lightGray, colors.white))\n else\n term.setTextColor(colorass(colors.lightBlue, colors.white))\n term.setBackgroundColor(colors.black)\n end\n term.write(" Quit ")\nend\n\n\nlocal function runMenu()\n drawMenu()\n\n while true do\n local event = { os.pullEvent() }\n if event[1] == "key" then\n local key = event[2]\n if key == keys.right or key == keys.d and selected == 1 then\n level = math.min(level + 1, 9)\n drawMenu()\n elseif key == keys.left or key == keys.a and selected == 1 then\n level = math.max(level - 1, 1)\n drawMenu()\n elseif key >= keys.one and key <= keys.nine and selected == 1 then\n level = key - keys.one + 1\n drawMenu()\n elseif key == keys.up or key == keys.w then\n selected = selected - 1\n if selected == 0 then\n selected = 2\n end\n drawMenu()\n elseif key == keys.down or key == keys.s then\n selected = selected % 2 + 1\n drawMenu()\n elseif key == keys.enter or key == keys.numPadEnter or key == keys.space then\n break --begin play!\n end\n end\n end\nend\n\nwhile true do\n runMenu()\n if selected == 2 then\n break\n end\n\n playGame()\nend\n\n\nterm.setTextColor(colors.white)\nterm.setBackgroundColor(colors.black)\nterm.clear()\nterm.setCursorPos(1, 1)\n',"rom/programs/pocket/unequip.lua":'-- SPDX-FileCopyrightText: 2017 The CC: Tweaked Developers\n--\n-- SPDX-License-Identifier: MPL-2.0\n\nif not pocket then\n printError("Requires a Pocket Computer")\n return\nend\n\nlocal ok, err = pocket.unequipBack()\nif not ok then\n printError(err)\nelse\n print("Item unequipped")\nend\n',"rom/programs/programs.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal bAll = false\nlocal tArgs = { ... }\nif #tArgs > 0 and tArgs[1] == "all" then\n bAll = true\nend\n\nlocal tPrograms = shell.programs(bAll)\ntextutils.pagedTabulate(tPrograms)\n',"rom/programs/reboot.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif term.isColour() then\n term.setTextColour(colours.yellow)\nend\nprint("Goodbye")\nterm.setTextColour(colours.white)\n\nsleep(1)\nos.reboot()\n',"rom/programs/rednet/chat.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\n\nlocal function printUsage()\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usages:")\n print(programName .. " host <hostname>")\n print(programName .. " join <hostname> <nickname>")\nend\n\nlocal sOpenedModem = nil\nlocal function openModem()\n for _, sModem in ipairs(peripheral.getNames()) do\n if peripheral.getType(sModem) == "modem" then\n if not rednet.isOpen(sModem) then\n rednet.open(sModem)\n sOpenedModem = sModem\n end\n return true\n end\n end\n print("No modems found.")\n return false\nend\n\nlocal function closeModem()\n if sOpenedModem ~= nil then\n rednet.close(sOpenedModem)\n sOpenedModem = nil\n end\nend\n\n-- Colours\nlocal highlightColour, textColour\nif term.isColour() then\n textColour = colours.white\n highlightColour = colours.yellow\nelse\n textColour = colours.white\n highlightColour = colours.white\nend\n\nlocal sCommand = tArgs[1]\nif sCommand == "host" then\n -- "chat host"\n -- Get hostname\n local sHostname = tArgs[2]\n if sHostname == nil then\n printUsage()\n return\n end\n\n -- Host server\n if not openModem() then\n return\n end\n rednet.host("chat", sHostname)\n print("0 users connected.")\n\n local tUsers = {}\n local nUsers = 0\n local function send(sText, nUserID)\n if nUserID then\n local tUser = tUsers[nUserID]\n if tUser then\n rednet.send(tUser.nID, {\n sType = "text",\n nUserID = nUserID,\n sText = sText,\n }, "chat")\n end\n else\n for nUserID, tUser in pairs(tUsers) do\n rednet.send(tUser.nID, {\n sType = "text",\n nUserID = nUserID,\n sText = sText,\n }, "chat")\n end\n end\n end\n\n -- Setup ping pong\n local tPingPongTimer = {}\n local function ping(nUserID)\n local tUser = tUsers[nUserID]\n rednet.send(tUser.nID, {\n sType = "ping to client",\n nUserID = nUserID,\n }, "chat")\n\n local timer = os.startTimer(15)\n tUser.bPingPonged = false\n tPingPongTimer[timer] = nUserID\n end\n\n local function printUsers()\n local _, y = term.getCursorPos()\n term.setCursorPos(1, y - 1)\n term.clearLine()\n if nUsers == 1 then\n print(nUsers .. " user connected.")\n else\n print(nUsers .. " users connected.")\n end\n end\n\n -- Handle messages\n local ok, error = pcall(parallel.waitForAny,\n function()\n while true do\n local _, timer = os.pullEvent("timer")\n local nUserID = tPingPongTimer[timer]\n if nUserID and tUsers[nUserID] then\n local tUser = tUsers[nUserID]\n if tUser then\n if not tUser.bPingPonged then\n send("* " .. tUser.sUsername .. " has timed out")\n tUsers[nUserID] = nil\n nUsers = nUsers - 1\n printUsers()\n else\n ping(nUserID)\n end\n end\n end\n end\n end,\n function()\n while true do\n local tCommands\n tCommands = {\n ["me"] = function(tUser, sContent)\n if #sContent > 0 then\n send("* " .. tUser.sUsername .. " " .. sContent)\n else\n send("* Usage: /me [words]", tUser.nUserID)\n end\n end,\n ["nick"] = function(tUser, sContent)\n if #sContent > 0 then\n local sOldName = tUser.sUsername\n tUser.sUsername = sContent\n send("* " .. sOldName .. " is now known as " .. tUser.sUsername)\n else\n send("* Usage: /nick [nickname]", tUser.nUserID)\n end\n end,\n ["users"] = function(tUser, sContent)\n send("* Connected Users:", tUser.nUserID)\n local sUsers = "*"\n for _, tUser in pairs(tUsers) do\n sUsers = sUsers .. " " .. tUser.sUsername\n end\n send(sUsers, tUser.nUserID)\n end,\n ["help"] = function(tUser, sContent)\n send("* Available commands:", tUser.nUserID)\n local sCommands = "*"\n for sCommand in pairs(tCommands) do\n sCommands = sCommands .. " /" .. sCommand\n end\n send(sCommands .. " /logout", tUser.nUserID)\n end,\n }\n\n local nSenderID, tMessage = rednet.receive("chat")\n if type(tMessage) == "table" then\n if tMessage.sType == "login" then\n -- Login from new client\n local nUserID = tMessage.nUserID\n local sUsername = tMessage.sUsername\n if nUserID and sUsername then\n tUsers[nUserID] = {\n nID = nSenderID,\n nUserID = nUserID,\n sUsername = sUsername,\n }\n nUsers = nUsers + 1\n printUsers()\n send("* " .. sUsername .. " has joined the chat")\n ping(nUserID)\n end\n\n else\n -- Something else from existing client\n local nUserID = tMessage.nUserID\n local tUser = tUsers[nUserID]\n if tUser and tUser.nID == nSenderID then\n if tMessage.sType == "logout" then\n send("* " .. tUser.sUsername .. " has left the chat")\n tUsers[nUserID] = nil\n nUsers = nUsers - 1\n printUsers()\n\n elseif tMessage.sType == "chat" then\n local sMessage = tMessage.sText\n if sMessage then\n local sCommand = string.match(sMessage, "^/([a-z]+)")\n if sCommand then\n local fnCommand = tCommands[sCommand]\n if fnCommand then\n local sContent = string.sub(sMessage, #sCommand + 3)\n fnCommand(tUser, sContent)\n else\n send("* Unrecognised command: /" .. sCommand, tUser.nUserID)\n end\n else\n send("<" .. tUser.sUsername .. "> " .. tMessage.sText)\n end\n end\n\n elseif tMessage.sType == "ping to server" then\n rednet.send(tUser.nID, {\n sType = "pong to client",\n nUserID = nUserID,\n }, "chat")\n\n elseif tMessage.sType == "pong to server" then\n tUser.bPingPonged = true\n\n end\n end\n end\n end\n end\n end\n )\n if not ok then\n printError(error)\n end\n\n -- Unhost server\n for nUserID, tUser in pairs(tUsers) do\n rednet.send(tUser.nID, {\n sType = "kick",\n nUserID = nUserID,\n }, "chat")\n end\n rednet.unhost("chat")\n closeModem()\n\nelseif sCommand == "join" then\n -- "chat join"\n -- Get hostname and username\n local sHostname = tArgs[2]\n local sUsername = tArgs[3]\n if sHostname == nil or sUsername == nil then\n printUsage()\n return\n end\n\n -- Connect\n if not openModem() then\n return\n end\n write("Looking up " .. sHostname .. "... ")\n local nHostID = rednet.lookup("chat", sHostname)\n if nHostID == nil then\n print("Failed.")\n return\n else\n print("Success.")\n end\n\n -- Login\n local nUserID = math.random(1, 2147483647)\n rednet.send(nHostID, {\n sType = "login",\n nUserID = nUserID,\n sUsername = sUsername,\n }, "chat")\n\n -- Setup ping pong\n local bPingPonged = true\n local pingPongTimer = os.startTimer(0)\n\n local function ping()\n rednet.send(nHostID, {\n sType = "ping to server",\n nUserID = nUserID,\n }, "chat")\n bPingPonged = false\n pingPongTimer = os.startTimer(15)\n end\n\n -- Handle messages\n local w, h = term.getSize()\n local parentTerm = term.current()\n local titleWindow = window.create(parentTerm, 1, 1, w, 1, true)\n local historyWindow = window.create(parentTerm, 1, 2, w, h - 2, true)\n local promptWindow = window.create(parentTerm, 1, h, w, 1, true)\n historyWindow.setCursorPos(1, h - 2)\n\n term.clear()\n term.setTextColour(textColour)\n term.redirect(promptWindow)\n promptWindow.restoreCursor()\n\n local function drawTitle()\n local w = titleWindow.getSize()\n local sTitle = sUsername .. " on " .. sHostname\n titleWindow.setTextColour(highlightColour)\n titleWindow.setCursorPos(math.floor(w / 2 - #sTitle / 2), 1)\n titleWindow.clearLine()\n titleWindow.write(sTitle)\n promptWindow.restoreCursor()\n end\n\n local function printMessage(sMessage)\n term.redirect(historyWindow)\n print()\n if string.match(sMessage, "^%*") then\n -- Information\n term.setTextColour(highlightColour)\n write(sMessage)\n term.setTextColour(textColour)\n else\n -- Chat\n local sUsernameBit = string.match(sMessage, "^<[^>]*>")\n if sUsernameBit then\n term.setTextColour(highlightColour)\n write(sUsernameBit)\n term.setTextColour(textColour)\n write(string.sub(sMessage, #sUsernameBit + 1))\n else\n write(sMessage)\n end\n end\n term.redirect(promptWindow)\n promptWindow.restoreCursor()\n end\n\n drawTitle()\n\n local ok, error = pcall(parallel.waitForAny,\n function()\n while true do\n local sEvent, timer = os.pullEvent()\n if sEvent == "timer" then\n if timer == pingPongTimer then\n if not bPingPonged then\n printMessage("Server timeout.")\n return\n else\n ping()\n end\n end\n\n elseif sEvent == "term_resize" then\n local w, h = parentTerm.getSize()\n titleWindow.reposition(1, 1, w, 1)\n historyWindow.reposition(1, 2, w, h - 2)\n promptWindow.reposition(1, h, w, 1)\n\n end\n end\n end,\n function()\n while true do\n local nSenderID, tMessage = rednet.receive("chat")\n if nSenderID == nHostID and type(tMessage) == "table" and tMessage.nUserID == nUserID then\n if tMessage.sType == "text" then\n local sText = tMessage.sText\n if sText then\n printMessage(sText)\n end\n\n elseif tMessage.sType == "ping to client" then\n rednet.send(nSenderID, {\n sType = "pong to server",\n nUserID = nUserID,\n }, "chat")\n\n elseif tMessage.sType == "pong to client" then\n bPingPonged = true\n\n elseif tMessage.sType == "kick" then\n return\n\n end\n end\n end\n end,\n function()\n local tSendHistory = {}\n while true do\n promptWindow.setCursorPos(1, 1)\n promptWindow.clearLine()\n promptWindow.setTextColor(highlightColour)\n promptWindow.write(": ")\n promptWindow.setTextColor(textColour)\n\n local sChat = read(nil, tSendHistory)\n if string.match(sChat, "^/logout") then\n break\n else\n rednet.send(nHostID, {\n sType = "chat",\n nUserID = nUserID,\n sText = sChat,\n }, "chat")\n table.insert(tSendHistory, sChat)\n end\n end\n end\n )\n\n -- Close the windows\n term.redirect(parentTerm)\n\n -- Print error notice\n local _, h = term.getSize()\n term.setCursorPos(1, h)\n term.clearLine()\n term.setCursorBlink(false)\n if not ok then\n printError(error)\n end\n\n -- Logout\n rednet.send(nHostID, {\n sType = "logout",\n nUserID = nUserID,\n }, "chat")\n closeModem()\n\n -- Print disconnection notice\n print("Disconnected.")\n\nelse\n -- "chat somethingelse"\n printUsage()\n\nend\n',"rom/programs/rednet/repeat.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n-- Find modems\nlocal tModems = {}\nfor _, sModem in ipairs(peripheral.getNames()) do\n if peripheral.getType(sModem) == "modem" then\n table.insert(tModems, sModem)\n end\nend\nif #tModems == 0 then\n print("No modems found.")\n return\nelseif #tModems == 1 then\n print("1 modem found.")\nelse\n print(#tModems .. " modems found.")\nend\n\nlocal function open(nChannel)\n for n = 1, #tModems do\n local sModem = tModems[n]\n peripheral.call(sModem, "open", nChannel)\n end\nend\n\nlocal function close(nChannel)\n for n = 1, #tModems do\n local sModem = tModems[n]\n peripheral.call(sModem, "close", nChannel)\n end\nend\n\n-- Open channels\nprint("0 messages repeated.")\nopen(rednet.CHANNEL_REPEAT)\n\n-- Main loop (terminate to break)\nlocal ok, error = pcall(function()\n local tReceivedMessages = {}\n local tReceivedMessageTimeouts = {}\n local nTransmittedMessages = 0\n\n while true do\n local sEvent, sModem, nChannel, nReplyChannel, tMessage = os.pullEvent()\n if sEvent == "modem_message" then\n -- Got a modem message, rebroadcast it if it\'s a rednet thing\n if nChannel == rednet.CHANNEL_REPEAT then\n if type(tMessage) == "table" and tMessage.nMessageID and tMessage.nRecipient and type(tMessage.nRecipient) == "number" then\n if not tReceivedMessages[tMessage.nMessageID] then\n -- Ensure we only repeat a message once\n tReceivedMessages[tMessage.nMessageID] = true\n tReceivedMessageTimeouts[os.startTimer(30)] = tMessage.nMessageID\n\n local recipient_channel = tMessage.nRecipient\n if tMessage.nRecipient ~= rednet.CHANNEL_BROADCAST then\n recipient_channel = recipient_channel % rednet.MAX_ID_CHANNELS\n end\n\n -- Send on all other open modems, to the target and to other repeaters\n for n = 1, #tModems do\n local sOtherModem = tModems[n]\n peripheral.call(sOtherModem, "transmit", rednet.CHANNEL_REPEAT, nReplyChannel, tMessage)\n peripheral.call(sOtherModem, "transmit", recipient_channel, nReplyChannel, tMessage)\n end\n\n -- Log the event\n nTransmittedMessages = nTransmittedMessages + 1\n local _, y = term.getCursorPos()\n term.setCursorPos(1, y - 1)\n term.clearLine()\n if nTransmittedMessages == 1 then\n print(nTransmittedMessages .. " message repeated.")\n else\n print(nTransmittedMessages .. " messages repeated.")\n end\n end\n end\n end\n\n elseif sEvent == "timer" then\n -- Got a timer event, use it to clear the message history\n local nTimer = sModem\n local nMessageID = tReceivedMessageTimeouts[nTimer]\n if nMessageID then\n tReceivedMessageTimeouts[nTimer] = nil\n tReceivedMessages[nMessageID] = nil\n end\n\n end\n end\nend)\nif not ok then\n printError(error)\nend\n\n-- Close channels\nclose(rednet.CHANNEL_REPEAT)\n',"rom/programs/redstone.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\n\nlocal function printUsage()\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usages:")\n print(programName .. " probe")\n print(programName .. " set <side> <value>")\n print(programName .. " set <side> <color> <value>")\n print(programName .. " pulse <side> <count> <period>")\nend\n\nlocal sCommand = tArgs[1]\nif sCommand == "probe" then\n -- "redstone probe"\n -- Regular input\n print("Redstone inputs: ")\n\n local count = 0\n local bundledCount = 0\n for _, sSide in ipairs(redstone.getSides()) do\n if redstone.getBundledInput(sSide) > 0 then\n bundledCount = bundledCount + 1\n end\n if redstone.getInput(sSide) then\n if count > 0 then\n io.write(", ")\n end\n io.write(sSide)\n count = count + 1\n end\n end\n if count > 0 then\n print(".")\n else\n print("None.")\n end\n\n -- Bundled input\n if bundledCount > 0 then\n print()\n print("Bundled inputs:")\n for _, sSide in ipairs(redstone.getSides()) do\n local nInput = redstone.getBundledInput(sSide)\n if nInput ~= 0 then\n write(sSide .. ": ")\n local count = 0\n for sColour, nColour in pairs(colors) do\n if type(nColour) == "number" and colors.test(nInput, nColour) then\n if count > 0 then\n write(", ")\n end\n if term.isColour() then\n term.setTextColour(nColour)\n end\n write(sColour)\n if term.isColour() then\n term.setTextColour(colours.white)\n end\n count = count + 1\n end\n end\n print(".")\n end\n end\n end\n\nelseif sCommand == "pulse" then\n -- "redstone pulse"\n local sSide = tArgs[2]\n local nCount = tonumber(tArgs[3]) or 1\n local nPeriod = tonumber(tArgs[4]) or 0.5\n for _ = 1, nCount do\n redstone.setOutput(sSide, true)\n sleep(nPeriod / 2)\n redstone.setOutput(sSide, false)\n sleep(nPeriod / 2)\n end\n\nelseif sCommand == "set" then\n -- "redstone set"\n local sSide = tArgs[2]\n if #tArgs > 3 then\n -- Bundled cable output\n local sColour = tArgs[3]\n local nColour = colors[sColour] or colours[sColour]\n if type(nColour) ~= "number" then\n printError("No such color")\n return\n end\n\n local sValue = tArgs[4]\n if sValue == "true" then\n rs.setBundledOutput(sSide, colors.combine(rs.getBundledOutput(sSide), nColour))\n elseif sValue == "false" then\n rs.setBundledOutput(sSide, colors.subtract(rs.getBundledOutput(sSide), nColour))\n else\n print("Value must be boolean")\n end\n else\n -- Regular output\n local sValue = tArgs[3]\n local nValue = tonumber(sValue)\n if sValue == "true" then\n rs.setOutput(sSide, true)\n elseif sValue == "false" then\n rs.setOutput(sSide, false)\n elseif nValue and nValue >= 0 and nValue <= 15 then\n rs.setAnalogOutput(sSide, nValue)\n else\n print("Value must be boolean or 0-15")\n end\n end\n\nelse\n -- Something else\n printUsage()\n\nend\n',"rom/programs/rename.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\nif #tArgs < 2 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <source> <destination>")\n return\nend\n\nlocal sSource = shell.resolve(tArgs[1])\nlocal sDest = shell.resolve(tArgs[2])\n\nif not fs.exists(sSource) then\n printError("No matching files")\n return\nelseif fs.isDriveRoot(sSource) then\n printError("Can\'t rename mounts")\n return\nelseif fs.isReadOnly(sSource) then\n printError("Source is read-only")\n return\nelseif fs.exists(sDest) then\n printError("Destination exists")\n return\nelseif fs.isReadOnly(sDest) then\n printError("Destination is read-only")\n return\nend\n\nfs.move(sSource, sDest)\n',"rom/programs/set.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal pp = require "cc.pretty"\n\nlocal tArgs = { ... }\nif #tArgs == 0 then\n -- "set"\n local _, y = term.getCursorPos()\n local tSettings = {}\n for n, sName in ipairs(settings.getNames()) do\n tSettings[n] = textutils.serialize(sName) .. " is " .. textutils.serialize(settings.get(sName))\n end\n textutils.pagedPrint(table.concat(tSettings, "\\n"), y - 3)\n\nelseif #tArgs == 1 then\n -- "set foo"\n local sName = tArgs[1]\n local deets = settings.getDetails(sName)\n local msg = pp.text(sName, colors.cyan) .. " is " .. pp.pretty(deets.value)\n if deets.default ~= nil and deets.value ~= deets.default then\n msg = msg .. " (default is " .. pp.pretty(deets.default) .. ")"\n end\n pp.print(msg)\n if deets.description then print(deets.description) end\n\nelse\n -- "set foo bar"\n local sName = tArgs[1]\n local sValue = tArgs[2]\n local value\n if sValue == "true" then\n value = true\n elseif sValue == "false" then\n value = false\n elseif sValue == "nil" then\n value = nil\n elseif tonumber(sValue) then\n value = tonumber(sValue)\n else\n value = sValue\n end\n\n local option = settings.getDetails(sName)\n if value == nil then\n settings.unset(sName)\n print(textutils.serialize(sName) .. " unset")\n elseif option.type and option.type ~= type(value) then\n printError(("%s is not a valid %s."):format(textutils.serialize(sValue), option.type))\n else\n settings.set(sName, value)\n print(textutils.serialize(sName) .. " set to " .. textutils.serialize(value))\n end\n\n if value ~= option.value then\n settings.save()\n end\nend\n',"rom/programs/shell.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\n--[[- The shell API provides access to CraftOS\'s command line interface.\n\nIt allows you to [start programs][`run`], [add completion for a\nprogram][`setCompletionFunction`], and much more.\n\n[`shell`] is not a "true" API. Instead, it is a standard program, which injects\nits API into the programs that it launches. This allows for multiple shells to\nrun at the same time, but means that the API is not available in the global\nenvironment, and so is unavailable to other [APIs][`os.loadAPI`].\n\n## Programs and the program path\nWhen you run a command with the shell, either from the prompt or\n[from Lua code][`shell.run`], the shell API performs several steps to work out\nwhich program to run:\n\n 1. Firstly, the shell attempts to resolve [aliases][`shell.aliases`]. This allows\n us to use multiple names for a single command. For example, the `list`\n program has two aliases: `ls` and `dir`. When you write `ls /rom`, that\'s\n expanded to `list /rom`.\n\n 2. Next, the shell attempts to find where the program actually is. For this, it\n uses the [program path][`shell.path`]. This is a colon separated list of\n directories, each of which is checked to see if it contains the program.\n\n `list` or `list.lua` doesn\'t exist in `.` (the current directory), so the\n shell now looks in `/rom/programs`, where `list.lua` can be found!\n\n 3. Finally, the shell reads the file and checks if the file starts with a\n `#!`. This is a [hashbang][], which says that this file shouldn\'t be treated\n as Lua, but instead passed to _another_ program, the name of which should\n follow the `#!`.\n\n[hashbang]: https://en.wikipedia.org/wiki/Shebang_(Unix)\n\n@module[module] shell\n@changed 1.103.0 Added support for hashbangs.\n]]\n\nlocal make_package = dofile("rom/modules/main/cc/require.lua").make\n\nlocal multishell = multishell\nlocal parentShell = shell\nlocal parentTerm = term.current()\n\nif multishell then\n multishell.setTitle(multishell.getCurrent(), "shell")\nend\n\nlocal bExit = false\nlocal sDir = parentShell and parentShell.dir() or ""\nlocal sPath = parentShell and parentShell.path() or ".:/rom/programs"\nlocal tAliases = parentShell and parentShell.aliases() or {}\nlocal tCompletionInfo = parentShell and parentShell.getCompletionInfo() or {}\nlocal tProgramStack = {}\n\nlocal shell = {} --- @export\nlocal function createShellEnv(dir)\n local env = { shell = shell, multishell = multishell }\n env.require, env.package = make_package(env, dir)\n return env\nend\n\n-- Set up a dummy require based on the current shell, for loading some of our internal dependencies.\nlocal require\ndo\n local env = setmetatable(createShellEnv("/rom/programs"), { __index = _ENV })\n require = env.require\nend\nlocal expect = require("cc.expect").expect\nlocal exception = require "cc.internal.exception"\n\n-- Colours\nlocal promptColour, textColour, bgColour\nif term.isColour() then\n promptColour = colours.yellow\n textColour = colours.white\n bgColour = colours.black\nelse\n promptColour = colours.white\n textColour = colours.white\n bgColour = colours.black\nend\n\nlocal function tokenise(...)\n local sLine = table.concat({ ... }, " ")\n local tWords = {}\n local bQuoted = false\n for match in string.gmatch(sLine .. "\\"", "(.-)\\"") do\n if bQuoted then\n table.insert(tWords, match)\n else\n for m in string.gmatch(match, "[^ \\t]+") do\n table.insert(tWords, m)\n end\n end\n bQuoted = not bQuoted\n end\n return tWords\nend\n\n-- Execute a program using os.run, unless a shebang is present.\n-- In that case, execute the program using the interpreter specified in the hashbang.\n-- This may occur recursively, up to the maximum number of times specified by remainingRecursion\n-- Returns the same type as os.run, which is a boolean indicating whether the program exited successfully.\nlocal function executeProgram(remainingRecursion, path, args)\n local file, err = fs.open(path, "r")\n if not file then\n printError(err)\n return false\n end\n\n -- First check if the file begins with a #!\n local contents = file.readLine() or ""\n\n if contents:sub(1, 2) == "#!" then\n file.close()\n\n remainingRecursion = remainingRecursion - 1\n if remainingRecursion == 0 then\n printError("Hashbang recursion depth limit reached when loading file: " .. path)\n return false\n end\n\n -- Load the specified hashbang program instead\n local hashbangArgs = tokenise(contents:sub(3))\n local originalHashbangPath = table.remove(hashbangArgs, 1)\n local resolvedHashbangProgram = shell.resolveProgram(originalHashbangPath)\n if not resolvedHashbangProgram then\n printError("Hashbang program not found: " .. originalHashbangPath)\n return false\n elseif resolvedHashbangProgram == "rom/programs/shell.lua" and #hashbangArgs == 0 then\n -- If we try to launch the shell then our shebang expands to "shell <program>", which just does a\n -- shell.run("<program>") again, resulting in an infinite loop. This may still happen (if the user\n -- has a custom shell), but this reduces the risk.\n -- It\'s a little ugly special-casing this, but it\'s probably worth warning about.\n printError("Cannot use the shell as a hashbang program")\n return false\n end\n\n -- Add the path and any arguments to the interpreter\'s arguments\n table.insert(hashbangArgs, path)\n for _, v in ipairs(args) do\n table.insert(hashbangArgs, v)\n end\n\n hashbangArgs[0] = originalHashbangPath\n return executeProgram(remainingRecursion, resolvedHashbangProgram, hashbangArgs)\n end\n\n contents = contents .. "\\n" .. (file.readAll() or "")\n file.close()\n\n local dir = fs.getDir(path)\n local env = setmetatable(createShellEnv(dir), { __index = _G })\n env.arg = args\n\n local func, err = load(contents, "@/" .. path, nil, env)\n if not func then\n -- We had a syntax error. Attempt to run it through our own parser if\n -- the file is "small enough", otherwise report the original error.\n if #contents < 1024 * 128 then\n local parser = require "cc.internal.syntax"\n if parser.parse_program(contents) then printError(err) end\n else\n printError(err)\n end\n\n return false\n end\n\n if settings.get("bios.strict_globals", false) then\n getmetatable(env).__newindex = function(_, name)\n error("Attempt to create global " .. tostring(name), 2)\n end\n end\n\n local ok, err, co = exception.try(func, table.unpack(args, 1, args.n))\n\n if ok then return true end\n\n if err and err ~= "" then\n printError(err)\n exception.report(err, co)\n end\n\n return false\nend\n\n--- Run a program with the supplied arguments.\n--\n-- Unlike [`shell.run`], each argument is passed to the program verbatim. While\n-- `shell.run("echo", "b c")` runs `echo` with `b` and `c`,\n-- `shell.execute("echo", "b c")` runs `echo` with a single argument `b c`.\n--\n-- @tparam string command The program to execute.\n-- @tparam string ... Arguments to this program.\n-- @treturn boolean Whether the program exited successfully.\n-- @since 1.88.0\n-- @usage Run `paint my-image` from within your program:\n--\n-- shell.execute("paint", "my-image")\nfunction shell.execute(command, ...)\n expect(1, command, "string")\n for i = 1, select(\'#\', ...) do\n expect(i + 1, select(i, ...), "string")\n end\n\n local sPath = shell.resolveProgram(command)\n if sPath ~= nil then\n tProgramStack[#tProgramStack + 1] = sPath\n if multishell then\n local sTitle = fs.getName(sPath)\n if sTitle:sub(-4) == ".lua" then\n sTitle = sTitle:sub(1, -5)\n end\n multishell.setTitle(multishell.getCurrent(), sTitle)\n end\n\n local result = executeProgram(100, sPath, { [0] = command, ... })\n\n tProgramStack[#tProgramStack] = nil\n if multishell then\n if #tProgramStack > 0 then\n local sTitle = fs.getName(tProgramStack[#tProgramStack])\n if sTitle:sub(-4) == ".lua" then\n sTitle = sTitle:sub(1, -5)\n end\n multishell.setTitle(multishell.getCurrent(), sTitle)\n else\n multishell.setTitle(multishell.getCurrent(), "shell")\n end\n end\n return result\n else\n printError("No such program")\n return false\n end\nend\n\n-- Install shell API\n\n--- Run a program with the supplied arguments.\n--\n-- All arguments are concatenated together and then parsed as a command line. As\n-- a result, `shell.run("program a b")` is the same as `shell.run("program",\n-- "a", "b")`.\n--\n-- @tparam string ... The program to run and its arguments.\n-- @treturn boolean Whether the program exited successfully.\n-- @usage Run `paint my-image` from within your program:\n--\n-- shell.run("paint", "my-image")\n-- @see shell.execute Run a program directly without parsing the arguments.\n-- @changed 1.80pr1 Programs now get their own environment instead of sharing the same one.\n-- @changed 1.83.0 `arg` is now added to the environment.\nfunction shell.run(...)\n local tWords = tokenise(...)\n local sCommand = tWords[1]\n if sCommand then\n return shell.execute(sCommand, table.unpack(tWords, 2))\n end\n return false\nend\n\n--- Exit the current shell.\n--\n-- This does _not_ terminate your program, it simply makes the shell terminate\n-- after your program has finished. If this is the toplevel shell, then the\n-- computer will be shutdown.\nfunction shell.exit()\n bExit = true\nend\n\n--- Return the current working directory. This is what is displayed before the\n-- `> ` of the shell prompt, and is used by [`shell.resolve`] to handle relative\n-- paths.\n--\n-- @treturn string The current working directory.\n-- @see setDir To change the working directory.\nfunction shell.dir()\n return sDir\nend\n\n--- Set the current working directory.\n--\n-- @tparam string dir The new working directory.\n-- @throws If the path does not exist or is not a directory.\n-- @usage Set the working directory to "rom"\n--\n-- shell.setDir("rom")\nfunction shell.setDir(dir)\n expect(1, dir, "string")\n if not fs.isDir(dir) then\n error("Not a directory", 2)\n end\n sDir = fs.combine(dir, "")\nend\n\n--- Set the path where programs are located.\n--\n-- The path is composed of a list of directory names in a string, each separated\n-- by a colon (`:`). On normal turtles will look in the current directory (`.`),\n-- `/rom/programs` and `/rom/programs/turtle` folder, making the path\n-- `.:/rom/programs:/rom/programs/turtle`.\n--\n-- @treturn string The current shell\'s path.\n-- @see setPath To change the current path.\nfunction shell.path()\n return sPath\nend\n\n--- Set the [current program path][`path`].\n--\n-- Be careful to prefix directories with a `/`. Otherwise they will be searched\n-- for from the [current directory][`shell.dir`], rather than the computer\'s root.\n--\n-- @tparam string path The new program path.\n-- @since 1.2\nfunction shell.setPath(path)\n expect(1, path, "string")\n sPath = path\nend\n\n--- Resolve a relative path to an absolute path.\n--\n-- The [`fs`] and [`io`] APIs work using absolute paths, and so we must convert\n-- any paths relative to the [current directory][`dir`] to absolute ones. This\n-- does nothing when the path starts with `/`.\n--\n-- @tparam string path The path to resolve.\n-- @usage Resolve `startup.lua` when in the `rom` folder.\n--\n-- shell.setDir("rom")\n-- print(shell.resolve("startup.lua"))\n-- -- => rom/startup.lua\nfunction shell.resolve(path)\n expect(1, path, "string")\n local sStartChar = string.sub(path, 1, 1)\n if sStartChar == "/" or sStartChar == "\\\\" then\n return fs.combine("", path)\n else\n return fs.combine(sDir, path)\n end\nend\n\nlocal function pathWithExtension(_sPath, _sExt)\n local nLen = #sPath\n local sEndChar = string.sub(_sPath, nLen, nLen)\n -- Remove any trailing slashes so we can add an extension to the path safely\n if sEndChar == "/" or sEndChar == "\\\\" then\n _sPath = string.sub(_sPath, 1, nLen - 1)\n end\n return _sPath .. "." .. _sExt\nend\n\n--- Resolve a program, using the [program path][`path`] and list of [aliases][`aliases`].\n--\n-- @tparam string command The name of the program\n-- @treturn string|nil The absolute path to the program, or [`nil`] if it could\n-- not be found.\n-- @since 1.2\n-- @changed 1.80pr1 Now searches for files with and without the `.lua` extension.\n-- @usage Locate the `hello` program.\n--\n-- shell.resolveProgram("hello")\n-- -- => rom/programs/fun/hello.lua\nfunction shell.resolveProgram(command)\n expect(1, command, "string")\n -- Substitute aliases firsts\n if tAliases[command] ~= nil then\n command = tAliases[command]\n end\n\n -- If the path is a global path, use it directly\n if command:find("/") or command:find("\\\\") then\n local sPath = shell.resolve(command)\n if fs.exists(sPath) and not fs.isDir(sPath) then\n return sPath\n else\n local sPathLua = pathWithExtension(sPath, "lua")\n if fs.exists(sPathLua) and not fs.isDir(sPathLua) then\n return sPathLua\n end\n end\n return nil\n end\n\n -- Otherwise, look on the path variable\n for sPath in string.gmatch(sPath, "[^:]+") do\n sPath = fs.combine(shell.resolve(sPath), command)\n if fs.exists(sPath) and not fs.isDir(sPath) then\n return sPath\n else\n local sPathLua = pathWithExtension(sPath, "lua")\n if fs.exists(sPathLua) and not fs.isDir(sPathLua) then\n return sPathLua\n end\n end\n end\n\n -- Not found\n return nil\nend\n\n--- Return a list of all programs on the [path][`shell.path`].\n--\n-- @tparam[opt] boolean include_hidden Include hidden files. Namely, any which\n-- start with `.`.\n-- @treturn { string } A list of available programs.\n-- @usage textutils.tabulate(shell.programs())\n-- @since 1.2\nfunction shell.programs(include_hidden)\n expect(1, include_hidden, "boolean", "nil")\n\n local tItems = {}\n\n -- Add programs from the path\n for sPath in string.gmatch(sPath, "[^:]+") do\n sPath = shell.resolve(sPath)\n if fs.isDir(sPath) then\n local tList = fs.list(sPath)\n for n = 1, #tList do\n local sFile = tList[n]\n if not fs.isDir(fs.combine(sPath, sFile)) and\n (include_hidden or string.sub(sFile, 1, 1) ~= ".") then\n if #sFile > 4 and sFile:sub(-4) == ".lua" then\n sFile = sFile:sub(1, -5)\n end\n tItems[sFile] = true\n end\n end\n end\n end\n\n -- Sort and return\n local tItemList = {}\n for sItem in pairs(tItems) do\n table.insert(tItemList, sItem)\n end\n table.sort(tItemList)\n return tItemList\nend\n\nlocal function completeProgram(sLine)\n local bIncludeHidden = settings.get("shell.autocomplete_hidden")\n if #sLine > 0 and (sLine:find("/") or sLine:find("\\\\")) then\n -- Add programs from the root\n return fs.complete(sLine, sDir, {\n include_files = true,\n include_dirs = false,\n include_hidden = bIncludeHidden,\n })\n\n else\n local tResults = {}\n local tSeen = {}\n\n -- Add aliases\n for sAlias in pairs(tAliases) do\n if #sAlias > #sLine and string.sub(sAlias, 1, #sLine) == sLine then\n local sResult = string.sub(sAlias, #sLine + 1)\n if not tSeen[sResult] then\n table.insert(tResults, sResult)\n tSeen[sResult] = true\n end\n end\n end\n\n -- Add all subdirectories. We don\'t include files as they will be added in the block below\n local tDirs = fs.complete(sLine, sDir, {\n include_files = false,\n include_dirs = false,\n include_hidden = bIncludeHidden,\n })\n for i = 1, #tDirs do\n local sResult = tDirs[i]\n if not tSeen[sResult] then\n table.insert (tResults, sResult)\n tSeen [sResult] = true\n end\n end\n\n -- Add programs from the path\n local tPrograms = shell.programs()\n for n = 1, #tPrograms do\n local sProgram = tPrograms[n]\n if #sProgram > #sLine and string.sub(sProgram, 1, #sLine) == sLine then\n local sResult = string.sub(sProgram, #sLine + 1)\n if not tSeen[sResult] then\n table.insert(tResults, sResult)\n tSeen[sResult] = true\n end\n end\n end\n\n -- Sort and return\n table.sort(tResults)\n return tResults\n end\nend\n\nlocal function completeProgramArgument(sProgram, nArgument, sPart, tPreviousParts)\n local tInfo = tCompletionInfo[sProgram]\n if tInfo then\n return tInfo.fnComplete(shell, nArgument, sPart, tPreviousParts)\n end\n return nil\nend\n\n--- Complete a shell command line.\n--\n-- This accepts an incomplete command, and completes the program name or\n-- arguments. For instance, `l` will be completed to `ls`, and `ls ro` will be\n-- completed to `ls rom/`.\n--\n-- Completion handlers for your program may be registered with\n-- [`shell.setCompletionFunction`].\n--\n-- @tparam string sLine The input to complete.\n-- @treturn { string }|nil The list of possible completions.\n-- @see _G.read For more information about completion.\n-- @see shell.completeProgram\n-- @see shell.setCompletionFunction\n-- @see shell.getCompletionInfo\n-- @since 1.74\nfunction shell.complete(sLine)\n expect(1, sLine, "string")\n if #sLine > 0 then\n local tWords = tokenise(sLine)\n local nIndex = #tWords\n if string.sub(sLine, #sLine, #sLine) == " " then\n nIndex = nIndex + 1\n end\n if nIndex == 1 then\n local sBit = tWords[1] or ""\n local sPath = shell.resolveProgram(sBit)\n if tCompletionInfo[sPath] then\n return { " " }\n else\n local tResults = completeProgram(sBit)\n for n = 1, #tResults do\n local sResult = tResults[n]\n local sPath = shell.resolveProgram(sBit .. sResult)\n if tCompletionInfo[sPath] then\n tResults[n] = sResult .. " "\n end\n end\n return tResults\n end\n\n elseif nIndex > 1 then\n local sPath = shell.resolveProgram(tWords[1])\n local sPart = tWords[nIndex] or ""\n local tPreviousParts = tWords\n tPreviousParts[nIndex] = nil\n return completeProgramArgument(sPath , nIndex - 1, sPart, tPreviousParts)\n\n end\n end\n return nil\nend\n\n--- Complete the name of a program.\n--\n-- @tparam string program The name of a program to complete.\n-- @treturn { string } A list of possible completions.\n-- @see cc.shell.completion.program\nfunction shell.completeProgram(program)\n expect(1, program, "string")\n return completeProgram(program)\nend\n\n--- Set the completion function for a program. When the program is entered on\n-- the command line, this program will be called to provide auto-complete\n-- information.\n--\n-- The completion function accepts four arguments:\n--\n-- 1. The current shell. As completion functions are inherited, this is not\n-- guaranteed to be the shell you registered this function in.\n-- 2. The index of the argument currently being completed.\n-- 3. The current argument. This may be the empty string.\n-- 4. A list of the previous arguments.\n--\n-- For instance, when completing `pastebin put rom/st` our pastebin completion\n-- function will receive the shell API, an index of 2, `rom/st` as the current\n-- argument, and a "previous" table of `{ "put" }`. This function may then wish\n-- to return a table containing `artup.lua`, indicating the entire command\n-- should be completed to `pastebin put rom/startup.lua`.\n--\n-- You completion entries may also be followed by a space, if you wish to\n-- indicate another argument is expected.\n--\n-- @tparam string program The path to the program. This should be an absolute path\n-- _without_ the leading `/`.\n-- @tparam function(shell: table, index: number, argument: string, previous: { string }):({ string }|nil) complete\n-- The completion function.\n-- @see cc.shell.completion Various utilities to help with writing completion functions.\n-- @see shell.complete\n-- @see _G.read For more information about completion.\n-- @since 1.74\nfunction shell.setCompletionFunction(program, complete)\n expect(1, program, "string")\n expect(2, complete, "function")\n tCompletionInfo[program] = {\n fnComplete = complete,\n }\nend\n\n--- Get a table containing all completion functions.\n--\n-- This should only be needed when building custom shells. Use\n-- [`setCompletionFunction`] to add a completion function.\n--\n-- @treturn { [string] = { fnComplete = function } } A table mapping the\n-- absolute path of programs, to their completion functions.\nfunction shell.getCompletionInfo()\n return tCompletionInfo\nend\n\n--- Returns the path to the currently running program.\n--\n-- @treturn string The absolute path to the running program.\n-- @since 1.3\nfunction shell.getRunningProgram()\n if #tProgramStack > 0 then\n return tProgramStack[#tProgramStack]\n end\n return nil\nend\n\n--- Add an alias for a program.\n--\n-- @tparam string command The name of the alias to add.\n-- @tparam string program The name or path to the program.\n-- @since 1.2\n-- @usage Alias `vim` to the `edit` program\n--\n-- shell.setAlias("vim", "edit")\nfunction shell.setAlias(command, program)\n expect(1, command, "string")\n expect(2, program, "string")\n tAliases[command] = program\nend\n\n--- Remove an alias.\n--\n-- @tparam string command The alias name to remove.\nfunction shell.clearAlias(command)\n expect(1, command, "string")\n tAliases[command] = nil\nend\n\n--- Get the current aliases for this shell.\n--\n-- Aliases are used to allow multiple commands to refer to a single program. For\n-- instance, the `list` program is aliased to `dir` or `ls`. Running `ls`, `dir`\n-- or `list` in the shell will all run the `list` program.\n--\n-- @treturn { [string] = string } A table, where the keys are the names of\n-- aliases, and the values are the path to the program.\n-- @see shell.setAlias\n-- @see shell.resolveProgram This uses aliases when resolving a program name to\n-- an absolute path.\nfunction shell.aliases()\n -- Copy aliases\n local tCopy = {}\n for sAlias, sCommand in pairs(tAliases) do\n tCopy[sAlias] = sCommand\n end\n return tCopy\nend\n\nif multishell then\n --- Open a new [`multishell`] tab running a command.\n --\n -- This behaves similarly to [`shell.run`], but instead returns the process\n -- index.\n --\n -- This function is only available if the [`multishell`] API is.\n --\n -- @tparam string ... The command line to run.\n -- @see shell.run\n -- @see multishell.launch\n -- @since 1.6\n -- @usage Launch the Lua interpreter and switch to it.\n --\n -- local id = shell.openTab("lua")\n -- shell.switchTab(id)\n function shell.openTab(...)\n local tWords = tokenise(...)\n local sCommand = tWords[1]\n if sCommand then\n local sPath = shell.resolveProgram(sCommand)\n if sPath == "rom/programs/shell.lua" then\n return multishell.launch(createShellEnv("rom/programs"), sPath, table.unpack(tWords, 2))\n elseif sPath ~= nil then\n return multishell.launch(createShellEnv("rom/programs"), "rom/programs/shell.lua", sCommand, table.unpack(tWords, 2))\n else\n printError("No such program")\n end\n end\n end\n\n --- Switch to the [`multishell`] tab with the given index.\n --\n -- @tparam number id The tab to switch to.\n -- @see multishell.setFocus\n -- @since 1.6\n function shell.switchTab(id)\n expect(1, id, "number")\n multishell.setFocus(id)\n end\nend\n\nlocal tArgs = { ... }\nif #tArgs > 0 then\n -- "shell x y z"\n -- Run the program specified on the commandline\n shell.run(...)\n\nelse\n local function show_prompt()\n term.setBackgroundColor(bgColour)\n term.setTextColour(promptColour)\n write(shell.dir() .. "> ")\n term.setTextColour(textColour)\n end\n\n -- "shell"\n -- Print the header\n term.setBackgroundColor(bgColour)\n term.setTextColour(promptColour)\n print(os.version())\n term.setTextColour(textColour)\n\n -- Run the startup program\n if parentShell == nil then\n shell.run("/rom/startup.lua")\n end\n\n -- Read commands and execute them\n local tCommandHistory = {}\n while not bExit do\n term.redirect(parentTerm)\n show_prompt()\n\n\n local complete\n if settings.get("shell.autocomplete") then complete = shell.complete end\n\n local ok, result\n local co = coroutine.create(read)\n assert(coroutine.resume(co, nil, tCommandHistory, complete))\n\n while coroutine.status(co) ~= "dead" do\n local event = table.pack(os.pullEvent())\n if event[1] == "file_transfer" then\n -- Abandon the current prompt\n local _, h = term.getSize()\n local _, y = term.getCursorPos()\n if y == h then\n term.scroll(1)\n term.setCursorPos(1, y)\n else\n term.setCursorPos(1, y + 1)\n end\n term.setCursorBlink(false)\n\n -- Run the import script with the provided files\n local ok, err = require("cc.internal.import")(event[2].getFiles())\n if not ok and err then printError(err) end\n\n -- And attempt to restore the prompt.\n show_prompt()\n term.setCursorBlink(true)\n event = { "term_resize", n = 1 } -- Nasty hack to force read() to redraw.\n end\n\n if result == nil or event[1] == result or event[1] == "terminate" then\n ok, result = coroutine.resume(co, table.unpack(event, 1, event.n))\n if not ok then error(result, 0) end\n end\n end\n\n if result:match("%S") and tCommandHistory[#tCommandHistory] ~= result then\n table.insert(tCommandHistory, result)\n end\n shell.run(result)\n end\nend\n',"rom/programs/shutdown.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif term.isColour() then\n term.setTextColour(colours.yellow)\nend\nprint("Goodbye")\nterm.setTextColour(colours.white)\n\nsleep(1)\nos.shutdown()\n',"rom/programs/time.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal nTime = os.time()\nlocal nDay = os.day()\nprint("The time is " .. textutils.formatTime(nTime, false) .. " on Day " .. nDay)\n',"rom/programs/turtle/craft.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif not turtle then\n printError("Requires a Turtle")\n return\nend\n\nif not turtle.craft then\n print("Requires a Crafty Turtle")\n return\nend\n\nlocal tArgs = { ... }\nlocal nLimit = tonumber(tArgs[1])\n\nif not nLimit and tArgs[1] ~= "all" then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " all|<number>")\n return\nend\n\nlocal nCrafted = 0\nlocal nOldCount = turtle.getItemCount(turtle.getSelectedSlot())\nif turtle.craft(nLimit) then\n local nNewCount = turtle.getItemCount(turtle.getSelectedSlot())\n if not nLimit or nOldCount <= nLimit then\n nCrafted = nNewCount\n else\n nCrafted = nOldCount - nNewCount\n end\nend\n\nif nCrafted > 1 then\n print(nCrafted .. " items crafted")\nelseif nCrafted == 1 then\n print("1 item crafted")\nelse\n print("No items crafted")\nend\n',"rom/programs/turtle/dance.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif not turtle then\n printError("Requires a Turtle")\nend\n\nlocal tMoves = {\n function()\n turtle.up()\n turtle.down()\n end,\n function()\n turtle.up()\n turtle.turnLeft()\n turtle.turnLeft()\n turtle.turnLeft()\n turtle.turnLeft()\n turtle.down()\n end,\n function()\n turtle.up()\n turtle.turnRight()\n turtle.turnRight()\n turtle.turnRight()\n turtle.turnRight()\n turtle.down()\n end,\n function()\n turtle.turnLeft()\n turtle.turnLeft()\n turtle.turnLeft()\n turtle.turnLeft()\n end,\n function()\n turtle.turnRight()\n turtle.turnRight()\n turtle.turnRight()\n turtle.turnRight()\n end,\n function()\n turtle.turnLeft()\n turtle.back()\n turtle.back()\n turtle.turnRight()\n turtle.turnRight()\n turtle.back()\n turtle.back()\n turtle.turnLeft()\n end,\n function()\n turtle.turnRight()\n turtle.back()\n turtle.back()\n turtle.turnLeft()\n turtle.turnLeft()\n turtle.back()\n turtle.back()\n turtle.turnRight()\n end,\n function()\n turtle.back()\n turtle.turnLeft()\n turtle.back()\n turtle.turnLeft()\n turtle.back()\n turtle.turnLeft()\n turtle.back()\n turtle.turnLeft()\n end,\n function()\n turtle.back()\n turtle.turnRight()\n turtle.back()\n turtle.turnRight()\n turtle.back()\n turtle.turnRight()\n turtle.back()\n turtle.turnRight()\n end,\n}\n\ntextutils.slowWrite("Preparing to get down.")\ntextutils.slowPrint("..", 0.75)\n\nlocal sAudio = nil\nfor _, sName in pairs(peripheral.getNames()) do\n if disk.hasAudio(sName) then\n disk.playAudio(sName)\n print("Jamming to " .. disk.getAudioTitle(sName))\n sAudio = sName\n break\n end\nend\n\nprint("Press any key to stop the groove")\n\nparallel.waitForAny(\n function() os.pullEvent("key") end,\n function()\n while true do\n tMoves[math.random(1, #tMoves)]()\n end\n end\n)\n\nif sAudio then\n disk.stopAudio(sAudio)\nend\n',"rom/programs/turtle/equip.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif not turtle then\n printError("Requires a Turtle")\n return\nend\n\nlocal tArgs = { ... }\nlocal function printUsage()\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <slot> <side>")\nend\n\nif #tArgs ~= 2 then\n printUsage()\n return\nend\n\nlocal function equip(nSlot, fnEquipFunction)\n turtle.select(nSlot)\n local nOldCount = turtle.getItemCount(nSlot)\n if nOldCount == 0 then\n print("Nothing to equip")\n elseif fnEquipFunction() then\n local nNewCount = turtle.getItemCount(nSlot)\n if nNewCount > 0 then\n print("Items swapped")\n else\n print("Item equipped")\n end\n else\n print("Item not equippable")\n end\nend\n\nlocal nSlot = tonumber(tArgs[1])\nlocal sSide = tArgs[2]\nif sSide == "left" then\n equip(nSlot, turtle.equipLeft)\nelseif sSide == "right" then\n equip(nSlot, turtle.equipRight)\nelse\n printUsage()\n return\nend\n',"rom/programs/turtle/excavate.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif not turtle then\n printError("Requires a Turtle")\n return\nend\n\nlocal tArgs = { ... }\nif #tArgs ~= 1 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <diameter>")\n return\nend\n\n-- Mine in a quarry pattern until we hit something we can\'t dig\nlocal size = tonumber(tArgs[1])\nif size < 1 then\n print("Excavate diameter must be positive")\n return\nend\n\nlocal depth = 0\nlocal unloaded = 0\nlocal collected = 0\n\nlocal xPos, zPos = 0, 0\nlocal xDir, zDir = 0, 1\n\nlocal goTo -- Filled in further down\nlocal refuel -- Filled in further down\n\nlocal function unload(_bKeepOneFuelStack)\n print("Unloading items...")\n for n = 1, 16 do\n local nCount = turtle.getItemCount(n)\n if nCount > 0 then\n turtle.select(n)\n local bDrop = true\n if _bKeepOneFuelStack and turtle.refuel(0) then\n bDrop = false\n _bKeepOneFuelStack = false\n end\n if bDrop then\n turtle.drop()\n unloaded = unloaded + nCount\n end\n end\n end\n collected = 0\n turtle.select(1)\nend\n\nlocal function returnSupplies()\n local x, y, z, xd, zd = xPos, depth, zPos, xDir, zDir\n print("Returning to surface...")\n goTo(0, 0, 0, 0, -1)\n\n local fuelNeeded = 2 * (x + y + z) + 1\n if not refuel(fuelNeeded) then\n unload(true)\n print("Waiting for fuel")\n while not refuel(fuelNeeded) do\n os.pullEvent("turtle_inventory")\n end\n else\n unload(true)\n end\n\n print("Resuming mining...")\n goTo(x, y, z, xd, zd)\nend\n\nlocal function collect()\n local bFull = true\n local nTotalItems = 0\n for n = 1, 16 do\n local nCount = turtle.getItemCount(n)\n if nCount == 0 then\n bFull = false\n end\n nTotalItems = nTotalItems + nCount\n end\n\n if nTotalItems > collected then\n collected = nTotalItems\n if math.fmod(collected + unloaded, 50) == 0 then\n print("Mined " .. collected + unloaded .. " items.")\n end\n end\n\n if bFull then\n print("No empty slots left.")\n return false\n end\n return true\nend\n\nfunction refuel(amount)\n local fuelLevel = turtle.getFuelLevel()\n if fuelLevel == "unlimited" then\n return true\n end\n\n local needed = amount or xPos + zPos + depth + 2\n if turtle.getFuelLevel() < needed then\n for n = 1, 16 do\n if turtle.getItemCount(n) > 0 then\n turtle.select(n)\n if turtle.refuel(1) then\n while turtle.getItemCount(n) > 0 and turtle.getFuelLevel() < needed do\n turtle.refuel(1)\n end\n if turtle.getFuelLevel() >= needed then\n turtle.select(1)\n return true\n end\n end\n end\n end\n turtle.select(1)\n return false\n end\n\n return true\nend\n\nlocal function tryForwards()\n if not refuel() then\n print("Not enough Fuel")\n returnSupplies()\n end\n\n while not turtle.forward() do\n if turtle.detect() then\n if turtle.dig() then\n if not collect() then\n returnSupplies()\n end\n else\n return false\n end\n elseif turtle.attack() then\n if not collect() then\n returnSupplies()\n end\n else\n sleep(0.5)\n end\n end\n\n xPos = xPos + xDir\n zPos = zPos + zDir\n return true\nend\n\nlocal function tryDown()\n if not refuel() then\n print("Not enough Fuel")\n returnSupplies()\n end\n\n while not turtle.down() do\n if turtle.detectDown() then\n if turtle.digDown() then\n if not collect() then\n returnSupplies()\n end\n else\n return false\n end\n elseif turtle.attackDown() then\n if not collect() then\n returnSupplies()\n end\n else\n sleep(0.5)\n end\n end\n\n depth = depth + 1\n if math.fmod(depth, 10) == 0 then\n print("Descended " .. depth .. " metres.")\n end\n\n return true\nend\n\nlocal function turnLeft()\n turtle.turnLeft()\n xDir, zDir = -zDir, xDir\nend\n\nlocal function turnRight()\n turtle.turnRight()\n xDir, zDir = zDir, -xDir\nend\n\nfunction goTo(x, y, z, xd, zd)\n while depth > y do\n if turtle.up() then\n depth = depth - 1\n elseif turtle.digUp() or turtle.attackUp() then\n collect()\n else\n sleep(0.5)\n end\n end\n\n if xPos > x then\n while xDir ~= -1 do\n turnLeft()\n end\n while xPos > x do\n if turtle.forward() then\n xPos = xPos - 1\n elseif turtle.dig() or turtle.attack() then\n collect()\n else\n sleep(0.5)\n end\n end\n elseif xPos < x then\n while xDir ~= 1 do\n turnLeft()\n end\n while xPos < x do\n if turtle.forward() then\n xPos = xPos + 1\n elseif turtle.dig() or turtle.attack() then\n collect()\n else\n sleep(0.5)\n end\n end\n end\n\n if zPos > z then\n while zDir ~= -1 do\n turnLeft()\n end\n while zPos > z do\n if turtle.forward() then\n zPos = zPos - 1\n elseif turtle.dig() or turtle.attack() then\n collect()\n else\n sleep(0.5)\n end\n end\n elseif zPos < z then\n while zDir ~= 1 do\n turnLeft()\n end\n while zPos < z do\n if turtle.forward() then\n zPos = zPos + 1\n elseif turtle.dig() or turtle.attack() then\n collect()\n else\n sleep(0.5)\n end\n end\n end\n\n while depth < y do\n if turtle.down() then\n depth = depth + 1\n elseif turtle.digDown() or turtle.attackDown() then\n collect()\n else\n sleep(0.5)\n end\n end\n\n while zDir ~= zd or xDir ~= xd do\n turnLeft()\n end\nend\n\nif not refuel() then\n print("Out of Fuel")\n return\nend\n\nprint("Excavating...")\n\nlocal reseal = false\nturtle.select(1)\nif turtle.digDown() then\n reseal = true\nend\n\nlocal alternate = 0\nlocal done = false\nwhile not done do\n for n = 1, size do\n for _ = 1, size - 1 do\n if not tryForwards() then\n done = true\n break\n end\n end\n if done then\n break\n end\n if n < size then\n if math.fmod(n + alternate, 2) == 0 then\n turnLeft()\n if not tryForwards() then\n done = true\n break\n end\n turnLeft()\n else\n turnRight()\n if not tryForwards() then\n done = true\n break\n end\n turnRight()\n end\n end\n end\n if done then\n break\n end\n\n if size > 1 then\n if math.fmod(size, 2) == 0 then\n turnRight()\n else\n if alternate == 0 then\n turnLeft()\n else\n turnRight()\n end\n alternate = 1 - alternate\n end\n end\n\n if not tryDown() then\n done = true\n break\n end\nend\n\nprint("Returning to surface...")\n\n-- Return to where we started\ngoTo(0, 0, 0, 0, -1)\nunload(false)\ngoTo(0, 0, 0, 0, 1)\n\n-- Seal the hole\nif reseal then\n turtle.placeDown()\nend\n\nprint("Mined " .. collected + unloaded .. " items total.")\n',"rom/programs/turtle/go.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif not turtle then\n printError("Requires a Turtle")\n return\nend\n\nlocal tArgs = { ... }\nif #tArgs < 1 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <direction> <distance>")\n return\nend\n\nlocal tHandlers = {\n ["fd"] = turtle.forward,\n ["forward"] = turtle.forward,\n ["forwards"] = turtle.forward,\n ["bk"] = turtle.back,\n ["back"] = turtle.back,\n ["up"] = turtle.up,\n ["dn"] = turtle.down,\n ["down"] = turtle.down,\n ["lt"] = turtle.turnLeft,\n ["left"] = turtle.turnLeft,\n ["rt"] = turtle.turnRight,\n ["right"] = turtle.turnRight,\n}\n\nlocal nArg = 1\nwhile nArg <= #tArgs do\n local sDirection = tArgs[nArg]\n local nDistance = 1\n if nArg < #tArgs then\n local num = tonumber(tArgs[nArg + 1])\n if num then\n nDistance = num\n nArg = nArg + 1\n end\n end\n nArg = nArg + 1\n\n local fnHandler = tHandlers[string.lower(sDirection)]\n if fnHandler then\n while nDistance > 0 do\n if fnHandler() then\n nDistance = nDistance - 1\n elseif turtle.getFuelLevel() == 0 then\n print("Out of fuel")\n return\n else\n sleep(0.5)\n end\n end\n else\n print("No such direction: " .. sDirection)\n print("Try: forward, back, up, down")\n return\n end\n\nend\n',"rom/programs/turtle/refuel.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif not turtle then\n printError("Requires a Turtle")\n return\nend\n\nlocal tArgs = { ... }\nlocal nLimit = 1\nif #tArgs > 1 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " [number]")\n return\nelseif #tArgs > 0 then\n if tArgs[1] == "all" then\n nLimit = nil\n else\n nLimit = tonumber(tArgs[1])\n if not nLimit then\n print("Invalid limit, expected a number or \\"all\\"")\n return\n end\n end\nend\n\nif turtle.getFuelLevel() ~= "unlimited" then\n for n = 1, 16 do\n -- Stop if we\'ve reached the limit, or are fully refuelled.\n if nLimit and nLimit <= 0 or turtle.getFuelLevel() >= turtle.getFuelLimit() then\n break\n end\n\n local nCount = turtle.getItemCount(n)\n if nCount > 0 then\n turtle.select(n)\n if turtle.refuel(nLimit) and nLimit then\n local nNewCount = turtle.getItemCount(n)\n nLimit = nLimit - (nCount - nNewCount)\n end\n end\n end\n print("Fuel level is " .. turtle.getFuelLevel())\n if turtle.getFuelLevel() == turtle.getFuelLimit() then\n print("Fuel limit reached")\n end\nelse\n print("Fuel level is unlimited")\nend\n',"rom/programs/turtle/tunnel.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif not turtle then\n printError("Requires a Turtle")\n return\nend\n\nlocal tArgs = { ... }\nif #tArgs ~= 1 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <length>")\n return\nend\n\n-- Mine in a quarry pattern until we hit something we can\'t dig\nlocal length = tonumber(tArgs[1])\nif length < 1 then\n print("Tunnel length must be positive")\n return\nend\nlocal collected = 0\n\nlocal function collect()\n collected = collected + 1\n if math.fmod(collected, 25) == 0 then\n print("Mined " .. collected .. " items.")\n end\nend\n\nlocal function tryDig()\n while turtle.detect() do\n if turtle.dig() then\n collect()\n sleep(0.5)\n else\n return false\n end\n end\n return true\nend\n\nlocal function tryDigUp()\n while turtle.detectUp() do\n if turtle.digUp() then\n collect()\n sleep(0.5)\n else\n return false\n end\n end\n return true\nend\n\nlocal function tryDigDown()\n while turtle.detectDown() do\n if turtle.digDown() then\n collect()\n sleep(0.5)\n else\n return false\n end\n end\n return true\nend\n\nlocal function refuel()\n local fuelLevel = turtle.getFuelLevel()\n if fuelLevel == "unlimited" or fuelLevel > 0 then\n return\n end\n\n local function tryRefuel()\n for n = 1, 16 do\n if turtle.getItemCount(n) > 0 then\n turtle.select(n)\n if turtle.refuel(1) then\n turtle.select(1)\n return true\n end\n end\n end\n turtle.select(1)\n return false\n end\n\n if not tryRefuel() then\n print("Add more fuel to continue.")\n while not tryRefuel() do\n os.pullEvent("turtle_inventory")\n end\n print("Resuming Tunnel.")\n end\nend\n\nlocal function tryUp()\n refuel()\n while not turtle.up() do\n if turtle.detectUp() then\n if not tryDigUp() then\n return false\n end\n elseif turtle.attackUp() then\n collect()\n else\n sleep(0.5)\n end\n end\n return true\nend\n\nlocal function tryDown()\n refuel()\n while not turtle.down() do\n if turtle.detectDown() then\n if not tryDigDown() then\n return false\n end\n elseif turtle.attackDown() then\n collect()\n else\n sleep(0.5)\n end\n end\n return true\nend\n\nlocal function tryForward()\n refuel()\n while not turtle.forward() do\n if turtle.detect() then\n if not tryDig() then\n return false\n end\n elseif turtle.attack() then\n collect()\n else\n sleep(0.5)\n end\n end\n return true\nend\n\nprint("Tunnelling...")\n\nfor n = 1, length do\n turtle.placeDown()\n tryDigUp()\n turtle.turnLeft()\n tryDig()\n tryUp()\n tryDig()\n turtle.turnRight()\n turtle.turnRight()\n tryDig()\n tryDown()\n tryDig()\n turtle.turnLeft()\n\n if n < length then\n tryDig()\n if not tryForward() then\n print("Aborting Tunnel.")\n break\n end\n else\n print("Tunnel complete.")\n end\n\nend\n\n--[[\nprint( "Returning to start..." )\n\n-- Return to where we started\nturtle.turnLeft()\nturtle.turnLeft()\nwhile depth > 0 do\n if turtle.forward() then\n depth = depth - 1\n else\n turtle.dig()\n end\nend\nturtle.turnRight()\nturtle.turnRight()\n]]\n\nprint("Tunnel complete.")\nprint("Mined " .. collected .. " items total.")\n',"rom/programs/turtle/turn.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif not turtle then\n printError("Requires a Turtle")\n return\nend\n\nlocal tArgs = { ... }\nif #tArgs < 1 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <direction> <turns>")\n return\nend\n\nlocal tHandlers = {\n ["lt"] = turtle.turnLeft,\n ["left"] = turtle.turnLeft,\n ["rt"] = turtle.turnRight,\n ["right"] = turtle.turnRight,\n}\n\nlocal nArg = 1\nwhile nArg <= #tArgs do\n local sDirection = tArgs[nArg]\n local nDistance = 1\n if nArg < #tArgs then\n local num = tonumber(tArgs[nArg + 1])\n if num then\n nDistance = num\n nArg = nArg + 1\n end\n end\n nArg = nArg + 1\n\n local fnHandler = tHandlers[string.lower(sDirection)]\n if fnHandler then\n for _ = 1, nDistance do\n fnHandler(nArg)\n end\n else\n print("No such direction: " .. sDirection)\n print("Try: left, right")\n return\n end\nend\n',"rom/programs/turtle/unequip.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nif not turtle then\n printError("Requires a Turtle")\n return\nend\n\nlocal tArgs = { ... }\nlocal function printUsage()\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <side>")\nend\n\nif #tArgs ~= 1 then\n printUsage()\n return\nend\n\nlocal function unequip(fnEquipFunction)\n for nSlot = 1, 16 do\n local nOldCount = turtle.getItemCount(nSlot)\n if nOldCount == 0 then\n turtle.select(nSlot)\n if fnEquipFunction() then\n local nNewCount = turtle.getItemCount(nSlot)\n if nNewCount > 0 then\n print("Item unequipped")\n return\n else\n print("Nothing to unequip")\n return\n end\n end\n end\n end\n print("No space to unequip item")\nend\n\nlocal sSide = tArgs[1]\nif sSide == "left" then\n unequip(turtle.equipLeft)\nelseif sSide == "right" then\n unequip(turtle.equipRight)\nelse\n printUsage()\n return\nend\n',"rom/programs/type.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal tArgs = { ... }\nif #tArgs < 1 then\n local programName = arg[0] or fs.getName(shell.getRunningProgram())\n print("Usage: " .. programName .. " <path>")\n return\nend\n\nlocal sPath = shell.resolve(tArgs[1])\nif fs.exists(sPath) then\n if fs.isDir(sPath) then\n print("directory")\n else\n print("file")\n end\nelse\n print("No such path")\nend\n',"rom/startup.lua":'-- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe\n--\n-- SPDX-License-Identifier: LicenseRef-CCPL\n\nlocal completion = require "cc.shell.completion"\n\n-- Setup paths\nlocal sPath = ".:/rom/programs:/rom/programs/http"\nif term.isColor() then\n sPath = sPath .. ":/rom/programs/advanced"\nend\nif turtle then\n sPath = sPath .. ":/rom/programs/turtle"\nelse\n sPath = sPath .. ":/rom/programs/rednet:/rom/programs/fun"\n if term.isColor() then\n sPath = sPath .. ":/rom/programs/fun/advanced"\n end\nend\nif pocket then\n sPath = sPath .. ":/rom/programs/pocket"\nend\nif commands then\n sPath = sPath .. ":/rom/programs/command"\nend\nshell.setPath(sPath)\nhelp.setPath("/rom/help")\n\n-- Setup aliases\nshell.setAlias("ls", "list")\nshell.setAlias("dir", "list")\nshell.setAlias("cp", "copy")\nshell.setAlias("mv", "move")\nshell.setAlias("rm", "delete")\nshell.setAlias("clr", "clear")\nshell.setAlias("rs", "redstone")\nshell.setAlias("sh", "shell")\nif term.isColor() then\n shell.setAlias("background", "bg")\n shell.setAlias("foreground", "fg")\nend\n\n-- Setup completion functions\n\nlocal function completePastebinPut(shell, text, previous)\n if previous[2] == "put" then\n return fs.complete(text, shell.dir(), true, false)\n end\nend\n\nshell.setCompletionFunction("rom/programs/alias.lua", completion.build(nil, completion.program))\nshell.setCompletionFunction("rom/programs/cd.lua", completion.build(completion.dir))\nshell.setCompletionFunction("rom/programs/clear.lua", completion.build({ completion.choice, { "screen", "palette", "all" } }))\nshell.setCompletionFunction("rom/programs/copy.lua", completion.build(\n { completion.dirOrFile, true },\n completion.dirOrFile\n))\nshell.setCompletionFunction("rom/programs/delete.lua", completion.build({ completion.dirOrFile, many = true }))\nshell.setCompletionFunction("rom/programs/drive.lua", completion.build(completion.dir))\nshell.setCompletionFunction("rom/programs/edit.lua", completion.build(completion.file))\nshell.setCompletionFunction("rom/programs/eject.lua", completion.build(completion.peripheral))\nshell.setCompletionFunction("rom/programs/gps.lua", completion.build({ completion.choice, { "host", "host ", "locate" } }))\nshell.setCompletionFunction("rom/programs/help.lua", completion.build(completion.help))\nshell.setCompletionFunction("rom/programs/id.lua", completion.build(completion.peripheral))\nshell.setCompletionFunction("rom/programs/label.lua", completion.build(\n { completion.choice, { "get", "get ", "set ", "clear", "clear " } },\n completion.peripheral\n))\nshell.setCompletionFunction("rom/programs/list.lua", completion.build(completion.dir))\nshell.setCompletionFunction("rom/programs/mkdir.lua", completion.build({ completion.dir, many = true }))\n\nlocal complete_monitor_extra = { "scale" }\nshell.setCompletionFunction("rom/programs/monitor.lua", completion.build(\n function(shell, text, previous)\n local choices = completion.peripheral(shell, text, previous, true)\n for _, option in pairs(completion.choice(shell, text, previous, complete_monitor_extra, true)) do\n choices[#choices + 1] = option\n end\n return choices\n end,\n function(shell, text, previous)\n if previous[2] == "scale" then\n return completion.peripheral(shell, text, previous, true)\n else\n return completion.programWithArgs(shell, text, previous, 3)\n end\n end,\n {\n function(shell, text, previous)\n if previous[2] ~= "scale" then\n return completion.programWithArgs(shell, text, previous, 3)\n end\n end,\n many = true,\n }\n))\n\nshell.setCompletionFunction("rom/programs/move.lua", completion.build(\n { completion.dirOrFile, true },\n completion.dirOrFile\n))\nshell.setCompletionFunction("rom/programs/redstone.lua", completion.build(\n { completion.choice, { "probe", "set ", "pulse " } },\n completion.side\n))\nshell.setCompletionFunction("rom/programs/rename.lua", completion.build(\n { completion.dirOrFile, true },\n completion.dirOrFile\n))\nshell.setCompletionFunction("rom/programs/shell.lua", completion.build({ completion.programWithArgs, 2, many = true }))\nshell.setCompletionFunction("rom/programs/type.lua", completion.build(completion.dirOrFile))\nshell.setCompletionFunction("rom/programs/set.lua", completion.build({ completion.setting, true }))\nshell.setCompletionFunction("rom/programs/advanced/bg.lua", completion.build({ completion.programWithArgs, 2, many = true }))\nshell.setCompletionFunction("rom/programs/advanced/fg.lua", completion.build({ completion.programWithArgs, 2, many = true }))\nshell.setCompletionFunction("rom/programs/fun/dj.lua", completion.build(\n { completion.choice, { "play", "play ", "stop " } },\n completion.peripheral\n))\nshell.setCompletionFunction("rom/programs/fun/speaker.lua", completion.build(\n { completion.choice, { "play ", "stop " } },\n function(shell, text, previous)\n if previous[2] == "play" then return completion.file(shell, text, previous, true)\n elseif previous[2] == "stop" then return completion.peripheral(shell, text, previous, false)\n end\n end,\n function(shell, text, previous)\n if previous[2] == "play" then return completion.peripheral(shell, text, previous, false)\n end\n end\n))\nshell.setCompletionFunction("rom/programs/fun/advanced/paint.lua", completion.build(completion.file))\nshell.setCompletionFunction("rom/programs/http/pastebin.lua", completion.build(\n { completion.choice, { "put ", "get ", "run " } },\n completePastebinPut\n))\nshell.setCompletionFunction("rom/programs/rednet/chat.lua", completion.build({ completion.choice, { "host ", "join " } }))\nshell.setCompletionFunction("rom/programs/command/exec.lua", completion.build(completion.command))\nshell.setCompletionFunction("rom/programs/http/wget.lua", completion.build({ completion.choice, { "run " } }))\n\nif turtle then\n shell.setCompletionFunction("rom/programs/turtle/go.lua", completion.build(\n { completion.choice, { "left", "right", "forward", "back", "down", "up" }, true, many = true }\n ))\n shell.setCompletionFunction("rom/programs/turtle/turn.lua", completion.build(\n { completion.choice, { "left", "right" }, true, many = true }\n ))\n shell.setCompletionFunction("rom/programs/turtle/equip.lua", completion.build(\n nil,\n { completion.choice, { "left", "right" } }\n ))\n shell.setCompletionFunction("rom/programs/turtle/unequip.lua", completion.build(\n { completion.choice, { "left", "right" } }\n ))\nend\n\n-- Run autorun files\nif fs.exists("/rom/autorun") and fs.isDir("/rom/autorun") then\n local tFiles = fs.list("/rom/autorun")\n for _, sFile in ipairs(tFiles) do\n if string.sub(sFile, 1, 1) ~= "." then\n local sPath = "/rom/autorun/" .. sFile\n if not fs.isDir(sPath) then\n shell.run(sPath)\n end\n end\n end\nend\n\nlocal function findStartups(sBaseDir)\n local tStartups = nil\n local sBasePath = "/" .. fs.combine(sBaseDir, "startup")\n local sStartupNode = shell.resolveProgram(sBasePath)\n if sStartupNode then\n tStartups = { sStartupNode }\n end\n -- It\'s possible that there is a startup directory and a startup.lua file, so this has to be\n -- executed even if a file has already been found.\n if fs.isDir(sBasePath) then\n if tStartups == nil then\n tStartups = {}\n end\n for _, v in pairs(fs.list(sBasePath)) do\n local sPath = "/" .. fs.combine(sBasePath, v)\n if not fs.isDir(sPath) then\n tStartups[#tStartups + 1] = sPath\n end\n end\n end\n return tStartups\nend\n\n-- Show MOTD\nif settings.get("motd.enable") then\n shell.run("motd")\nend\n\n-- Run the user created startup, either from disk drives or the root\nlocal tUserStartups = nil\nif settings.get("shell.allow_startup") then\n tUserStartups = findStartups("/")\nend\nif settings.get("shell.allow_disk_startup") then\n for _, sName in pairs(peripheral.getNames()) do\n if disk.isPresent(sName) and disk.hasData(sName) then\n local startups = findStartups(disk.getMountPath(sName))\n if startups then\n tUserStartups = startups\n break\n end\n end\n end\nend\nif tUserStartups then\n for _, v in pairs(tUserStartups) do\n shell.run(v)\n end\nend\n'},e.version="1.108.4"});