Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local myenv = getfenv()
- local turtle = turtle
- local env = {
- turtle = {
- select = turtle.select,
- drop = turtle.drop
- }
- }
- setmetatable(env, {__index = myenv, __newindex = myenv})
- local undolist = {}
- -- initially: +X is forward, +Y is left, +Z is up
- local dx, dy = 1, 0
- local x, y, z = 0, 0, 0
- function env.turtle.gps()
- return x, y, z
- end
- function env.turtle.face(ndx, ndy)
- if ndx == -dx and ndy == -dy then
- env.turtle.turnLeft()
- env.turtle.turnLeft()
- elseif ndy == dx and ndx == -ndy then
- env.turtle.turnLeft()
- elseif ndy == -dx and ndx == ndy then
- env.turtle.turnRight()
- end
- end
- local gpshook = {
- [turtle.turnLeft] = function()
- dy, dx = dx, -dy
- end,
- [turtle.turnRight] = function()
- dy, dx = -dx, dy
- end,
- [turtle.forward] = function()
- x = x + dx
- y = y + dy
- end,
- [turtle.back] = function()
- x = x - dx
- y = y - dy
- end,
- [turtle.up] = function()
- z = z + 1
- end,
- [turtle.down] = function()
- z = z - 1
- end,
- }
- local function wrap(fn, rev)
- return function(...)
- table.insert(undolist, rev)
- local a = {fn(...)}
- if #a == 0 or a[1] then
- if gpshook[fn] then gpshook[fn]() end
- else
- table.remove(undolist,#undolist)
- end
- return unpack(a)
- end
- end
- local function pair(a, b)
- env.turtle[a] = wrap(turtle[a], turtle[b])
- env.turtle[b] = wrap(turtle[b], turtle[a])
- end
- pair("forward", "back")
- pair("up", "down")
- pair("turnLeft", "turnRight")
- pair("dig", "place")
- pair("digUp", "placeUp")
- pair("digDown", "placeDown")
- local args = {...}
- local noundo = (args[1] == "noundo")
- if noundo then table.remove(args, 1) end
- local prog = shell.resolveProgram(table.remove(args, 1))
- print("Beginning sandboxed execution")
- local ok, result = pcall(os.run, env, prog, unpack(args))
- print("Ended sandboxed execution")
- if not ok then print("Error: ",result) end
- if noundo then
- print("Not undoing ",#undolist," actions")
- else
- print("Undoing ",#undolist," actions")
- for k = #undolist,1,-1 do
- undolist[k]()
- end
- print("Undo complete")
- end
Advertisement
Add Comment
Please, Sign In to add comment