Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate Lua script?

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
like image 969
user1610406 Avatar asked Oct 06 '12 14:10

user1610406


People also ask

How do I end a Lua script?

Use os. exit() or just return from some "main" function if your script is embedded.

Does return end in Lua?

There is an implicit return at the end of the Lua functions. As per syntactic reason the return statement should be the last statement of a block or function, before the end keyword.

How do I close Lua Windows?

Try control-D in Unix, control-Z in Windows or os. exit() if you must. I've found one situation where only os. exit() works: the interactive lua shell of the lua.

How do I run a Lua script from the command line?

To run a Lua scriptOpen the Lua Script Library through Prepare > Run Lua Script. Use the appearing dialog to load, save, and execute Lua scripts as well as to create new ones. Select the script to be run. Click Execute Script.


1 Answers

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
like image 117
user1704650 Avatar answered Sep 28 '22 01:09

user1704650