How To Craft

How to call a function in computer craft

  1. Home
  2. Events Calendar
  3. How to call a function in computer craft
How to call a function in computer craft
October 30, 2019 Events Calendar 1 comment

Last night I played around with Tekkit and the Mining Turtle which comes with it. The Turtle is part of the ComputerCraft mod and can be programmed using Lua and the Turtle API.

For fun I wanted to level an area, and I specifically wanted to fill in annoying holes and messy open caves. I decided to divide this into separate problems. First is having the turtle cover a rectangular area. Second is to fill in the holes below each block in the area.

I decided to create a function which takes a Lua table like the following:

{
  size ={X=x, Y=y},
  forward =function,
  left =function,
  right =function,
  callback =function,
}

The size is the width and length of the area. Forward, left and right are for moving the turtle and callback is the function to call for each point in the rectangle. This way the function is decoupled from turtle specifics and what I actually want to do.

Move in a rectangle

Struggled embarrassingly long with this (so seems this was a useful exercise for my programming brain), but figured it out in the end 😛

-- Helper function for looping over a range
function range(limit)
    localfunction seq(state, x)
        if(x >= limit)then
            returnnil
        else
            return x +1
        end
    end
    return seq,nil,0
end
-- The magic function
function moveSpiral(w)
    local X,Y = w.size.x,w.size.y

    -- Prepare for first row
    w.forward()
    w.right()

    -- Loop over each row
    for y in range(Y)do
        -- Loop over each column
        for x in range(X)do
            -- Do the callback for each point
            w.callback()

            -- Unless we have completed the row
            if x ~= X then
                -- Move forward
                w.forward()
            end
        end
       
        -- Unless we have completed all rows
        if y ~= Y then
            -- Move to next row
            if y%2==1then
                w.left()
                w.forward()
                w.left()
            else
                w.right()
                w.forward()
                w.right()
            end
        end
    end

    -- Move back to starting point
    if Y%2==1then
        w.left()
        w.left()
        for x in range(X-1)do w.forward()end
    end
    w.left()
    for y in range(Y)do w.forward()end
    w.right()
    w.right()
end

Please let me know if you have a better way to do it. Either way, now the callbacks handed to this function.

Moving the turtle

As you saw, the function requires three callbacks for moving. For turning left and right we can just use the turtle API directly. However, since I wanted to level an area, we need to do some digging if we hit any obstructions.

function forward()
    whilenot turtle.forward()do
        sleep(0.5)
        turtle.dig()
    end
end

This function will keep trying to move forward and whenever it fails it will wait for a short while and then try to dig in front of itself. This will usually only run once, but if you’re standing in its way it will keep trying until you move. This way you being in the way won’t mess it up 🙂

Filling the hole

First of all I wanted to fill up whatever hole is below me. I also wanted to replace dirt with stone and have a single layer of dirt on top. This is what I ended up with.

-- Fill hole
function fill()
    -- How far down we have gone
    local depth =0

    -- Make sure we have an empty slot for picking up junk
    -- This is an attempt to not mess up the convention by
    -- the blocks we dig that are picked up. Not 100%
    -- reliable still...
    turtle.select(9)
    turtle.drop()

    -- Move down to first block we can find
    whilenot turtle.detectDown()and turtle.down()do
        depth = depth +1
    end

    -- Remove top block
    turtle.digDown()
    turtle.down()
    depth = depth +1

    -- Dig down to first non-dirt block we can find
    turtle.select(1)
    while(turtle.compareDown()and turtle.digDown()and turtle.down())or turtle.down()do
        depth = depth +1
    end

    -- Start filling
    while depth >0do
        -- Until we move up 1 successfully
        whilenot turtle.up()do
            -- Try dig upwards and wait a bit
            turtle.digUp()
            sleep(0.5)
        end
        depth = depth -1
       
        -- As long as we have something to place
        if selectSource(depth)>0then
            -- Place it below us
            turtle.placeDown()
        end
    end
end

-- Returns the count of an appropriate slot
function selectSource(depth)
    -- If we're at the top
    if depth==1then
        -- Select slot 1 and return its count
        turtle.select(1)
        return turtle.getItemCount(1)
    -- Otherwise
    else
        -- Move through the rest of the slots
        for i=2,9do
            turtle.select(i)
            local count = turtle.getItemCount(i)
            -- Until we find one with something in it
            if count >0then
                return count
            end
        end
    end
    return0
