Vital.sandbox
Engine

engine.compile_string

Shared

Validates whether a buffer contains valid Lua syntax


Syntax

local result, error = engine.compile_string(buffer, chunk_name = "")

Parameters

TypeNameDescription
stringbufferBuffer containing code to be validated
stringchunk_nameLabel used in error messages to identify the source
Example: "scripts/init.lua"

Returns

TypeNameDescription
boolresulttrue if the buffer is valid Lua syntax, false otherwise
bool / stringerrorfalse on success, or error message containing chunk name and line number on failure

Examples

Check if code is valid before executing
local result, err = engine.compile_string("engine.print('info', 'hello')")
if result then
    engine.print("info", "Valid syntax")
else
    engine.print("error", err)
end
Use chunk_name to get readable error locations
local result, err = engine.compile_string("local x =", "scripts/init.lua")
if not result then
    engine.print("error", err) --scripts/init.lua:1: unexpected symbol near '<eof>'
end
Use compile_string to try expression syntax before falling back to statement
local code = "x = 1 + 1"
local try_expr = "return "..code

local exec = (
    engine.compile_string(try_expr) and 
    engine.load_string(try_expr, nil, false)
) or engine.load_string(code, nil, false)

if exec then
    exec()
end

On this page