lualike library
An embeddable Lua-like runtime and tooling library for Dart.
This library is the main public entrypoint for embedding LuaLike in Dart
applications. It combines the high-level runtime bridge in LuaLike, the
one-shot execution helper executeCode(), AST parsing helpers such as
parse() and parseExpression(), and the public value and error types used
when Dart code exchanges data with scripts.
Typical usage starts with LuaLike when you want a long-lived runtime:
import 'package:lualike/lualike.dart';
Future<void> main() async {
final lua = LuaLike();
lua.expose('double', (List<Object?> args) {
final value = Value.wrap(args.first).unwrap() as num;
return Value(value * 2);
});
final result = await lua.execute('return double(21)');
print((result as Value).unwrap());
}
Use executeCode() when you want a one-shot helper without managing a
runtime instance yourself:
import 'package:lualike/lualike.dart';
Future<void> main() async {
final result = await executeCode(
'return 20 + 22',
mode: EngineMode.luaBytecode,
);
print((result as Value).unwrap());
}
The EngineMode.luaBytecode backend currently passes the Lua compatibility
suite, but it is still slower than the default AST interpreter in the
current implementation.
Use parse(), parseExpression(), luaChunkId(), and
looksLikeLuaFilePath() when you want syntax analysis or source labeling
without executing code.
For lower-level parser utilities, import package:lualike/parsers.dart.
For the native library registration APIs used by the built-in standard
libraries, import package:lualike/library_builder.dart.
Classes
- ABCInstruction
- Instruction using the ABC mode (3 operands + optional k flag).
- ABxInstruction
- Instruction using the ABx mode (A + 17-bit unsigned operand).
- AliasDescriptor
- Concrete DocDescriptor for a type alias.
- AliasDoc
-
Describes a type alias (
---@alias). - AliasVariant
- A single variant in a string literal union alias.
- AsBxInstruction
- Instruction using the AsBx mode (A + 17-bit signed operand).
- AsJInstruction
- Instruction using the sJ mode (25-bit signed jump offset).
- Assignment
- x = expr or k, v = next(t)
- AssignmentIndexAccessExpr
-
words[i] = 1words.value[i] = 1 - AstNode
-
Base class for all ASFuture
<T>nodes. -
AstVisitor<
T> -
Visitor interface for ASFuture
<T>nodes. - AvBCInstruction
- Instruction using the vBC mode (variant-length operands + k flag).
- AxInstruction
- Instruction using the Ax mode (25-bit unsigned operand).
- BaseIODevice
- Base implementation with common functionality
- BinaryExpression
- Binary operation: left op right.
- BinaryFormatOption
-
Represents a single directive inside a Lua 5.4
string.packformat. - BinaryFormatParser
- Parser that turns a Lua 5.4 binary-format string into a list of BinaryFormatOptions, performing the same validation that the Lua VM does.
- BooleanConstant
- BooleanLiteral
- Boolean literal.
-
Box<
T> - A generic box class that wraps a single value of type T. Used to create mutable references to values in the environment.
- Break
- BuiltinFunction
- Abstract base class representing a built-in function in the interpreter.
- BuiltinFunctionGcRefs
- Optional interface for builtins that need to keep GC-visible references.
- Call
- CallFrame
- Represents a call frame in the interpreter's call stack.
- CallStack
- Manages the call stack for the interpreter.
- ChildPrototypeBuilder
- CompileArtifact
- Result of running the compilation pipeline.
- CompilePipeline Compiler
- Multi-pass compilation pipeline that transforms Lua source into bytecode.
- CompilePipelineConfig
- Configuration for the compilation pipeline.
- CompositeFileSystemBackend
- Chains multiple FileSystemBackend instances in priority order.
- ConstantDescriptor
- Concrete DocDescriptor for a constant value.
- DartFunction
- Wrapper for Dart functions to make them callable from LuaLike.
- DoBlock
- DocDescriptor
- A documentation descriptor that pairs with LibraryRegistrationContext.define to declare an exported value's type and metadata.
- DocParam
- Describes a single parameter accepted by a library function.
- Dumpable
- Mixin for AST nodes that can be serialized ("dumped") into a data structure and reconstructed ("undumped") later.
- ElseIfClause
- EnumDescriptor
- Concrete DocDescriptor for an enum table.
- EnumDoc
-
Describes an enum table (
---@enum). - Environment
- Represents a scope for variable bindings in the interpreter.
- ExpressionStatement
- Expression used as a statement.
- FieldDoc
- Describes a single field in a Lua table schema.
- FileManager
- Manages source file loading and virtual file system for the VM.
- FileSystemBackend
- Abstract interface for filesystem operations.
- FileSystemProvider
- Single file system provider that can be configured with different IODevice implementations
- ForInLoop
- ForLoop
-
A numeric
forloop, as infor var = start, end [, step] do ... end. - FormatPart
- Represents a parsed format specifier or a literal string segment.
- FormatStringParser
- FunctionBody
- FunctionCall
- Function call: name(args).
- FunctionDef
- function name(params) body end
- FunctionDescriptor
- Concrete DocDescriptor for a callable function.
- FunctionDoc
- Documentation for a Lua-standard-library function or constant.
- FunctionLiteral
- FunctionName
- GenericParam
- Declares a generic type parameter on a function or class.
- GlobalDeclaration
- global * / global name list / global name list = exprs
- Goto
- GroupedExpression
- Grouped expression in parentheses: (expr)
- Identifier
- Identifier.
- IfStatement
- if cond then thenBlock ... end
- IndexedTableEntry
- IntegerConstant
- Interpreter
- Virtual Machine for the LuaLike interpreter.
- IODevice
- Abstract interface for IO devices
- IrBytecodeRegisterBudget
- Shared limits for IR → Lua bytecode lowering.
- KeyedTableEntry
- Label
- Library
- Abstract base class for organizing standard library functions.
- LiteralPart
- LocalDebugEntry
- Local variable debug entry attached to an IR prototype.
- LocalDeclaration
- local x = expr
- LocalFunctionDef
- Logger
- LongStringConstant
- LuaAssetLoader
- Loads compiled Lua bytecode from the filesystem or the CLI bundle.
- LuaBytecodeArtifact
- A Lua 5.5 binary chunk produced by CompilePipeline.
- LuaBytecodeRuntime
-
Runtime wrapper that executes source by emitting real
lua_bytecodechunks and running them through the bytecode VM. - LuaBytecodeVm
- LuaCallableArtifact
- Engine-neutral callable artifact marker for compiled runtime closures.
- LuaChunkLoadRequest
- Request for loading source or binary chunk input through the active engine.
- LuaChunkLoadResult
- Result of loading a chunk through the active runtime engine.
- LuaClosurePayload
- Closure-only payload for Lua function values.
- LuaFile
- Represents a Lua file object
- LuaFunctionDebugInfo
- Function metadata that debug helpers can consume without engine-specific casts.
- LuaLike
- Bridge class to manage Dart-LuaLike interop.
- LuaLikeConfig
- Global configuration settings for the LuaLike interpreter
- LualikeIrArtifact
- A lualike IR chunk produced by CompilePipeline.
- LualikeIrBasicBlock
- A basic block in the existing lualike IR.
- LualikeIrChunk
- Complete lualike IR chunk ready for serialization/execution.
- LualikeIrChunkBuilder
- LualikeIrChunkFlags
- Flags applied to a lualike IR chunk/header.
- LualikeIrCompiler
- Compiles AST programs into lualike IR chunks understood by the upcoming VM.
- LualikeIrConstant
- Representation of a constant used within a lualike IR prototype.
- LualikeIrControlFlowGraph
- A control-flow graph derived from a lualike IR prototype.
- LualikeIrDebugInfo
- Debug info associated with a prototype.
- LualikeIrInstruction
- Base class for lualike IR instructions expressed in structured form.
- LualikeIrOpcode
- Enumeration of the lualike IR instructions supported by the lualike VM.
- LualikeIrPhi
- An SSA phi node describing a value selected from predecessor blocks.
- LualikeIrPrototype
- A lualike IR prototype (function), mirroring Lua's Proto structure.
- LualikeIrPrototypeBuilder
- Utility for building lualike IR prototypes with automatic constant interning.
- LualikeIrReader
-
Parses a textual
lualike_irdescription into executable IR objects. - LualikeIrRuntime
- Runtime wrapper that executes code via the lualike IR VM while satisfying the LuaRuntime contract expected by higher-level tooling.
- LualikeIrSsaBlock
- A CFG block with an SSA overlay.
- LualikeIrSsaFunction
- A placeholder SSA shape built on top of the existing IR control-flow graph.
- LualikeIrSsaTypeAnalysis
- Result of type-analyzing a single IR prototype (function).
- LualikeIrSsaUse
- A use of an SSA value at a particular control-flow location.
- LualikeIrSsaValue
- A single SSA value for one register version.
- LualikeIrToDart
- Emits Dart source from lualike IR using the existing Value runtime.
- LualikeIrToLlvm
-
Lowers a lualike IR prototype to LLVM IR using
lualike_rtC runtime calls. - LualikeIrUpvalueDescriptor
- Descriptor for an upvalue captured by a prototype.
- LuaMatch
- Result of a single Lua pattern match.
- LuaNumberParser
- Prevent instantiation – this is a pure utility class.
- LuaPattern
- Compiled Lua pattern that can search within strings.
- LuaPatternCompiler
- LuaRuntime
- Shared runtime capabilities required by stdlib, lualike IR VM, and the AST interpreter.
- LuaStackFrame
- Represents a stack frame in a Lua call stack.
- LuaStackTrace
- Represents a call stack in Lua.
- LuaString
- LuaStringParser
- A PetitParser-based parser for Lua string literals that handles escape sequences correctly
- LuaValueMetadata
- Optional side metadata for Value features that most wrappers never need.
- MethodCall
- NilConstant
- NilValue
- Literal representing a nil value.
- NumberConstant
- NumberLiteral
- Numeric literal.
- NumberUtils
- OperatorDoc
-
Describes a Lua operator metamethod declaration (
---@operator). - OverloadDoc
- An alternative overloaded signature for a function.
- PeepholePass
- Applies peephole optimizations to an IR chunk after emission.
- ProcessBackend
- Pluggable backend for process execution.
- ProcessRunResult
- Result of a synchronous process execution.
- Program
- Represents the top-level program.
- ReadResult
- Represents the result of a read operation
- RepeatUntilLoop
- repeat body until cond
- ReturnStatement
- return expr
- ShortStringConstant
- SpecifierPart
-
Stack<
T> - A simple generic stack implementation.
- StringLiteral
- String literal.
- TableAccessExpr
- Legacy table access expression - kept for backward compatibility Will be deprecated in favor of TableFieldAccess and TableIndexAccess
- TableConstructor
- Table constructor: { entries }.
- TableDescriptor
- Concrete DocDescriptor for a table schema.
- TableDoc
- Describes the expected shape of a Lua table value.
- TableEntry
- Abstract base class for table entries.
- TableEntryLiteral
- Table entry given as a lone expression.
- TableFieldAccess
- Table field access expression (table.field) - dot notation
- TableIndexAccess
-
A table index access expression, as in
table[expr]. - TailCallSignal
- Non-exception tail-call handoff used by the AST interpreter.
- UnaryExpression
- Unary operation: op expr. Example: -5, not true.
- Utf8DecodeResult
- Internal helper result for UTF-8 decode routines.
- Value
- Represents a value in the LuaLike runtime system.
- ValueClass
- Example usage:
- ValueDoc
- Documents a constant value or typed global variable.
- VarArg
- VirtualLuaTable
- WhileStatement
- while cond do body end
- WriteResult
- Represents the result of a write operation
- YieldStatement
- yield expr
Enums
- AccessScope
- Controls visibility of functions, fields, and class members in generated LuaLS annotations.
- BufferMode
- Represents buffering modes for IO operations
- CompileBackend
- Which bytecode backend to target.
- EngineMode
- Supported execution engines for LuaLike.
- Level
- LualikeIrSsaType
- Classification of what a Lua value can be at runtime.
- SeekWhence
- Represents a seek position in a file
Mixins
Extensions
- DynamicValueExtension on Object?
- Extension methods for all objects to simplify Value conversion.
- FutureValueExtension on Future
- Extension methods for Futures to simplify async Value operations
- ListValueExtension on List
- Extension methods for Lists to simplify Value operations
- MapValueExtension on Map
- Extension methods for Maps to simplify Value operations
- OperatorExtension on Value
- StringLuaExtension on String
- Extension methods for strings to simplify Lua-style string operations
- ValueExtension on T
- Extension methods for the Value class to simplify common operations
- VMInterop on LuaRuntime
- Extension methods for the VM to add Dart interop capabilities
Constants
- isProductMode → const bool
- Detect if we're running in product mode (compiled executable)
- isWeb → const bool
- Detect if we're running on the web platform
Properties
- currentFileSystemBackend → FileSystemBackend?
-
The current custom backend, or
nullif using the default.no setter - currentProcessBackend → ProcessBackend?
-
The currently installed ProcessBackend, or
nullif the platform default is in use.no setter - currentRssBytes → int
-
Platform-safe way to get the current process RSS in bytes.
no setter
-
environment
→ Map<
String, String> -
Platform-safe way to get environment variables
no setter
- executableName → String
-
Platform-safe way to get the executable name/path
no setter
-
fileMetamethods
→ Map<
String, Object> -
final
- isLinux → bool
-
Platform-safe way to check if we're on Linux
no setter
- isMacOS → bool
-
Platform-safe way to check if we're on macOS
no setter
- isWindows → bool
-
Platform-safe way to check if we're on Windows
no setter
- pathSeparator → String
-
Platform-safe way to get path separator
no setter
- resolvedExecutablePath → String
-
Platform-safe way to get the resolved executable path of the current process
For compiled binaries, this is the absolute path to the binary.
no setter
- scriptPath → String?
-
Platform-safe way to get the script path
no setter
Functions
-
analyzeLualikeIrSsaTypes(
LualikeIrPrototype prototype, LualikeIrSsaFunction ssaFunction) → LualikeIrSsaTypeAnalysis - Runs type inference on an SSA function.
-
buildLualikeIrSsaFunction(
LualikeIrPrototype prototype) → LualikeIrSsaFunction - Builds a simplified SSA view for a compiled IR prototype.
-
compileLuaPattern(
String pattern) → Parser< String> -
createDirectory(
String path, {bool recursive = true, LuaRuntime? interpreter}) → Future< bool> - Platform-safe way to create a directory.
-
createLuaFile(
IODevice device, {bool isStandardFile = false, LuaRuntime? interpreter}) → Value -
currentFileSystemBackendFor(
LuaRuntime? interpreter) → FileSystemBackend? -
Returns the filesystem backend selected for
interpreter. -
dartStringCacheKey(
String value) → String - Produces a cache key for public Dart-string Value wrappers.
-
deleteFile(
String path, {LuaRuntime? interpreter}) → Future< void> - Platform-safe way to delete a file
-
deletePath(
String path, {bool recursive = true, LuaRuntime? interpreter}) → Future< bool> - Platform-safe way to delete either a file or a directory.
-
deserializeLualikeIrBytes(
List< int> bytes) → LualikeIrChunk -
directoryExists(
String path, {LuaRuntime? interpreter}) → Future< bool> - Platform-safe way to check if a directory exists
-
disassembleChunk(
LualikeIrChunk chunk, {bool includeSubPrototypes = true, bool includeConstants = true, bool includeLineInfo = true}) → String - Human-readable dump of a LualikeIrChunk.
-
executeCode(
String sourceCode, {FileManager? fileManager, RuntimeSetupCallback? onRuntimeSetup, LuaRuntime? vm, EngineMode? mode, Object? url, bool? foldEnabled}) → Future< Object?> - Executes source text using the selected engine.
-
fileExists(
String path, {LuaRuntime? interpreter}) → Future< bool> - Platform-safe way to check if a file exists
-
fileSize(
String path, {LuaRuntime? interpreter}) → Future< int?> - Platform-safe way to get a file's size in bytes.
-
formatLualikeIrChunk(
LualikeIrChunk chunk) → String -
formatLualikeIrSsaFunction(
LualikeIrSsaFunction function) → String -
fromLuaValue(
dynamic obj) → dynamic -
getCurrentDirectory(
{LuaRuntime? interpreter}) → String? - Platform-safe way to get current working directory
-
getEnvironmentVariable(
String name) → String? - Platform-safe way to get a specific environment variable
-
getLastModified(
String path, {LuaRuntime? interpreter}) → Future< DateTime?> - Platform-safe way to get the last modified time for a file.
-
levelName(
Level level) → String -
listDirectory(
String path, {LuaRuntime? interpreter}) → Future< List< String> > - Platform-safe way to list directory contents
-
loadFile(
String path, {LuaRuntime? runtime}) → Future< Value> - Loads a Lua script from a file.
-
looksLikeLuaFilePath(
String source) → bool -
Returns whether
sourcelooks like a filesystem path that Lua should treat as a chunk name instead of a literal inline source label. -
looksLikeLualikeIrBytes(
List< int> bytes) → bool -
looksLikeLualikeIrString(
String value) → bool -
lowerIrChunkToLuaBytecodeChunk(
LualikeIrChunk chunk, {String? chunkName}) → LuaBytecodeBinaryChunk - Mechanically lowers finalized lualike IR into Lua 5.5 bytecode.
-
lowerIrPrototypeToLuaBytecodePrototype(
LualikeIrPrototype prototype, {required String sourceName, bool isMainPrototype = false}) → LuaBytecodePrototype - Lowers one finalized IR prototype to a Lua bytecode prototype.
-
luaChunkId(
String source) → String -
Returns the Lua-style chunk identifier for
source. -
luaStringCacheKey(
List< int> bytes) → String -
Produces a stable cache key for Lua strings based on their raw byte
sequence. This avoids collisions between textual keys such as the string
"100"and a one-byte string whose byte value is100("d"). -
luaStringCacheKeyFromRawString(
String value) → String - Produces a Lua string cache key for a Dart string whose code units already represent the intended Lua byte sequence.
-
parse(
String source, {Object? url}) → Program - Parses a LuaLike chunk into a Program.
-
parseExpression(
String source, {Object? url}) → AstNode - Parses a single LuaLike expression into an AstNode.
-
parseLogLevel(
String name) → Level? - Parse level names from CLI/env supporting both contextual and legacy names. Examples: debug, info, warning, error, alert, notice, FINE, INFO, WARNING, SEVERE, SHOUT, CONFIG
-
readFileAsBytes(
String path, {LuaRuntime? interpreter}) → Future< List< int> ?> - Platform-safe way to read a file as bytes
-
readFileAsString(
String path, {LuaRuntime? interpreter}) → Future< String?> - Platform-safe way to read a file as string
-
renameFile(
String oldPath, String newPath, {LuaRuntime? interpreter}) → Future< void> - Platform-safe way to rename/move a file
-
runCode(
String code, {String? filePath, Map< String, dynamic> ? env, LuaRuntime? runtime}) → Future<List< Value> > - Runs Lua code with the given environment.
-
runFile(
String pathStr, {Map< String, dynamic> ? env, LuaRuntime? runtime}) → Future<List< Value> > - Runs a Lua file with the given path.
-
runWithLuaErrorHandling<
T> (T fn(), {String? message, SourceSpan? span, AstNode? node, LuaStackTrace? luaStackTrace}) → T - Runs a function and catches any exceptions, converting them to LuaError.
-
serializeLualikeIrChunk(
LualikeIrChunk chunk) → Uint8List -
serializeLualikeIrChunkAsLuaString(
LualikeIrChunk chunk) → LuaString -
setFileSystemBackend(
FileSystemBackend? backend, {LuaRuntime? interpreter}) → void - Set a custom FileSystemBackend to override filesystem operations.
-
setFileSystemProvider(
FileSystemProvider? provider, {LuaRuntime? interpreter}) → void -
Sets the FileSystemProvider used by
io.open(),io.lines(),io.input(),io.output(), andio.tmpfile(). -
setLualikeLogging(
{bool? enabled, Level? level, String? category, List< String> ? categories, String? backend, bool? pretty}) → void - Sets up logging for LuaLike, using environment variables or explicit arguments.
-
setProcessBackend(
ProcessBackend? backend) → void - Overrides process execution with a custom ProcessBackend.
-
synchronized<
T> (Object lock, Future< T> fn()) → Future<T> -
throwLuaError(
String message, {SourceSpan? span, AstNode? node, Object? cause, StackTrace? stackTrace, LuaStackTrace? luaStackTrace}) → Never - Throws a Lua runtime error with the given message.
-
throwLuaErrorFromNode(
AstNode node, String message, {Object? cause, StackTrace? stackTrace, LuaStackTrace? luaStackTrace}) → Never - Throws a Lua runtime error from an AST node.
-
throwLuaTypeError(
String message, {SourceSpan? span, AstNode? node, Object? cause, StackTrace? stackTrace, LuaStackTrace? luaStackTrace}) → Never - Throws a Lua type error.
-
toLuaError(
Object exception, {String? message, SourceSpan? span, AstNode? node, StackTrace? stackTrace, LuaStackTrace? luaStackTrace}) → LuaError - Converts any exception to a LuaError.
-
toLuaValue(
dynamic dy) → Value -
validateIrChunkRegisterBudget(
LualikeIrChunk chunk) → void -
Validates
chunk(and nested prototypes) for Lua bytecode register limits. -
wrapLuaFileValue(
LuaFile luaFile, {LuaRuntime? interpreter}) → Value - Helper function to create a LuaFile wrapped in a Value with proper metamethods
-
writeFile(
String path, String content, {LuaRuntime? interpreter}) → Future< void> - Platform-safe way to write a file
Typedefs
-
AsyncFunction
= Future<
Object?> Function(List<Object?> args) - Represents an asynchronous function that can be called with a list of arguments.
-
IODeviceFactory
= Future<
IODevice> Function(String path, String mode) - Factory function type for creating IODevice instances
Exceptions / Errors
- BreakException
- Exception thrown for 'break' statements.
- ContinueException
- Exception thrown for 'continue' statements (if implemented).
- ControlFlowException
- Base class for exceptions used by the interpreter for control flow.
- GoToException
- GotoException
- Exception thrown for 'goto' statements.
- IrRegisterBudgetExceeded
- Thrown when IR cannot be encoded as official Lua bytecode registers.
- LuaError
- Exception thrown for Lua runtime errors with source location information.
- LuaPatternTooComplex
- Thrown when a Lua pattern would exceed Lua's recursive matcher depth.
- ReturnException
- Exception thrown for 'return' statements.
- TailCallException
- Exception used to implement proper tail calls.
- YieldException
- Exception thrown for 'coroutine.yield' calls.