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

java.lang.ArrayIndexOutOfBoundsException: 256

Started by X3ME, 12 November 2016 - 06:14 PM
X3ME #1
Posted 12 November 2016 - 07:14 PM
Hey guys, I made a quick program in 10 minutes. It works for a good time until eventually it gets this error:

"bios:139: vm error:
java.lang.ArrayIndexOutOfBoundsException :256"

Here is the pastebin: http://pastebin.com/VPt847nS

any help would be greatly appreciated!
KingofGamesYami #2
Posted 12 November 2016 - 07:21 PM
Looks like you're using recursion. Stop using recursion.

countdown calls itself repeatedly. Use a loop instead.

countdown calls disaster. disaster calls countdown. Use a loop instead.

display calls itself repeatedly. Use a loop instead.

terminal calls itself repeatedly. Use a loop instead.
jakejakey #3
Posted 12 November 2016 - 08:21 PM
What I understand is that this is a countdown program that sounds an alarm through a redstone port after a certain amount of time?
Bomb Bloke #4
Posted 12 November 2016 - 11:47 PM
To be more specific, when a function calls a function, the first isn't necessarily removed from the function stack - it usually stays there, so that when the second function finishes (and returns), the first can carry on from where it left off. The idea is that whatever function is on top of the stack is active - new functions get piled on top, and as they complete, they get removed.

If you never allow your functions to return, but instead have them continue to call fresh instances of themselves over and over again, eventually Lua runs out of the memory reserved for such shenanigans and the function stack overflows. In the case of LuaJ (used by ComputerCraft), this leads to the precise error you're getting.

For eg, this sort of thing:

Spoiler
function display()
  while disasterstatus == false do
    p = peripheral.wrap("top")
    p.clear()
    p.setCursorPos(1,1)
    p.setTextColor(colors.green)
    p.write(counttime)
    sleep(1)
    display()
  end
  if disasterstatus == true then
    p.clear()
    p.setCursorPos(1,1)
    p.setTextColor(colors.red)
    p.write("SYSTEM FAILURE")
    sleep(2)
    display()
  end
end

… could be re-written like this:

Spoiler
local function display()
	local p = peripheral.wrap("top")

	while true do
		p.clear()
		p.setCursorPos(1,1)

		if not disasterstatus then
			p.setTextColor(colors.green)
			p.write(counttime)
			sleep(1)
		else
			p.setTextColor(colors.red)
			p.write("SYSTEM FAILURE")
			sleep(2)
		end
	end
end
X3ME #5
Posted 12 November 2016 - 11:51 PM
Thanks guys! I have read up a bit more on this exact error and why it was occuring to me. Didn't know the function / memory usage worked this way, glad I got to learn before making this mistake again! Thanks once again!