Expert knowledge for developing CC:Tweaked ComputerCraft Lua scripts in Minecraft. Use when writing turtle automation, computer programs, rednet communication, peripheral control, or any Minecraft ComputerCraft code.
I am an expert in developing Lua scripts for CC:Tweaked (ComputerCraft) mod in Minecraft. I help create turtle automation, computer programs, rednet networks, and peripheral integrations.
CC:Tweaked provides programmable computers and turtles in Minecraft:
CC:Tweaked 1.109.0+ uses Lua 5.2. Key differences from 5.1:
... for varargs (not arg)_ENV for environments (not getfenv/setfenv)goto statement available-- Movement (all return success, errorMessage)
turtle.forward() turtle.back()
turtle.up() turtle.down()
turtle.turnLeft() turtle.turnRight()
-- World Interaction
turtle.dig() turtle.digUp() turtle.digDown()
turtle.place() turtle.placeUp() turtle.placeDown()
turtle.attack() turtle.attackUp() turtle.attackDown()
-- Inventory (16 slots)
turtle.select(slot) -- 1-16
turtle.getItemDetail(slot?)
turtle.getItemCount(slot?)
turtle.transferTo(slot, count?)
turtle.drop(count?) turtle.dropUp() turtle.dropDown()
turtle.suck(count?) turtle.suckUp() turtle.suckDown()
-- Fuel System
turtle.getFuelLevel() -- number or "unlimited"
turtle.getFuelLimit()
turtle.refuel(count?) -- consume fuel items in selected slot
-- Inspection
turtle.inspect() -- returns success, blockData
turtle.inspectUp()
turtle.inspectDown()
turtle.detect() -- returns boolean
turtle.detectUp()
turtle.detectDown()
-- Comparison
turtle.compare() -- compare block in front to selected slot
turtle.compareUp()
turtle.compareDown()
turtle.compareTo(slot) -- compare selected slot to another slot
-- Crafting (requires crafty turtle)
turtle.craft(limit?)
-- Pull events (yields execution)
local event, p1, p2, p3 = os.pullEvent(filter?)
local event, ... = os.pullEventRaw(filter?) -- catches terminate
-- Common Events
-- "key", keyCode, isHeld
-- "key_up", keyCode
-- "char", character
-- "timer", timerId
-- "alarm", alarmId
-- "rednet_message", senderId, message, protocol
-- "modem_message", side, channel, replyChannel, message, distance
-- "turtle_inventory"
-- "peripheral", side
-- "peripheral_detach", side
-- "redstone"
-- "terminate"
-- "mouse_click", button, x, y
-- "monitor_touch", side, x, y
-- Setup
rednet.open("back") -- open modem on specified side
rednet.close() -- close all modems
-- Sending
rednet.send(recipientId, message, protocol?)
rednet.broadcast(message, protocol?)
-- Receiving
local senderId, message, protocol = rednet.receive(protocolFilter?, timeout?)
-- DNS-like naming
rednet.host(protocol, hostname)
rednet.unhost(protocol)
rednet.lookup(protocol, hostname?) -- returns id or table of ids
-- Discovery
peripheral.getNames() -- list all peripherals
peripheral.isPresent(side)
peripheral.getType(side)
peripheral.find(type, filter?) -- returns wrapped peripheral(s)
-- Usage
local p = peripheral.wrap(side)
p.someMethod()
-- or
peripheral.call(side, "method", args...)
-- Common peripheral types:
-- "modem", "monitor", "speaker", "drive", "printer"
-- "command" (command computer), "computer" (networked computer)
-- "inventory" (chests, etc via generic peripheral)
-- Reading/Writing
local file = fs.open("path", mode) -- "r", "w", "a", "rb", "wb", "ab"
local content = file.readAll()
file.write("data")
file.writeLine("line")
file.close()
-- File Operations
fs.exists(path)
fs.isDir(path)
fs.list(path) -- returns table of names
fs.makeDir(path)
fs.delete(path)
fs.move(from, to)
fs.copy(from, to)
fs.getSize(path)
fs.getFreeSpace(path)
-- Synchronous
local response = http.get(url, headers?, binary?)
local body = response.readAll()
response.close()
local response = http.post(url, body, headers?, binary?)
-- Asynchronous (fires http_success or http_failure events)
http.request(url, body?, headers?, binary?, method?)
-- WebSockets
local ws = http.websocket(url, headers?)
ws.send(message)
local msg = ws.receive(timeout?)
ws.close()
term.write(text)
term.clear()
term.clearLine()
term.setCursorPos(x, y)
term.getCursorPos()
term.getSize()
term.setTextColor(color)
term.setBackgroundColor(color)
term.scroll(n)
-- For monitors
local mon = peripheral.wrap("top")
mon.setTextScale(scale) -- 0.5 to 5
term.redirect(mon) -- redirect output to monitor
-- Run until any function completes
parallel.waitForAny(func1, func2, ...)
-- Run until all functions complete
parallel.waitForAll(func1, func2, ...)
-- Read redstone input from a side
redstone.getInput("top") -- returns boolean
redstone.getAnalogInput("top") -- returns 0-15
-- Set redstone output
redstone.setOutput("left", true)
redstone.setAnalogOutput("left", 15) -- 0-15
-- Bundled cable (if available)
redstone.getBundledInput("back")
redstone.setBundledOutput("back", colors.combine(colors.red, colors.blue))
-- Color constants for term, monitors, bundled cables
colors.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
-- Bundled cable combinations
colors.combine(colors.red, colors.blue)
colors.subtract(combined, colors.red)
colors.test(combined, colors.blue) -- returns boolean
local function safeDig()
local success, err = turtle.dig()
if not success and err ~= "Nothing to dig here" then
print("Dig failed: " .. tostring(err))
return false
end
return true
end
-- Prevent "Too long without yielding" error
for i = 1, 10000 do
doWork()
if i % 100 == 0 then
sleep(0) -- minimal yield
end
end
local function ensureFuel(minLevel)
local fuel = turtle.getFuelLevel()
if fuel == "unlimited" then return true end
if fuel < minLevel then
for slot = 1, 16 do
turtle.select(slot)
if turtle.refuel(0) then -- test if item is fuel
turtle.refuel()
end
if turtle.getFuelLevel() >= minLevel then
return true
end
end
return false
end
return true
end
-- utils.lua
local M = {}
function M.log(msg)
print("[" .. os.date("%H:%M:%S") .. "] " .. msg)
end
return M
-- main.lua
local utils = require("utils")
utils.log("Started")
-- startup.lua (runs on boot)
shell.run("bg_program") -- run in background
shell.run("main") -- run main program
startup, startup.lua, or main.lua).require from the same folder.pastebin and wget usage.pastebin put <file.lua> then pastebin get <id> <file.lua>wget http://<host>:8000/path/file.lua file.luasaves/<world>/computercraft/computer/<id>/copy/cplocal function mineForward()
while turtle.detect() do
turtle.dig()
sleep(0.4) -- wait for gravel/sand
end
return turtle.forward()
end
rednet.open("back")
rednet.host("myservice", "server1")
while true do
local senderId, message, protocol = rednet.receive("myservice")
if message.type == "request" then
local response = handleRequest(message.data)
rednet.send(senderId, {type="response", data=response}, "myservice")
end
end
local x, y, z = gps.locate(5) -- 5 second timeout
if x then
print(("Position: %d, %d, %d"):format(x, y, z))
else
print("GPS unavailable")
end
write("length: ")
local length = tonumber(read())
write("direction (l, r): ")
local direction = read():lower()
-- Normalize input
if direction == "l" or direction == "left" then
direction = "left"
elseif direction == "r" or direction == "right" then
direction = "right"
end
local MIN_FUEL_LEVEL = 100
local function verifyFuelLevel()
local fuelLevel = turtle.getFuelLevel()
if fuelLevel ~= "unlimited" and fuelLevel <= MIN_FUEL_LEVEL then
write("Fuel level low. Insert fuel & press enter to continue.\n")
read()
shell.run("refuel", "all")
print("New fuel level: " .. turtle.getFuelLevel())
end
end
-- Keep digging until block stops falling
local function digUntilEmpty()
while turtle.detect() do
turtle.dig()
sleep(0.4) -- wait for falling blocks
end
end
local function forwardAndDig()
repeat
turtle.dig()
until turtle.forward()
end
-- Monitor redstone and control outputs
while true do
if redstone.getInput("top") then
redstone.setOutput("left", true)
end
if redstone.getInput("right") then
redstone.setOutput("left", false)
end
os.sleep(1)
end
local function safeRednetOpen(side)
if not rednet.isOpen() then
rednet.open(side or "top")
end
end
local function getCords()
while true do
local x, y, z = gps.locate()
if x then return x, y, z end
os.sleep(1)
end
end
local function startTransmitter(topCord, bottomCord)
safeRednetOpen("top")
while true do
local x, y, z = getCords()
if y < bottomCord then
rednet.broadcast("AT_BOTTOM")
os.sleep(60)
elseif y > topCord then
rednet.broadcast("AT_TOP")
os.sleep(60)
end
os.sleep(1)
end
end
local function startReceiver(messageName, redstoneSide, value)
safeRednetOpen("top")
while true do
local senderId, message = rednet.receive()
if message == messageName then
redstone.setOutput(redstoneSide, value)
end
os.sleep(1)
end
end
local slot = 1
local function checkAndFillSlot()
while turtle.getItemCount(slot) == 0 do
slot = slot + 1
if slot > 16 then
slot = 1
end
turtle.select(slot)
end
end
local turn = "left"
local function adjustOrientation()
if turn == "left" then
turtle.turnLeft()
forwardAndDig()
turtle.turnLeft()
turn = "right"
else
turtle.turnRight()
forwardAndDig()
turtle.turnRight()
turn = "left"
end
end
-- Mine a 3D area
for depth = 1, maxDepth do
for length = 1, maxLength do
for width = 1, maxWidth - 1 do
digUpOrDown()
forwardAndDig()
end
digUpOrDown()
if length ~= maxLength then
adjustOrientation()
end
end
-- Move to next layer
if direction == "up" then turtle.up() else turtle.down() end
turtle.turnLeft() turtle.turnLeft() -- reverse direction
end
docs/cc-tweaked/scripts/turtle/, scripts/computer/