-- ============================================================================ -- MinecraftPE Lua API (LuaJIT) -- This file is loaded by the game before any mod. It builds the friendly -- `mc` API on top of the native primitives (mc._*) that the game provides. -- Documentation: mods/README.md -- ============================================================================ local mc = mc mc.VERSION = "1.0" local floor, max, min = math.floor, math.max, math.min -- ---------------------------------------------------------------- utilities mc.util = {} function mc.util.split(s, sep) local out = {} sep = sep or "%s+" for piece in string.gmatch(s, "([^" .. (sep == "%s+" and "%s" or sep) .. "]+)") do out[#out + 1] = piece end return out end function mc.util.copy(t) local c = {} for k, v in pairs(t) do c[k] = v end return c end local function serialize(v, indent) local t = type(v) if t == "number" or t == "boolean" then return tostring(v) end if t == "string" then return string.format("%q", v) end if t == "table" then local parts = {} for k, val in pairs(v) do parts[#parts + 1] = "[" .. serialize(k) .. "]=" .. serialize(val) end return "{" .. table.concat(parts, ",") .. "}" end return "nil" end --- Saves a plain Lua table (numbers, strings, booleans, tables) to a file. function mc.save_table(path, tbl) local f, err = io.open(path, "w") if not f then return false, err end f:write("return ", serialize(tbl)) f:close() return true end --- Loads a table written by mc.save_table, or returns `default`. function mc.load_table(path, default) local chunk = loadfile(path) if not chunk then return default end setfenv(chunk, {}) local ok, res = pcall(chunk) if ok then return res end return default end function mc.log(...) local parts = {} for i = 1, select("#", ...) do parts[i] = tostring((select(i, ...))) end mc._log(table.concat(parts, " ")) end -- ------------------------------------------------------------------ blocks local BLOCKS = { [0] = "air", [1] = "stone", [2] = "grass", [3] = "dirt", [4] = "cobblestone", [5] = "planks", [6] = "sapling", [7] = "bedrock", [8] = "flowing_water", [9] = "water", [10] = "flowing_lava", [11] = "lava", [12] = "sand", [13] = "gravel", [14] = "gold_ore", [15] = "iron_ore", [16] = "coal_ore", [17] = "log", [18] = "leaves", [20] = "glass", [21] = "lapis_ore", [22] = "lapis_block", [24] = "sandstone", [26] = "bed", [30] = "cobweb", [31] = "tallgrass", [35] = "wool", [37] = "dandelion", [38] = "rose", [39] = "brown_mushroom", [40] = "red_mushroom", [41] = "gold_block", [42] = "iron_block", [43] = "double_slab", [44] = "slab", [45] = "bricks", [46] = "tnt", [47] = "bookshelf", [48] = "mossy_cobblestone", [49] = "obsidian", [50] = "torch", [51] = "fire", [53] = "oak_stairs", [54] = "chest", [56] = "diamond_ore", [57] = "diamond_block", [58] = "crafting_table", [59] = "wheat", [60] = "farmland", [61] = "furnace", [62] = "lit_furnace", [63] = "sign", [64] = "wooden_door", [65] = "ladder", [67] = "stone_stairs", [68] = "wall_sign", [71] = "iron_door", [73] = "redstone_ore", [74] = "lit_redstone_ore", [78] = "snow_layer", [79] = "ice", [80] = "snow", [81] = "cactus", [82] = "clay", [83] = "reeds", [85] = "fence", [86] = "pumpkin", [87] = "netherrack", [89] = "glowstone", [91] = "jack_o_lantern", [96] = "trapdoor", [98] = "stonebrick", [102] = "glass_pane", [103] = "melon", [105] = "melon_stem", [107] = "fence_gate", [108] = "brick_stairs", [109] = "stonebrick_stairs", [112] = "nether_brick", [114] = "nether_brick_stairs", [128] = "sandstone_stairs", [129] = "emerald_ore", [133] = "emerald_block", [155] = "quartz_block", [156] = "quartz_stairs", [245] = "stonecutter", [246] = "glowing_obsidian", [247] = "nether_reactor", } local ALIASES = { rock = 1, smooth_stone = 1, grass_block = 2, cobble = 4, wood = 5, wood_planks = 5, oak_planks = 5, planks = 5, sapling = 6, adminium = 7, bed_rock = 7, water = 9, still_water = 9, stationary_water = 9, lava = 11, still_lava = 11, stationary_lava = 11, flowing_water = 8, flowing_lava = 10, gold = 14, iron = 15, coal = 16, trunk = 17, tree = 17, wood_log = 17, oak_log = 17, leaf = 18, leaves = 18, lapis = 21, sandstone = 24, web = 30, grass_plant = 31, cloth = 35, flower = 37, yellow_flower = 37, red_flower = 38, goldblock = 41, ironblock = 42, brick = 45, bricks = 45, mossy = 48, mossy_cobble = 48, moss = 48, obsidian = 49, torch = 50, fire = 51, chest = 54, diamond = 56, workbench = 58, crafting = 58, table = 58, furnace = 61, ladder = 65, ice = 79, snowblock = 80, snow_block = 80, cactus = 81, clay = 82, sugarcane = 83, fence = 85, glowstone = 89, lightstone = 89, netherrack = 87, hell = 87, stonebricks = 98, stone_brick = 98, stone_bricks = 98, melon = 103, quartz = 155, door = 64, iron_door = 71, tnt = 46, bookshelf = 47, books = 47, glass = 20, sand = 12, gravel = 13, dirt = 3, stone = 1, grass = 2, bedrock = 7, pane = 102, trap_door = 96, pumpkin = 86, lantern = 91, stair = 53, stairs = 53, double_step = 43, step = 44, half_slab = 44, slab = 44, double_slab = 43, farmland = 60, soil = 60, } local WOOL = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" } local WOOL_DATA = {} for i, name in ipairs(WOOL) do WOOL_DATA[name] = i - 1 ALIASES[name .. "_wool"] = { 35, i - 1 } end local NAME_TO_ID = {} for id, name in pairs(BLOCKS) do NAME_TO_ID[name] = id end mc.block = { ids = NAME_TO_ID, names = BLOCKS } --- Name of a block id ("stone"), or the number as a string. function mc.block.name(id) return BLOCKS[id] or tostring(id) end --- Parses "stone", "35:14", "red_wool", "log:1" -> id, data (data is nil when not given) function mc.block.parse(text) text = string.lower(text) local nameOrId, data = string.match(text, "^([%w_]+):(%d+)$") if nameOrId then data = tonumber(data) else nameOrId = text end local id = tonumber(nameOrId) if not id then local alias = ALIASES[nameOrId] if type(alias) == "table" then id, data = alias[1], data or alias[2] else id = alias or NAME_TO_ID[nameOrId] end end if not id or id < 0 or id > 255 then return nil end return id, data end -- Blocks that are not solid ground (used by e.g. //green, //naturalize, //ascend) mc.block.AIR = 0 -- ------------------------------------------------------------------- items mc.item = { stick = 280, compass = 345, wooden_axe = 271, wooden_pickaxe = 270, wooden_shovel = 269, wooden_sword = 268, stone_axe = 275, iron_axe = 258, diamond_axe = 279, flint_and_steel = 259, apple = 260, bow = 261, arrow = 262, coal = 263, diamond = 264, iron_ingot = 265, gold_ingot = 266, bucket = 325, water_bucket = 326, lava_bucket = 327, clock = 347, paper = 339, book = 340, } mc.mob = { chicken = 10, cow = 11, pig = 12, sheep = 13, zombie = 32, creeper = 33, skeleton = 34, spider = 35, pig_zombie = 36 } -- ------------------------------------------------------------------ players local Player = {} Player.__index = Player local playerCache = {} local function getPlayer(id) if not id then return nil end local p = playerCache[id] if not p then local name = mc._pname(id) if not name then return nil end p = setmetatable({ id = id, name = name, data = {} }, Player) playerCache[id] = p end return p end mc._player = getPlayer function Player:__tostring() return "Player(" .. self.name .. ")" end --- Feet position: x, y, z function Player:pos() local x, y, z = mc._ppos(self.id); return x, y, z end --- Block the feet are in function Player:block_pos() local x, y, z = mc._ppos(self.id) return floor(x), floor(y), floor(z) end --- yaw, pitch in degrees function Player:look() local _, _, _, yaw, pitch = mc._ppos(self.id); return yaw, pitch end --- Horizontal facing as 0..3 (south, west, north, east) and its unit vector function Player:facing() local yaw = self:look() local dir = floor(((yaw % 360) + 45) / 90) % 4 local vec = { [0] = { 0, 1 }, [1] = { -1, 0 }, [2] = { 0, -1 }, [3] = { 1, 0 } } return dir, vec[dir][1], vec[dir][2] end function Player:teleport(x, y, z, yaw, pitch) mc._pteleport(self.id, x, y, z, yaw, pitch) end function Player:say(...) local parts = {} for i = 1, select("#", ...) do parts[i] = tostring((select(i, ...))) end local text = table.concat(parts, " ") for line in string.gmatch(text .. "\n", "(.-)\n") do if line ~= "" then mc._pmsg(self.id, line) end end end function Player:is_op() return mc._pop(self.id) end --- id, data, count of the held item (0,0,0 when empty) function Player:held() return mc._pheld(self.id) end function Player:give(id, count, data) mc._pgive(self.id, id, count or 1, data or 0) end --- 0 = survival, 1 = creative function Player:gamemode() return mc._pgamemode() end --- x, y, z, face of the block the player is looking at, or nil function Player:target(distance) return mc._ptrace(self.id, distance or 128) end function Player:is_online() return mc._pname(self.id) ~= nil end mc.Player = Player function mc.players() local list = {} for i, id in ipairs(mc._players()) do list[i] = getPlayer(id) end return list end function mc.player(name) name = string.lower(name) for _, id in ipairs(mc._players()) do local p = getPlayer(id) if p and string.lower(p.name) == name then return p end end return nil end function mc.broadcast(text) mc._broadcast(text) end -- -------------------------------------------------------------------- world mc.world = {} local W = mc.world W.get_block = mc._get_block W.set_block = mc._set_block --- Re-sends/relights everything written with silent set_block calls W.flush = mc._flush W.is_loaded = mc._loaded W.ensure_loaded = mc._ensure W.seed = mc._seed W.explode = mc._explode W.spawn_mob = mc._spawn_mob W.drop_item = mc._drop_item W.butcher = mc._butcher W.height = mc._solid_height W.get_time = mc._get_time W.set_time = mc._set_time -- ---------------------------------------------------------------- scheduler local tasks, nextTask, tickCount = {}, 1, 0 mc.tick_count = 0 function mc.after(ticks, fn) local id = nextTask; nextTask = nextTask + 1 tasks[id] = { at = tickCount + max(1, ticks), fn = fn } return id end function mc.every(ticks, fn) local id = nextTask; nextTask = nextTask + 1 tasks[id] = { at = tickCount + max(1, ticks), fn = fn, period = max(1, ticks) } return id end function mc.cancel(id) tasks[id] = nil end -- ------------------------------------------------------------------- events local handlers = {} --- mc.on("block_break", function(player, x, y, z, tile) return false end) --- Events: start, stop, tick, join, leave, chat, block_break, use_item --- Returning false from a cancellable event (chat, block_break, use_item) cancels it. function mc.on(event, fn) handlers[event] = handlers[event] or {} table.insert(handlers[event], fn) end local function report(modName, err) mc._log("error in handler: " .. tostring(err)) end function mc._fire(event, pid, ...) local list = handlers[event] if not list then return true end local first = pid if pid ~= nil then first = getPlayer(pid) end local result = true for i = 1, #list do local ok, res = xpcall(list[i], debug.traceback, first, ...) if not ok then report(nil, res) elseif res == false then result = false end end if event == "leave" and pid then playerCache[pid] = nil end return result end function mc._tick() tickCount = tickCount + 1 mc.tick_count = tickCount for id, task in pairs(tasks) do if task.at <= tickCount then if task.period then task.at = tickCount + task.period else tasks[id] = nil end local ok, err = xpcall(task.fn, debug.traceback) if not ok then report(nil, err) end end end if handlers.tick then mc._fire("tick") end end -- ----------------------------------------------------------------- commands local commands = {} --- mc.command("home", { description = "...", usage = "/home", op = false }, function(ctx) ... end) --- Names are what the player types after the first slash, so WorldEdit's "//set" is "/set". function mc.command(name, opts, fn) if type(opts) == "function" then fn, opts = opts, {} end commands[string.lower(name)] = { fn = fn, opts = opts or {}, name = name } end function mc._command_names() local names = {} for name in pairs(commands) do names[#names + 1] = name end table.sort(names) return names end function mc._run_command(pid, name, args) local cmd = commands[string.lower(name)] if not cmd then return false end local player = getPlayer(pid) if cmd.opts.op and not player:is_op() then return true, "You are not allowed to use this command." end local replies = {} local ctx = { player = player, args = args, name = name, reply = function(_, ...) player:say(...) end, } setmetatable(ctx, { __index = function(_, k) return nil end }) local ok, res = xpcall(cmd.fn, debug.traceback, ctx) if not ok then mc._log("command /" .. name .. " failed: " .. tostring(res)) return true, "Command failed: " .. tostring(res):match("^[^\n]*") end if type(res) == "string" then return true, res end return true end -- ------------------------------------------------------------------- mods mc.mods = {} local function listDir(dir) return mc._listdir and mc._listdir(dir) or {} end local function loadMod(name, dir, file) local env = setmetatable({}, { __index = _G }) env.MOD = { name = name, dir = dir } env.require = function(m) local path = dir .. "/" .. m:gsub("%.", "/") .. ".lua" local chunk = loadfile(path) if chunk then setfenv(chunk, env) return chunk() end return require(m) end local chunk, err = loadfile(file) if not chunk then mc._log("cannot load mod '" .. name .. "': " .. tostring(err)) return end setfenv(chunk, env) local ok, res = xpcall(chunk, debug.traceback) if not ok then mc._log("mod '" .. name .. "' failed: " .. tostring(res)) return end mc.mods[name] = env.MOD mc._log("loaded mod '" .. name .. "'") end function mc._load_mods() local entries = listDir("mods") table.sort(entries, function(a, b) return a.name < b.name end) for _, e in ipairs(entries) do if e.dir then local main = "mods/" .. e.name .. "/main.lua" local f = io.open(main, "r") if f then f:close(); loadMod(e.name, "mods/" .. e.name, main) end elseif e.name:match("%.lua$") then loadMod((e.name:gsub("%.lua$", "")), "mods", "mods/" .. e.name) end end mc._fire("start") for _, id in ipairs(mc._players()) do mc._fire("join", id) end end