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
Use os. exit() or just return from some "main" function if your script is embedded.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With