end

Works pretty well, but any advice on improvements are more than welcome 🙂

Running it

Create a file on a Mining Turtle called for example “fill” and add the above functions together with the following snippet of code:

local arg ={...}
if#arg ==2then
    moveSpiral({
        size ={
            x =tonumber(arg[1]),
            y =tonumber(arg[2]),
            },
        forward = forward,
        left = turtle.turnLeft,
        right = turtle.turnRight,
        callback = fill,
    })
else
    print("Usage: fill x y")
end

You should now be able to level an area by running the program on the Mining Turtle like this:

> fill 10 15

It should then go ahead and level a 10 x 15 block area 🙂

ComputerCraftGamesLuaMineCraftRobotTurtle

Including Lua Code

To format your code for inclusion in a post, please wrap it in [lua][/lua] tags and we'll make it look all pretty for you.

[lua]--this is a comment[/lua]

Including A Gist

[gist]https://gist.github.com/walterlua/3937293[/gist] or [gist]3937293[/gist]

External Images / URLs / Email Addresses

An image: [img]https://www.google.com/intl/en_ALL/images/logo.gif[/img]

A link: [url=https://www.CoronaLabs.com/blog/]Corona Labs Blog[/url]

A 'mailto:' link: Send support requests to [email][email protected][/email]

YouTube and Other Media

You can link to many popular third party media sites (like YouTube) by wrapping the link in [media][/media] tags.

Watch my YouTube video: [media]https://www.youtube.com/watch?v=CiPuo5fIuZ0[/media]

Twitter

Here is a link to my username: [twitter]CoronaLabs[/twitter]

Here is an embedded tweet: [tweet]https://twitter.com/CoronaLabs/status/310555907283107840[/tweet]

Corona Labs Specific Tags

[docsLink] Will create a link to the documentation.
[bugLink] Will create a link to our bug reporting tool.
[supportLink] Will create a link to our support form.

A function is a piece of code that can be called over again after it's been made. Let's say you want something to execute another piece of code if it's true.

FUNCTION REFERENCE

In this reference, you’ll find short descriptions of every function used in this book. The functions are grouped by application programming interface (API), also known as a module. This reference is not a complete list of all the functions in ComputerCraft, but you can read about other available functions in the documentation that ComputerCraft provides at http://computercraft.info/wiki/Category:APIs.

If you want to learn more about Lua, you can use the Lua 5.1 Reference Manual, which is available online at https://www.lua.org/manual/5.1/. Note that ComputerCraft uses Lua 5.1, even though newer versions of Lua are available.

NOTE

Some functions in this reference include italicized terms that indicate where parameters would go and what the data types of those parameters would be.

FS (FILE SYSTEM) API

Turtles and in-game Minecraft computers have file systems similar to those your computer has. You can interact with these files using the fs API and the file’s name:

fs.delete(string filename) Deletes a file named filename

fs.exists(string filename) Returns true if a file named filename exists; otherwise returns false

NOTE

The programs you write in this book can interact with the files loaded on a turtle or in-game computer but not with the files on the computer that is running Minecraft.

HARE API

You wrote the hare API while reading this book. Unlike the other APIs listed in this reference, hare doesn’t come with ComputerCraft, so you must first run pastebin get wwzvaKuW hare from the CLI shell to download it. Each program you write that uses the hare API must include the code os.loadAPI('hare') in order for the program to call the hare module’s functions:

hare.buildFloor(number length,number width) Builds a floor length blocks long and width blocks wide using items in the turtle’s inventory.

hare.buildRoom(number length,number width,number height) Builds a room length blocks long, width blocks wide, and height blocks tall using items in the turtle’s inventory.

hare.buildWall(number length,number height) Builds a wall length blocks long and height blocks tall using items in the turtle’s inventory.

hare.countInventory() Returns the total number of items in all the turtle’s inventory slots.

hare.digUntilClear() Continues to mine the space in front of the turtle until the space contains no blocks. You use this function when gravel or sand could fall in front of the turtle as it mines the block in front of it.

hare.digUpUntilClear() Similar to hare.digUntilClear() except it clears the space above the turtle.

hare.findBlock(string name) Spins the turtle around and stops if the turtle is facing a block named name. If the turtle can’t find the block, the turtle ends up facing its original direction after the function code finishes running. Returns true if the block was found; otherwise returns false.

hare.selectAndPlaceDown() Selects a nonempty inventory slot and places the item in that slot beneath the turtle.

hare.selectEmptySlot() Selects an empty inventory slot. Returns true if a slot is found; otherwise returns false.

hare.selectItem(string name) Selects an inventory slot containing an item named name. Returns true if the item is found; otherwise returns false.

hare.sweepField(number length,number width,function sweepFunc) Moves the turtle over every space in a rectangular field length blocks long and width blocks wide, calling sweepFunc at each space.

IO (INPUT/OUTPUT) API

When you use the io API, programs can display text on the screen and also accept text from the player via the keyboard. There are several functions in the io API, but the most important function to know is io.read():

io.read() When the player types a response and presses ENTER, this function returns the response as a string value.

MATH API

The math API is part of Lua, and you can call its functions from non-ComputerCraft Lua programs. This API includes the following number and mathematics-related functions:

math.ceil(number num) Returns num rounded up.

math.floor(number num) Returns num rounded down.

math.random(number start,number end) Returns a random whole number between start and end, including start and end. The start and end arguments are optional. If no arguments are passed, the function returns a decimal point number between 0.0 and 1.0. If the start argument is not used, the function returns an integer between 1 and end.

OS (OPERATING SYSTEM) API

The ComputerCraft operating system provides the following functions, which are useable by turtles and in-game computers:

os.getComputerLabel() Returns a string of the turtle’s label (that is, its name).

os.loadAPI(string filename) Loads the program named filename as a module so the current program can call its functions.

os.setComputerLabel(string/nil label) Sets the turtle’s label to label. If label is nil, the function erases the turtle’s label.

os.sleep(number time) Pauses the program for time number of seconds.

SHELL API

Turtles can run commands from the CLI the same way the player can run commands from the CLI. You can run a CLI command in a turtle program using the shell API:

shell.run(string command) Runs command as though the player entered the string at the CLI shell. Returns false if the command terminates because the command doesn’t exist, crashes, or calls error(); otherwise returns true.

STRING API

The string API is part of Lua, and you can call its functions from non-ComputerCraft Lua programs. Although these functions weren’t featured in this book, I’ve included them here because they’re useful:

string.find(string haystack,string needle) Looks for the needle string inside the haystack string and returns two integers: the position where the needle string was found and where this string ends. For example, string.find('hello', 'el') returns 2 and 3, because 'el' is found at the second character in 'hello' and ends at the third character. If the needle string is not in the haystack string, the function returns nil. The needle string can also find text patterns, which are outside the scope of this book. You can learn more about text patterns at https://www.lua.org/manual/5.1/manual.html#5.4.1/.

string.sub(string bigstring,number start,number length) Returns a substring, or portion, of bigstring, starting at the start position and returning the next length characters. The length argument is optional. If length is not passed, the substring starts at start and continues to the end of bigstring. For example, string.sub('hello', 3, 2) returns 'll' and string.sub('hello', 2) returns 'ello'.

TEXTUTILS API

Using textutils, you can make programs display text one character at a time to create a fancy typewriter effect:

textutils.slowPrint(string text,number rate) Similar to print() except it writes the characters in text one character at a time. The rate argument is optional and specifies how many characters are printed per second.

TURTLE API

The turtle API holds all the common functions that your programs could call to make a turtle perform some action. Let’s look at these functions in batches based on the actions the functions can trigger.

BUILDING FUNCTIONS

You can call functions to make turtles build by placing blocks. But the same function can also cause the turtle to perform other actions, depending on the item in the turtle’s current slot:

turtle.place() Performs an action with the item in the turtle’s current slot. For building blocks, this function places the block in the Minecraft world. However, if one of the special items listed in Table 1 is in the current slot, that item will be used in the way specified by Table 1. The function returns false if the turtle is unable to place the block or perform an action on the block.

turtle.placeDown() Similar to turtle.place() but performs the action on the space below the turtle.

turtle.placeUp() Similar to turtle.place() but performs the action on the space above the turtle.

Table 1: Special Items That the place Functions Can Use

Item

Action

Armor

Sets the armor on an armor stand.

Boats

Places the boat on water.

Dyes

Dyes a sheep.

Empty bucket

Collects lava or water. Can also collect milk from a cow.

Fireworks

Launches the fireworks.

Flint and steel

Sets fire to a flammable block or activates a Nether portal.

Minecarts

Places the minecart on tracks.

Saplings, flowers, or seeds

Plants the object in a dirt or grass block.

Shears

Shears a sheep and collects its wool.

Sign

Places a sign with text on it. To write text on the sign, pass the turtle function a string. For example, turtle.place('This\nis a\nsign.').

Spawn eggs

Spawns a mob.

FUELING FUNCTIONS

Turtles use one unit of fuel each time they move, but they can’t move if they run out of fuel. For this reason, refueling the turtle and understanding its fueling functions are important:

turtle.getFuelLevel() Returns the amount of fuel the turtle currently has stored. Returns 'unlimited' if the ComputerCraft.cfg config file has disabled the fuel requirement.

turtle.getFuelLimit() Returns the maximum amount of fuel the turtle can store. For most turtles, the limit is 20,000 units; for other types of turtles, the limit is 100,000 units. Returns 'unlimited' if the ComputerCraft.cfg config file has disabled the fuel requirements.

turtle.refuel(number amount) Consumes amount of fuel items in the current slot. The amount argument is optional. If amount is not given, the function consumes all the items in the current slot by default.

INVENTORY FUNCTIONS

Each turtle has an inventory with 16 numbered slots. You can use various inventory functions to make the turtle perform actions on its inventory. These functions often take a number to indicate which of the numbered slots to perform an action on.

turtle.compareTo(number slot) Returns true if the item in the current slot is the same as the item in slot; otherwise returns false.

turtle.drop(number amount) Drops amount items from the current slot into the space or container in front of the turtle. The amount argument is optional. If amount isn’t given, the function drops all the items in the current slot. Returns true if any items were dropped; otherwise returns false.

turtle.dropDown(number amount) Similar to turtle.drop() except this function drops items into the space or container below the turtle.

turtle.dropUp(number amount) Similar to turtle.drop() except this function drops items into the space or container above the turtle.

turtle.equipLeft() Unequips the tool, if any, on the turtle’s left side and equips the tool in the current slot. Returns true if equipped; otherwise returns false.

turtle.equipRight() Unequips the tool, if any, on the turtle’s right side and equips the tool in the current slot. Returns true if equipped; otherwise returns false.

turtle.getItemCount(number slot) Returns the number of items in slot. Uses the current slot if slot isn’t given.

turtle.getItemDetail(number slot) Returns a table value of information about the item in slot or returns nil if the slot is empty. Uses the current slot if slot isn’t given.

turtle.getItemSpace(number slot) Returns the amount of free space in slot. Uses the current slot if slot isn’t given.

turtle.getSelectedSlot() Returns the slot number (1 to 16) of the current slot.

turtle.select(number slot) Changes the current slot to slot, a number from 1 to 16.

turtle.suck(number amount) Takes amount items from the space or container in front of the turtle, sucking them up like a vacuum cleaner, and places them in either the current slot (if empty) or the first available empty slot. The amount argument is optional. If amount isn’t given, a full stack of items is taken. (A full stack is 64 for most items, although some items like eggs, snowballs, or empty buckets can only stack up to 16.) Returns true if any items were taken; otherwise returns false.

turtle.suckDown(number amount) Like turtle.suck() except this function takes items from the space or container below the turtle.

turtle.suckUp(number amount) Like turtle.suck() except this function takes items from the space or container above the turtle.

turtle.transferTo(number slot,number amount) Transfers amount items from the current slot to slot. The amount argument is optional. If amount isn’t given, the function attempts to transfer all items in the current slot to slot. Returns true if any items were transferred; otherwise returns false.

MOVEMENT FUNCTIONS

Turtles can move in any direction as long as the space they’re attempting to move to is not already occupied by another block. You can use the following functions to tell a turtle to move in various directions. All movement functions return true if the turtle was able to move; otherwise, they return false:

turtle.back() Moves the turtle backward one space

turtle.down() Moves the turtle down one space

turtle.forward() Moves the turtle forward one space

turtle.turnLeft() Turns the turtle to the left; doesn’t use fuel

turtle.turnRight() Turns the turtle to the right; doesn’t use fuel

turtle.up() Moves the turtle up one space

PERCEPTION FUNCTIONS

Turtles can examine blocks one space in front of, above, or below them using the following functions:

turtle.compare() Returns true if the block in front of the turtle is of the same type as the block in the current slot; otherwise returns false.

turtle.compareDown() Similar to turtle.compare() but compares the block below the turtle to the item in the current slot.

turtle.compareUp() Similar to turtle.compare() but compares the block above the turtle to the item in the current slot.

turtle.detect() Returns true if a block is in front of the turtle; otherwise returns false.

turtle.detectDown() Similar to turtle.detect() but checks the block below the turtle.

turtle.detectUp() Similar to turtle.detect() but checks the block above the turtle.

turtle.inspect() Returns two values: true and a table value with information about the block in front of the turtle. If no block is in front of the turtle, returns false.

turtle.inspectDown() Similar to turtle.inspect() but returns information about the block below the turtle.

turtle.inspectUp() Similar to turtle.inspect() but returns information about the block above the turtle.

TOOL-RELATED FUNCTIONS

Turtles can perform actions with the tools they have equipped, and there are corresponding tool-related functions for each action the turtle can perform. You can equip turtles with diamond pickaxes, shovels, axes, swords, hoes, and crafting benches to make the following functions available:

turtle.attack() If equipped with a sword, the turtle attacks anything in front of the turtle. Returns true if a mob was attacked; otherwise returns false if nothing was attacked.

turtle.attackDown() Similar to turtle.attack() but the turtle attacks the space below it.

turtle.attackUp() Similar to turtle.attack() but the turtle attacks the space above it.

turtle.craft(number amount) When you lay out items for a recipe in the turtle’s inventory, this function crafts amount number of items and puts them in the current slot. Requires the turtle to equip a crafting table. The amount argument is optional. If amount isn’t given, the function will craft as many items as possible. Returns true if something was crafted; otherwise returns false when no recipe matches the laid-out items.

turtle.dig() Mines or tills the block in front of the turtle. The turtle must be equipped with a pickaxe for this function to mine blocks. If the turtle has equipped a hoe, the function tills the block in front of the turtle. Returns true if something was mined or hoed; otherwise returns false.

turtle.digDown() Similar to turtle.dig() but mines or tills the block below the turtle.

turtle.digUp() Similar to turtle.dig() but mines the block above the turtle. Note that this function cannot till dirt blocks.

LUA FUNCTIONS

The following functions come with the Lua language, so you don’t need to type a module name before the function name when calling these functions:

error(string message) Terminates the program and displays message, if given. The message argument is optional.

exit() Exits the interactive shell. You can use this only while in the interactive shell.

print(string/number value) Displays value on the screen, followed by a newline. The value argument is optional. If no value is passed, the function only displays a newline.

Calling function from another function in an API

how to call a function in computer craft

how to inventory craft items multiple consignment
How to make craft birds
how to decorate an arts and crafts home
How to sponsor a craft fair
how to craft a blade of grass in terraria xbox
How to craft northshire cleric
how to make craft penguins
Survival craft how to make weapons in the wild
This article is in need of a clean-up. You can help the wiki by cleaning up the article.

Lua is a computer programming language used by ComputerCraft.

Getting Started[edit]

This is a guide which attempts to impart the basics of programming to someone who is not familiar with programming languages or used a ComputerCraftTurtle. The first thing you need to know when programming in ComputerCraft is how to use the text interface in a Turtle.

The Turtle's text interface is accessed by right-clicking on a Turtle that is placed in the world. A GUI will appear that greets the player with the message, "TurtleOS 1.4" followed by an angle bracket and a blinking cursor. This is the text interface with which you will be working with and this particular screen is known as the "command line".

Running a Program: To run a program, type the name of the program you want to run and any input the program will need (if any) separated by a single space. For example, typing "tunnel 100" will make a Mining Turtle dig a 2 high by 3 wide by 100 long tunnel.

Creating a program: To create a program of your own, type "edit <program>", where <program> is the name of the program you wish to create (example: "edit turnAround"). It's important to note that the program name cannot contain any spaces. If we tried to use a space in our example and typed "edit turn around", we would end up with a program named "turn".

The name of a program must be a single string of characters. Multiple words may be placed together if needed but it is suggested that the first letter of each subsequent word be capitalized. This is commonly called camel-case notation in programming as the capital letters look like the humps on the back of a camel.

Save your program: To save your program you will need to make a disk drive and a floppy disk. Place your disk drive next to your computer, and put in your floppy. Then type "copy <program> disk" where <program> is the name of the program you wish to save.

Access a program on a floppy disk: To access a program on a disk you will need to first change the directory you are in to the disk directory. To do so type "cd disk". Now all you have to do is type the name of your program and any inputs it needs. Alternatively, you can type "disk/<program>", where <program> is the name of the program in the disk directory.

First Program[edit]

The most basic program you can create with a computer is known as the Hello world program. This program makes the Turtle speak in the screen "Hello, world".

For now we will create a program which does something slightly more useful. This program will make a Mining Turtle branch mine for you.

First type "edit mine" to create a new program titled "mine". You will now see a blank window where we will type our program. Pressing the control key allows you to access the menu which lets you save, exit, or print. Use your arrow keys to change which option you have selected and enter to do that option. For now, just press the control key again to close the menu.

Using The Turtle API[edit]

To make your turtle do something you will need to call a function from its API (Application Programming Interface). A function is basically a bit of code which can be run multiple times. I will get into more about how to make one later, but for now that is all you need to know.

The first thing you will want your turtle to do as it starts mining is to dig the block in front of it. To make it do this, type "turtle.dig()" (without the quotes) and then press enter. The Turtle won't actually mine the block in front of it right now as we are writing the program, not running it.

We also want to have the turtle dig above and below it. Type "turtle.digUp()" and press enter, then type "turtle.digDown()" and press enter.

Next we will want our turtle to move forward. To make your turtle move forward, type "turtle.forward()".

At this point your code should look like this:

turtle.dig()turtle.digUp()turtle.digDown()turtle.forward()

It is important that your code has the same capitalization as what is written above. Ensure that your code matches the above text exactly before before proceeding.

Now, save your program by pressing the control key, navigating to the save button on the menu with the arrow keys, and then pressing enter. You should see a message at the bottom which says "Saved to mine". Your program is now saved to the Turtle.

To run our program, we will need to exit the editor and get back to the command line. To do this, press the control key to access the menu again but this time navigate to the exit button and press enter.

Now that we're back at the command line you may type the name of our program and press enter to run it. Simply type "mine" and your turtle will dig in front, above, and below itself before moving forward one block.

Conditional Statements[edit]

As we have it right now, the turtle may waste a lot of time, since it digs without checking if there is something to dig. To make the turtle check to see if there's a block in-front of it, you will need to use an if statement.

The syntax for an if statement is as follows:

if[condition]then[codetorunwhentheconditionistrue]end

For our program, edit mine add an if statement using the turtle.detect() function in the condition. your code should look like this:

ifturtle.detect()thenturtle.dig()turtle.forward()end

We should do the same to check if there is a block above using turtle.detectUp() and bellow with turtle.detectDown()

After you add these if statements our code should look like this:

ifturtle.detect()thenturtle.dig()endifturtle.detectUp()thenturtle.digUp()endifturtle.detectDown()thenturtle.digDown()endturtle.forward()

Variables[edit]

Before we talk about the loops, we should spend a moment to learn about variables. A variable stores information specified by the programmer. This information may be a numeric value, a Boolean value (true or false) or a string (a collection) of characters (letters, numbers, symbols). A variable is declared(when you tell the computer that it exists, its name, and value) using this syntax:


[a single word name that starts with a letter] = [the value or contents of variable]


For example if we wanted a variable to hold the value of how far we want our turtle to dig, we would make a variable like this:

It is usually helpful for variables to be placed at the top of your code, unless they are temporary. A temporary variable (known as local) only exists within the body of a specific element of code. For instance, if you made your variable in an if statement, it probably would not be defined after the end.

You should now add "length = 100" above your code in mine, so that it looks like this:

length=100ifturtle.detect()thenturtle.dig()endifturtle.detectUp()thenturtle.digUp()endifturtle.detectDown()thenturtle.digDown()endturtle.forward()

Loops[edit]

Our turtle can now dig a block in front of it, if there is one, and then move forward once, but as it is we would have to rewrite those two commands over and over to get it to repeat. Instead of doing this we can use a loop to have the computer repeat those lines of code as many times as we need.There are at least two kinds of loops in Lua. We want the turtle to move and mine a predefined number of times ahead so we want to use a counting loop, which is known as a for loop.

A for loop's syntax is as follows:

for[variable]=[numericvalue],[endvalue],[valuetocountby]do[codetoloop]end

For our for loop, we will want to have it start at 1 and end at length. The following is an example of how to do this:

fori=1,length,1do[codetorepeat]end

This loop will first check to see if the counter is equal to the end value, and if it is not then it adds one and does whatever is within the body of the loop(between the do and end)

At this point your code should look something like this:

length=100fori=1,length,1doifturtle.detect()thenturtle.dig()endifturtle.detectUp()thenturtle.digUp()endifturtle.detectDown()thenturtle.digDown()endturtle.forward()end


When we run the program as is, you will find that there is a problem which will make the end result unpredictable. If the turtle runs into falling sand or gravel, its likely that it will cause the turtle to behave in a way we don't want, because the tunnel will be shorter than we planned. To account for this we can replace the if conditions with another kind of loop, so that before moving ahead the turtle will check if there is a new obstacle.

This loop is called a while loop. This is a while loops syntax:

while[conditionstatement]do[codetoloop]end

For an example of how we can use a while loop , we can replace the if condition in our program with a while loop. We will also want to make the turtle wait a second after digging to account for the time it takes for a block to fall. To do so we use the sleep(1) function.

Your while loop should look like this:

whileturtle.detect()doturtle.dig()sleep(1)end


You should go ahead and also replace the if condition for checking if there is a block above the turtle with a while loop, but it is not necessary to do so with the down.

Functions[edit]

So far, we have used a few different functions in our code without really knowing what they are. A function is a segment of code which you can call from somewhere else in our program as many times as you want. The following is the syntax for a function:

function[nameoffunctioninasingleword]()[functionscode]end

Using functions in your code has a few benefits. The first is that you can make a more complicated action then easily repeat it.

In our program we will create a function called dig, which will allow you to perform the dig forward, dig up, and dig down from our current code by calling the function instead of repeating all that code.

External Links[edit]

I want to call a function via: event, button, x, y = cnmcblog.coment("mouse_click") different values of y represent different functions. the f.

calling a function within a function defined by an argument

This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.


8.4 – Error Handling and Exceptions

For many applications, you do not need to do any error handling in Lua. Usually, the application program does this handling. All Lua activities start from a call by the application, usually asking Lua to run a chunk. If there is any error, this call returns an error code and the application can take appropriate actions. In the case of the stand-alone interpreter, its main loop just prints the error message and continues showing the prompt and running the commands.

If you need to handle errors in Lua, you should use the function (protected call) to encapsulate your code.

Suppose you want to run a piece of Lua code and to catch any error raised while running that code. Your first step is to encapsulate that piece of code in a function; let us call it :

function foo () ... if unexpected_condition then error() end ... print(a[i]) -- potential error: `a' may not be a table ... end Then, you call with : if pcall(foo) then -- no errors while running `foo' ... else -- `foo' raised an error: take appropriate actions ... end Of course, you can call with an anonymous function: if pcall(function () ... end) then ... else ...

The function calls its first argument in protected mode, so that it catches any errors while the function is running. If there are no errors, returns true, plus any values returned by the call. Otherwise, it returns false, plus the error message.

Despite its name, the error message does not have to be a string. Any Lua value that you pass to will be returned by :

local status, err = pcall(function () error({code=121}) end) print(err.code) --> 121 These mechanisms provide all we need to do exception handling in Lua. We throw an exception with and catch it with . The error message identifies the kind or error.
Copyright © 2003–2004 Roberto Ierusalimschy. All rights reserved.

how to call a function in computer craft

This reference is not a complete list of all the functions in ComputerCraft, but you loadAPI('hare') in order for the program to call the hare module's functions.

how to call a function in computer craft
Written by Kigalkis
1 Comment
  • Maugul

    MaugulNovember 06, 2019 1:08 AM

    On your place I would address for the help in search engines.

Write a comment