This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
stan2012's profile picture

[java] [error with lua script] java.lang.ArrayIndexOutOfBoundsException

Started by stan2012, 12 March 2012 - 02:18 PM
stan2012 #1
Posted 12 March 2012 - 03:18 PM
hi

i am making a automated tree farm with 2 turtle's
turtle 1 will chop down the tree when powerd with redstone from the back
turtle 2 will check if there is a tree and when there is a tree it will send out a redstone signal

but every time i run script(redstone_listner) on turtle 1 i get the error:
"java.lang.ArrayIndexOutOfBoundsException"

and on turtle 2's script(block_listner) i get the error:
"bios:15: vm error: java.lang.ArrayIndexOutOfBoundsException: 256

redstone_listner(turtle 1) script:
Spoiler
function rslistning()
if redstone.getInput("back")then
shell.run("tree")
rslistning()
else
rslistning()
end
end
rslistning()

block_listner(turtle 2) script
Spoiler
function listning()
if turtle.detect() == true then
redstone.setOutput("back", true)
sleep(2)
redstone.setOutput("back", false)
listning()
else
listning()
end
end
listning()

the script to chop the tree runs perfectly from the terminal

sorry for my bad english i am dutch
MysticT #2
Posted 12 March 2012 - 07:13 PM
The problem is that the functions are recursive and never end, so the stack is filling with function calls that you don't need.
There's two ways to fix it:
1- change the lines where the recursive calls are to something like return function(), so it makes a tail call and reuses the stack. It should look like this:

function someFunc()
    if a then
	    doSomeThing()
	    return someFunc()
    else
	    return someFunc()
    end
end
2- use a loop:

function someFunc()
    doSomething()
end

while true do
    someFunc()
end
I suggest using the loop, but if you want to use recursive functions for some reason, it works too :mellow:/>/>
stan2012 #3
Posted 13 March 2012 - 09:53 AM
so this script for turtle 2 will work?

function someFunc()
	if turtle.detect() == true then
		redstone.setOutput("back", true)
		sleep(2)
		redstone.setOutput("back", false)
end

while true do
	someFunc()
end
can't test it now becouse i am at school :mellow:/>/>
Hawk777 #4
Posted 14 March 2012 - 04:41 AM
You're missing an "end". You have one matched with the "function someFunc()" and one with the "while", but not one with the "if". Otherwise, this will work better, but now you have the problem that as long as turtle.detect() returns false, you will loop infinitely really fast, and your program will time out (I assume turtle.detect() doesn't delay); you probably want to sleep for a couple of seconds each time the loop iterates.