53

I want to exit the execution of a Lua script on some condition. For example:

content = get_content()
if not content then 
-- ( Here i want some kind of exit function )
next_content = get_content()
--example there can lot of further checks

Here I want that if I am not getting content my script suppose to terminate is should not go to check to next.

Luke100000
1,5382 gold badges8 silver badges21 bronze badges
asked Nov 25, 2013 at 9:22
1
  • 9
    os.exit() does just that. Commented Nov 25, 2013 at 20:29

4 Answers 4

68

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

answered Nov 25, 2013 at 9:28
29
os.exit()

kill process by sending a signal

do return end

stop execution

The two methods are not equal if you want to write and execute some luacode in the interpreter after stopping the execution by launching your program using the -i flag.

th -i main.lua
Matej
9,8738 gold badges52 silver badges68 bronze badges
answered Nov 26, 2013 at 13:51
1
  • 5
    In what way are they not equal? Commented Mar 8, 2017 at 18:14
8

In lua 5.2.0-beta-rc1+, you can add a label at the end of your code called ::exit:: or something of the like, and then whenever you need to exit the program just call it like this:

goto exit
answered Jun 7, 2016 at 21:05
3
  • Not sure what do you mean by adding a label of ::exit:: , is that a typo ? I don't think it's a correct syntax of lua. Commented Oct 25, 2020 at 17:10
  • 4
    It is valid Lua syntax Commented Nov 21, 2020 at 5:46
  • Ok, that is for the newest lua. I tried on old lua did not work Commented Oct 1, 2021 at 11:29
1

os.exit(ERROR_CODE) e.g. os.exit(1) is an answer.

Below is my practical example working with MS OS:

require("config_fonts")
local success, config_fonts = pcall(require, "config_fonts")
if not success then
 print("Error loading config_fonts.lua:", config_fonts)
 os.exit(1)
end

In a .bat or .cmd file:

%LUA% lua\some_script.lua
if errorlevel 1 (
 echo [ERROR] Failed to process something
 goto eof )
answered Jul 16, 2024 at 2:06

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.