Dylan Sheaffer
Dylan Sheaffer

Reputation: 45

Don't execute if there is an error and print error message

This is pretty self explanatory but...

if input~=nil then
    docom=loadstring(input)
    print(docom())
else
    print("Command execution failed")
end

I know my error on the if statement but my point is how do i not run it if it is not a valid Lua command and instead print an error. and if it is valid Lua how do I make sure errors just get stopped and it runs a printed error message without crashing. I'm on linux btw if it requires os.execute()

Upvotes: 2

Views: 180

Answers (1)

Yu Hao
Yu Hao

Reputation: 122493

loadstring (or load, since Lua 5.2) returns nil plus the error message if the chunk has syntactic errors. So you could just check the result of load like this:

local chunk = 'foo'
local f, err = loadstring(chunk)
if not f then
    print(err)
else
    f()
end

Upvotes: 1

Related Questions