Prerequisites
Before starting, make sure you have:- .NET 6.0 SDK or later installed
- A code editor (Visual Studio, VS Code, or Rider)
- The Loretta.CodeAnalysis.Lua NuGet package installed
Parse Lua code
Create a new C# file and add the following code to parse a simple Lua script:The
LuaSyntaxTree.ParseText method is your main entry point. It takes a string of Lua code and returns a syntax tree representing the parsed structure.Get the root node
Every syntax tree has a root node that represents the entire file:The root is always a
CompilationUnitSyntax, which contains all the statements in your Lua file plus the end-of-file token.Inspect the syntax tree
Now let’s explore the parsed structure. We’ll find all local variable declarations:Output:The
DescendantNodes() method traverses the entire tree, and OfType<T>() filters to specific node types.Complete example
Here’s a complete working example that puts it all together:Choose your Lua version
By default, Loretta accepts all syntax features (LuaSyntaxOptions.All). To parse code for a specific Lua version, use LuaParseOptions:
LuaSyntaxOptions.Lua51- Lua 5.1LuaSyntaxOptions.Lua52- Lua 5.2LuaSyntaxOptions.Lua53- Lua 5.3LuaSyntaxOptions.Lua54- Lua 5.4LuaSyntaxOptions.LuaJIT20- LuaJIT 2.0LuaSyntaxOptions.LuaJIT21- LuaJIT 2.1-beta3LuaSyntaxOptions.GMod- Garry’s Mod Lua (GLua)LuaSyntaxOptions.Luau/LuaSyntaxOptions.Roblox- Roblox LuauLuaSyntaxOptions.FiveM- FiveM (Lua 5.3 + hash strings)LuaSyntaxOptions.All- All features enabled (default)
Next steps
Now that you can parse Lua code, explore these topics:Core concepts
Understand syntax trees, nodes, tokens, and trivia
Syntax tree navigation
Learn how to traverse and query syntax trees
Code transformation
Rewrite and transform Lua code
Error handling
Work with parse errors and diagnostics
Common tasks
Parse from a file
Parse with specific encoding
Get syntax errors only
Troubleshooting
”The type or namespace name ‘Loretta’ could not be found”
Make sure you’ve installed the NuGet package:Unexpected parse errors
Verify you’re using the correct syntax preset for your Lua version. Features likecontinue, compound assignment, or type annotations are only available in certain Lua dialects.
Performance with large files
For very large files, consider parsing on a background thread and passing aCancellationToken: