-- Queue to store pending evaluations
local evalQueue = {}
-- Function to handle a single evaluation
local function handleEval(ws, obj)
local func = loadstring(obj["function"])
if func == nil then
return
end
local funcArgs = obj["args"]
if funcArgs == nil then
funcArgs = {}
end
local ok, result = pcall(func, unpack(funcArgs))
if not ok then
return
end
ws.send(textutils.serialiseJSON({ data = result }))
end
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
-- Function to process the evaluation queue
local function processEvalQueue(ws)
while true do
if #evalQueue > 0 then
local obj = table.remove(evalQueue, 1)
handleEval(ws, obj)
end
os.sleep(0.1)
end
end
-- Function to run the websocket receiver
local function runWebsocketReceiver(ws)
while true do
if ws == nil then
return
end
code
local ok, msg = pcall(ws.receive, 2)
if not ok then
os.sleep(2)
return
end
if msg ~= nil then
local obj = textutils.unserialiseJSON(msg)
if obj.type == "eval" then
-- Add the evaluation to the queue
table.insert(evalQueue, obj)
end
end
end
end
-- Main loop
while true do
local ws = http.websocket("wss://turtle.drewh.net/ws/" .. name)
ws.send(textutils.serialiseJSON({ type = "opening", name = name, isTurtle = turtle ~= nil }))
code
-- Run the websocket receiver and queue processor in parallel
parallel.waitForAny(
function()
runWebsocketReceiver(ws)
end,
function()
processEvalQueue(ws)
end
)
end
What is this file
Assistant
This Lua script is designed for a ComputerCraft (or CC:Tweaked) computer or turtle. Its primary purpose is to connect to a remote WebSocket server and allow that server to remotely execute Lua code on the ComputerCraft device.
Here's a breakdown of its functionality:
cPrint(msg) function:
A utility function that sends a msg (string) via an HTTP POST request to https://turtle.drewh.net/status. This is likely used for logging status updates or initial information to a web service.
Initial Setup:
args = { ... }: Captures any command-line arguments passed when the script is run (though not used in this specific script).
file = fs.open("computer.txt", "r"): Opens a file named "computer.txt" in read mode.
name = file.readAll(): Reads the entire content of "computer.txt". This name is used to identify this specific computer/turtle to the server.
print("computer name is: " .. name): Prints the computer's name to its local console.
peripheral.getNames(): Gets a list of all connected peripherals (e.g., modem, drive, monitor, turtle tools).
textutils.serialiseJSON(...): Converts this list into a JSON string.
cPrint(...): Sends this JSON string to the status URL. So, on startup, it reports its name and its connected peripherals.
evalQueue = {}:
Initializes an empty table. This table will act as a First-In, First-Out (FIFO) queue to store code execution requests received from the server. This prevents the system from being overwhelmed if multiple requests arrive quickly.
handleEval(ws, obj) function:
This function takes a websocket object (ws) and a Lua table obj (which is a deserialized JSON message from the server).
local func = loadstring(obj["function"]): It attempts to compile Lua code received as a string in obj.function into an executable Lua function. This is the core of the remote code execution.
if func == nil then return end: If the code string is invalid and cannot be compiled, it exits.
local funcArgs = obj["args"]: It retrieves arguments for the function, also sent by the server.
local ok, result = pcall(func, unpack(funcArgs)): It executes the compiled func with the provided funcArgs in a "protected call" (pcall). This means if the executed code errors, the script itself won't crash. ok will be false if there's an error.
if not ok then return end: If the execution failed, it exits (it doesn't report the error back in this version, which could be an improvement).
ws.send(textutils.serialiseJSON({ data = result })): If the execution was successful, it sends the result of the function back to the server over the websocket, formatted as a JSON object.
processEvalQueue(ws) function:
An infinite loop that continuously checks the evalQueue.
if #evalQueue > 0 then ...: If there are items in the queue.
local obj = table.remove(evalQueue, 1): It takes the oldest request from the front of the queue.
handleEval(ws, obj): It processes this request using the handleEval function.
os.sleep(0.1): It pauses briefly to prevent a tight loop from consuming too much CPU and to allow other tasks (like receiving new messages) to run.
runWebsocketReceiver(ws) function:
An infinite loop responsible for listening for messages from the websocket.
local ok, msg = pcall(ws.receive, 2): It attempts to receive a message from the ws with a 2-second timeout. pcall is used to catch errors if ws.receive fails (e.g., connection lost).
if not ok then os.sleep(2); return end: If ws.receive itself errors (likely a disconnect), it sleeps for 2 seconds and then returns. This will cause the parallel.waitForAny in the main loop to exit, leading to a reconnection attempt.
if msg ~= nil then ...: If a message is received.
local obj = textutils.unserialiseJSON(msg): It deserializes the JSON message string into a Lua table.
if obj.type == "eval" then ...: If the message has a type field equal to "eval".
table.insert(evalQueue, obj): It adds the entire obj (containing the function string and arguments) to the evalQueue to be processed later.
Main Loop (while true do ... end):
This is the main execution block that runs indefinitely.
local ws = http.websocket("wss://turtle.drewh.net/ws/" .. name): It attempts to establish a WebSocket connection to the server. The URL is constructed using the name read from "computer.txt", making the endpoint unique for this computer/turtle (e.g., wss://turtle.drewh.net/ws/MyTurtle123).
ws.send(textutils.serialiseJSON({ type = "opening", name = name, isTurtle = turtle ~= nil })):
Immediately after connecting, it sends an "opening" message to the server.
This message includes its name and a boolean isTurtle (which is true if the turtle global API exists, indicating it's a turtle, and false otherwise).
parallel.waitForAny(...): This is crucial for concurrency. It runs two functions "simultaneously" (by rapidly switching between them):
function() runWebsocketReceiver(ws) end: This runs the function to listen for incoming messages.
function() processEvalQueue(ws) end: This runs the function to process any commands in the queue.
parallel.waitForAny will continue until one of these functions returns. As designed, processEvalQueue is an infinite loop internally. runWebsocketReceiver will return if the websocket connection is lost or ws.receive errors.
If runWebsocketReceiver returns (signaling a disconnect), parallel.waitForAny finishes. The main while true loop then iterates, and the script attempts to re-establish the WebSocket connection.
In Summary:
This script turns a ComputerCraft computer or turtle into a remotely controlled agent.
It identifies itself to a central server (turtle.drewh.net) using a name stored in "computer.txt".
It reports its initial status (peripherals, whether it's a turtle).
It maintains a persistent WebSocket connection to the server.
It listens for "eval" commands from the server, which contain Lua code and arguments.
It queues these commands and executes them one by one.
It sends the results of the executed code back to the server.
It automatically attempts to reconnect if the WebSocket connection is lost.
This is a common pattern for managing and controlling multiple ComputerCraft devices from a central web interface or application. The use of loadstring means the server has full control over the computer/turtle and can make it do anything the ComputerCraft API allows.