NetherGranite
NetherGranite

Reputation: 2100

Load Lua file and catch any syntax errors

Is there a function in Lua that will try to load another Lua file and catch any syntax errors? I cannot find anything that doesn't only catch exceptions. Is the solution to include a Lua parser in my project?

Upvotes: 2

Views: 2136

Answers (2)

Curtis Fenner
Curtis Fenner

Reputation: 1403

loadfile, like load/loadstring, returns nil plus the error message when there are syntactic errors:

Source: If there are no syntactic errors, returns the compiled chunk as a function; otherwise, returns nil plus the error message.

local success, syntaxError = loadfile("myfile.lua")
if not success then
    print("There was a syntax error:", syntaxError)
else
    print("No syntax error")
end

A pcall is not necessary, since loadstring does not throw errors.

Upvotes: 2

NetherGranite
NetherGranite

Reputation: 2100

I'm dumb, the answer is obvious:

pcall(function()
    loadfile("path/to/file")
end)

Edit: As pointed out by Egor Skriptunoff in the comments, a more efficient solution:

pcall(loadfile, "path/to/file")

This works because all arguments after the first argument to pcall are passed as arguments to the first argument passed to pcall—in this case, loadfile.

Upvotes: 1

Related Questions