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

" IF , WHILE " problem.

Started by matamatama, 13 January 2013 - 05:23 AM
matamatama #1
Posted 13 January 2013 - 06:23 AM
How to call a function inside a " IF or While " ?

I know to call o function with :
functionname()

Exemple :
function name()
apple = eat
end

//Then To Call

name()

But when I call a function inside a " IF or While " I receive a error : "attempt do call nil"

Exemple of the error :
function name()
apple = eat
end

if orange == orange then
name()
else
print("LoLOloL")
end

Then my question is : can I call a function inside a " IF " or a " While " ?
W00dyR #2
Posted 13 January 2013 - 06:46 AM
yes you can, as long as you call it correctly, and if the function is written without errors, it should work flawlessly
ChunLing #3
Posted 13 January 2013 - 08:23 AM
You probably defined the function inside another scope or somewhere that the definition didn't get executed before the if block.

You should post the actual code that is producing the error.
matamatama #4
Posted 13 January 2013 - 08:35 AM
Actual Code :

function main()
term.clear()
term.setCursorPos(1,1)

print("Master Turtle Control OS v1.1")

textutils.slowPrint("Modo De Comando Acionado")
rednet.open("top")

write("Comando = ")
comando = read()

if comando == "ts1" then
rednet.broadcast("TS1s")
main()
elseif comando == "ts12" then
rednet.broadcast("TS1b")
main()
else
textutils.slowPrint("Error")
print(comando)
sleep(10)
main()
end
end
main()
crazyguymgd #5
Posted 13 January 2013 - 08:48 AM
Actual Code :

function main()
term.clear()
term.setCursorPos(1,1)

print("Master Turtle Control OS v1.1")

textutils.slowPrint("Modo De Comando Acionado")
rednet.open("top")

write("Comando = ")
comando = read()

if comando == "ts1" then
rednet.broadcast("TS1s")
main()
elseif comando == "ts12" then
rednet.broadcast("TS1b")
main()
else
textutils.slowPrint("Error")
print(comando)
sleep(10)
main()
end
end
main()

This worked fine for me when I ran it.
remiX #6
Posted 13 January 2013 - 08:48 AM
It should work, but what you're doing is causing it to have a stack over flow (calling a function within itself)

Rather use an infinite loop, like so:

rednet.open("top")

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

	print("Master Turtle Control OS v1.1")

	textutils.slowPrint("Modo De Comando Acionado")

	write("Comando = ")
	comando = read()

	if comando == "ts1" then
		rednet.broadcast("TS1s")
	elseif comando == "ts12" then
		rednet.broadcast("TS1b")
	else
		textutils.slowPrint("Error")
		print(comando)
		sleep(10)
	end
end

Btw, please use [code]– code here…[/code] tags :)/>
matamatama #7
Posted 13 January 2013 - 08:51 AM
Thanks everybody I'll use the remiX version (: again : thanks