0.5.1:minor tweaks only; added "REQ" header identifying inventory as a requirement (which I needed for my own automatic api loader, which has not been released), and added a hackish version of transferTo. Proper version coming.
More importantly, releasing a utility program for use with turtlex, called inv. Run from the shell, inv displays the contents of the turtle's inventory as a menu. It provides a method of manually setting up the inventory type names without doing it by calling turtle.setItemType from lua. See below for info on using it and a pastebin link to the program.
—-
This is an api - well, a pair of them actually - I've been working on as part of a larger project. It replicates most of the functionality of the built-in turtle API, but adds code to most methods to provide position, direction, and inventory tracking.
Installation
You'll need both the inventory API and the turtlex APIs installed and loaded (os.loadAPI), and you'll want to load them in your startup file or at the start of the program that uses them. Inventory must be loaded first or turtlex will throw an error.
Usage
Spoiler
inventory creates and manipulates table objects that describe the contents of an inventory. By itself, you must call functions to explicitly tell it of any changes in the inventory. I plan on making it more robust, but for now it's mainly meant to be used internally by the turtlex api.turtlex has the same functions as turtle, but most have additional optional parameters. I'm going to make a single installer program you can download which will set up not only the APIs but also the in-game help files, but for now I'm just pasting them in the spoilers below.
Inventory
All functions which modify the inventory of the turtle will update the intenal tables, and if a new slot contains items, they will compare it to existing slots. Type names are assigned initially only by the calling code, using the turtlex.setItemType command, which gives the turtle a name for items in the slot. If setItemType is not called, all objects are assigned names beginning with "unknown," which are numbered to distinguish non-matching stacks - ex, if an empty turtle uses turtlex.dig and gets cobblestone in slot 1, it will name it "unknown." If it then digs some dirt, that will be named "unknown2." If it gets more cobblestone in a new slot, it will recognize it as the same as slot 1 and also call it "unknown." A single call to setItemType("cobblestone", 1) would rename both slot 1 and slot 3's items to "cobblestone".
Most of the basic functions that involve items (place, compare, drop, etc) have been modified to take an optional index parameter. By default they use the current slot, but you can pass as an index either a slot number and it will select and use that slot (re-selecting the previous selected slot before returning), or a type name. If a type name is given, it checks it's inventory for an item of that type and uses the first slot it finds that matches it. In either case if an invalid slot or type is given, it returns failure without taking action.
Movement
The movement commands are extended more. forward(), back(), up(), and down() all take an optional distance parameter - defaulting to one - and a second optional parameter telling it what to do if it hits something. This second parameter is a string and may be "stop", "return", or "dig". "stop" is the default, and does just that, it stops when it hits something. "return" attempts to return to the point where it started this move from, and "dig" will dig, repeatedly if necessary, until it either finds something undiggable or reaches it's destination. These have been tested quite a bit and are quite robust. As an example, if you give the command
turtlex.forward(20,"dig")
the turtle will repeatedly dig and move forward; if it encounters a stack of sand or gravel, it will detect the failures to move into the cleared space and dig again, so it will still correctly move 20 blocks forward regardless of how many times falling blocks get in the way. Additionally, for convenience, left() and right() functions are added, which turn to face the direction, call forward with the same params, and then turn back.
In addition to these enhanced basic commands, there are also move and goto commands for absolute and relative movement. These take x,y,z parameters and the same optional "onBlocked" parameter as the basic commands, so they can be told to dig, stop, or return. They do not pathfind, so are not guaranteed to find a path, but they do repeated application, so they can handle basic corners and things like stairs.
Lastly for movement is the position stack; you can call pushPos() to save the current position and direction to a stack, then popPos() causes the turtle to return to the last pushed position using goto(). This can be useful, for example, if digging a tunnel and you encounter a vein of ore; you can push the current position, call a separate function to follow and mine the vein, then pop the position back and resume executing your tunnel-digging routines.
help files
detailed info on all functions in the api and their parameters and return values. This is rather out of date, and omits many of the newer functions. Will get around to updating this eventually!
Spoiler
main help index:Spoiler
turtlexturtleX
Replaces the standard turtle API, adding position tracking, more advanced movement functions, and inventory monitoring.
functions:
basic movement - for more info, help turtlex.basic
forward back up down left right turnLeft turnRight turnAround
positional movement - for more info, help turtlex.move
move goto
position stack - for more info, help turtlex.stack
pushPos popPos topPos getPosStackSize getPosStackItem
compare commands - for more info, help turtlex.compare
compare compare compareUp compareDown compareLeft compareRight compareBack compareTo compareAll
drop commands - for more info, help turtlex.drop
drop dropUp dropDown dropLeft dropRight dropBack
suck commands - for more info, help turtlex.suck
suck suckUp suckDown suckLeft suckRight suckBack
dig commands - for more info, help turtlex.dig
dig digUp digDown digLeft digRight digBack
place commands - for more info, help turtlex.place
place placeUp placeDown placeLeft placeRight placeBack
inventory commands - for more info, help turtlex.inventory
getItemCount getItemType setItemType findItemSlot getSelected updateInventory
attack commands - for more info, help turtlex.attack
attack, attackUp, attackDown, attackLeft, attackRight, attackBack
turtlex.basic:
Spoiler
Basic Movement CommandsWith no parameters, these behave exactly like the standard turtle commands. Internally, they detect failure to move and update the turtle's position and direction.
forward([dist[, onBlocked]])
back([dist[, onBlocked]])
up([dist[, onBlocked]])
down([dist[, onBlocked]])
left([dist[, onBlocked]])
right([dist[, onBlocked]])
dist: number of blocks to move, default 1
onBlocked: what to do on failure, options: "stop", "return", "dig" defaults to "stop"
returns: success, trueDist
success: True if moved specified distance, otherwise false.
trueDist: Number of blocks actually moved from start. On success, always dist. If onBlocked was "return," returns 0 if successfully returned to start point, otherwise final distance from start.
The new commands left and right turn to face the specified direction, move forward, and then turn back to face the original direction. Always turns to face the original direction, regardless of the parameters or success of the move.
turnLeft()
turnRight()
turnAround()
Turns the turtle to face left, right, or backwards. Stored direction is updated.
turtlex.move:
Spoiler
Positional Movement Commandsmove(x,y,z[,onBlocked="stop"])
x,y,z : offsets from current position to move; ex, move(1,1,1) would move one block in each direction.
onBlocked: what to do when obstructed on all sides, "stop", "return", "dig", default "stop"
Moves the turtle to x, y, z relative to current position. Attempts to move x first, then y, then z. If any are obstructed, this order repeats until it reaches the target or is blocked in all three directions. onBlocked behavior occurs only when blocked in all three directions.
Returns true if successful, otherwise false.
goto(x,y,z[,onFail="true"])
same as move, but x,y,z are an absolute position rather than a relative one.
face(direction)
direction: direction to face. "north", "south", "east", or "west".
turtlex.compare
Spoiler
compare(index)compareUp(index)
compareDown(index)
compareBack(index)
compareLeft(index)
compareRight(index)
compareAll(index)
Index can be a slot number or an item type (string) to compare to. When passing an item, returns nil and an error message if a sample of the type is not in the turtle's inventory. If index is not specified, uses the block in the currently selected slot.
Left, Right, and Back versions turn first, compare forward, and then turn back to their original orientation.
compareAll compares all six surrounding positions to the sample and returns two values. The first return value is the number of matches found, the second is an array containing strings identifying the matching directions, "up","down","left","right","forward", or "back".
turtlex.dig:
Spoiler
dig([slot=currentSlot])digUp([slot=currentSlot])
digDown([slot=currentSlot])
digLeft([slot=currentSlot])
digRight([slot=currentSlot])
digBack([slot=currentSlot])
Digs to the specified slot or, if none is specified, the current slot. Note that, even if slot is specified, if the slot is full or contains a different kind of item, items may wind up in other slots!
Left, Right, and Back versions turn first, dig, and then turn back. Automatically calls updateInventory if any items are collected.
returns success, items
success is true if it was able to dig, otherwise false.
Items is an array of tables for each item dropped in the dig. Each element in the array has members "type" and "count"
turtlex.drop:
Spoiler
drop([quantity=all[,index=currentSlot]])dropUp([quantity=all[,index=currentSlot]])
dropDown([quantity=all[,index=currentSlot]])
dropLeft([quantity=all[,index=currentSlot]])
dropRight([quantity=all[,index=currentSlot]])
dropBack([quantity=all[,index=currentSlot]])
Drops up to quantity items (if unspecified or nil, the whole stack) from the specified slot. If provided, index can be a slot number or the name of an item type in the inventory.
Left, Right, and Back versions turn first, drop, and then turn back. Automatically calls updateInventory.
Returns true if it was able to drop any amount of the specified item, otherwise false.
turtlex.inventory:
Spoiler
select(slot)Selects the specified slot.
return: success, type
success: true if the slot was valid and is now selected, otherwise false.
err: if success was false, the second param is the error message, otherwise nil
getSelected()
Returns two values, the index of the currently selected slot followed by the type of item in that slot, or 0 if the slot is empty. Unidentified types are assigned names in the pattern "unknown#", with # assigned based on comparisons to currently unidentified types.
getItemType([slot=selected])
Returns the type of the item in the specified slot; if not specified, uses current slot.
getItemCount([slot=selected])
Returns the number of items in the specified slot or, if no parameters, the current slot.
setItemType(type[, slot=selected])
Sets the type name of an item in a given slot. Slot defaults to the current selected slot. If multiple
slots contain items with the same current type, all slots are updated to the new type.
getItemSpace([slot=selected])
Returns how many more items of the same type the current slot can hold. If empty, returns 64.
findItemType(type[, afterSlot])
Returns the index of the first slot containing an object of the specified type. If afterSlot is included, begins comparing to afterSlot+1.
updateInventory()
compares tracked inventory to actual turtle inventory. Counts for all items are updated. New items are compared to the existing inventory and assigned a type, or an unknown type if there are no matches.
turtlex.place:
Spoiler
place([index=currentSlot])placeUp([index=currentSlot])
placeDown([index=currentSlot])
placeLeft([index=currentSlot])
placeRight([index=currentSlot])
placeBack([index=currentSlot])
index can be a slot number or a type name. If it is a type name, first slot containing this type is used. If nil, defaults to the current slot.
Left, Right, and Back versions turn first, place, and then turn back. Automatically calls updateInventory.
returns true if it was able to place the specified item, otherwise false.
turtlex.attack:
Spoiler
attack([untilFalse=false])attackUp([untilFalse=false])
attackDown([untilFalse=false])
attackLeft([untilFalse=false])
attackRight([untilFalse=false])
attackBack([untilFalse=false])
Attacks. Left, back, and right versions turn first, then return to the starting position. If untilFalse is specified and true, attacks repeatedly until attack returns false.
returns true if attack returned true on the first call, followed by a table of any new items added to the inventory.
turtlex.stack:
Spoiler
pushPos()pushes the current position to the position stack
popPos([go=true])
pops the last position from the stack. Optional parameter go defaults to true. If go is true, immediately moves to the position.
getPosStackSize()
returns the size of the position stack
topPos()
returns the position on the top of the stack, but leaves position on the stack and doesn't move
getPosStackItem(n)
returns the position on the stack at place n. 0 is the oldest item on the stack, getPosStackSize() returns the index of the newest item.
clearPosStack()
Resets the position stack, removing all entries.
turtlex.suck():
Spoiler
suck([slot=currentSlot])suckUp([slot=currentSlot])
suckDown([slot=currentSlot])
suckLeft([slot=currentSlot])
suckRight([slot=currentSlot])
suckBack([slot=currentSlot])
Sucks to the specified slot or, if none is specified, the current slot. Note that, even if slot is specified, if the slot is full or contains a different kind of item, items may wind up in other slots. Left, Right, and Back versions turn first, suck, and then turn back. Automatically calls updateInventory if any items are collected.
Returns success, items
success is true if it was able to suck some items, otherwise false.
items is an array of tables for each item collected by the suck. Each element in the array has members "type", "slot", and "count"
Version History
Spoiler
inventory apiv0.1 - http://pastebin.com/yp00iTji
turtlex api - (inventory api must be loaded before loading turtlex!)
v0.5 http://pastebin.com/SYhqiJTk
v0.42 http://pastebin.com/YMqUDiv6
v0.41 http://pastebin.com/34VLLqeb
v0.4 - http://pastebin.com/ZEpCiYtD
v0.3 - http://pastebin.com/45xZc4jV
v0.2 - http://pastebin.com/9xS0JT3i
v0.1 - http://pastebin.com/vMGUKLHW
changelog
0.42
All variants of turtlex.drop() have been extended. When you specify a 2nd parameter as a type name to tell it what to drop, it will iterate over multiple slots containing that type if necessary to drop the requested quantity.
0.41
fixed a bug in the drop methods that caused dropUp and dropDown to drop forward instead.
0.4
new features
-Basic move functions (forward, back, left, right, up, and down) all now take an optional 3rd parameter, which is a function to be called after each successful step. If onFail is "return," and it hits an obstacle, it does not call the function each step on the way back.
-place() can now take a parameter to set the text when placing a sign in addition to the index parameter that specifies what to place. Parameters can be in any order, to both maintain compatibility with earlier versions of turtlex and improve compatibility with the standard turtle api. Note: it attempts to match the first parameter as an index first, then if that fails, the second; the result is, if you're placing a sign with text and that text matches exactly the name of an item in the turtle's inventory, you MUST specify both parameters, and the index must be first. If you want to use the item in the selected slot rather than specify another slot or type, you can just pass nil as the first parameter, though. Should only come up in rare cases.
bug fixes:
-fixed bug with gps that caused it to attempt to get position even after failing in locate() call. Also made it check for presence of a modem first, so if no modem is attached you don't have to wait for it to fail on loading the API.
-tweaked sevaral functions to behave more like their standard turtle counterparts - drop works without a parameter to drop all, refuel with no params uses all fuel in current slot instead of just one, etc
0.3
new features
setMonitorId(id) - specifies a computer ID to send position update notices to. Is saved and reloaded on restart. Currently there's no special monitoring program.
attackXXX([untilFalse=false])
available in all 6 directions like the other turtlex commands - attack, attackDown, attackLeft, attackBack, etc. Attacks in the direction. The parameter is optional; if true, it causes the turtle to attack repeatedly in a loop until attack returns false. For automated farms, this will cause it to attack until all mobs are dead. When repeating, returns true if attack returned true at least once, otherwise false. Updates inventory only if attack returned true, and only once in calls where untilFalse==true.
place functions now take an index rather than a slot, so, for example, if you are carrying known dirt you can call turtlex.place("dirt")
setPosition(x,y,z) - sets the turtle's internal position value to (x,y,z)
setDirection(dir) - sets the turtle's facing direction. dir can be one of turtlex's numeric direction values - 0==north, 1==east, 2==south, 3==west - or a string matching "east", "west", "north", or "south". The strings are not case-sensitive, and can be abbreviated, i.e. setDirection("E") would set the direction to east.
bug fixes:
-forward() and certain other basic functions no longer throw an error if called with no parameters
-drop() correctly takes an index (slot or type) instead of just a slot as optional 2nd parameter
Utility programs
inv
inv displays the inventory of the turtle and allows changing the item type names. The controls are displayed on-screen, but for reference:
arrow keys - move the selection around in the inventory.
enter - edit the name of the current item. Enter again saves the new name. Entering a blank line will cancel the edit.
space - forces an update of the inventory, useful when you have added, removed, or transfered items in the turtle's inventory while running inv.
tab - exits to the shell
Download
inventory API - http://pastebin.com/yp00iTji
turtlex API - http://pastebin.com/SYhqiJTk
inv (utility program) - http://pastebin.com/BTTRKswG
go http://pastebin.com/EpLB5vrH replacement for standard go command, identical except uses turtlex, so that your turtle doesn't lose track of it's position when caled.
Sample installation process
Spoiler
This is just a suggestion for those who don't know how to load APIs. If you do, feel free to ignore them, though note that inventory must be loaded first, and must be named inventory. If inventory is renamed, turtlex must be modified to refer to the new name instead of inventory.In the shell, type the following commands:
> mkdir turtlex
> mkdir turtlex/apis
> pastebin get yp00iTji turtlex/apis/inventory
> pastebin get SYhqiJTk turtlex/apis/turtlex
> pastebin get BTTRKswG turtlex/inv
pastebin get EpLB5vrH turtlex/go
Add these lines to the top of your startup file.
--load the inventory and turtlex apis - order matters here!
os.loadAPI("turtlex/apis/inventory")
os.loadAPI("turtlex/apis/turtlex")
--add the turtlex directory to your path, so you can run inv and go directly
--added to the start of the path, so turtlex/go is found before rom/programs/turtle/go
shell.setPath("turtlex:"..shell.path())
If you don't want the apis loaded on startup, you can add the os.loadAPI commands to the top of your program instead, but you will not be able to run the inv or go programs.