How to terminate Lua script?

user1610406 picture user1610406 · Oct 6, 2012 · Viewed 34.3k times · Source

How would I terminate a Lua script? Right now I'm having problems with exit(), and I don't know why. (This is more of a Minecraft ComputerCraft question, since it uses the APIs included.) Here is my code:

while true do

    if turtle.detect() then

        if turtle.getItemCount(16) == 64 then

            exit() --here is where I get problems

        end

        turtle.dig() --digs block in front of it

    end

end

Answer

user1704650 picture user1704650 · Oct 6, 2012

As prapin's answer states, in Lua the function os.exit([code]) will terminate the execution of the host program. This, however, may not be what you're looking for, because calling os.exit will terminate not only your script, but also the parent Lua instances that are running.

In Minecraft ComputerCraft, calling error() will also accomplish what you're looking for, but using it for other purposes than genuinely terminating the script after an error has occurred is probably not a good practice.

Because in Lua all script files are also considered functions having their own scope, the preferred way to exit your script would be to use the return keyword, just like you return from functions.

Like this:

while true do

    if turtle.detect() then

        if turtle.getItemCount(16) == 64 then

            return -- exit from the script and return to the caller

        end

        turtle.dig() --digs block in front of it

    end

end