flutter_lua_bridge 0.3.0
flutter_lua_bridge: ^0.3.0 copied to clipboard
Typed Dart / Lua interoperability with annotation-based code generation.
flutter_lua_bridge #
Run Lua in Flutter and Dart apps with synchronous calls in both directions.
Lua is compiled from source for the target platform by a build hook; nothing
needs to be installed. LuaRuntime is the single entry point, used directly
or through typed APIs generated by
flutter_lua_bridge_codegen.
flutter pub add flutter_lua_bridge
import 'package:flutter_lua_bridge/flutter_lua_bridge.dart';
final lua = LuaRuntime.create(); // LuaLibrary.safe by default
try {
lua['greet'] = lua.function((args) => 'hello ${args.first}');
print(lua.eval('return greet("lua")')); // hello lua
final config = lua.eval('return { size = 3, tags = { "a", "b" } }') as LuaTable;
print(config.toDart()); // {size: 3, tags: [a, b]}
} on LuaBridgeException catch (e) {
print('${e.message}\n${e.traceback}');
} finally {
lua.close();
}
- Values cross the boundary as
null,bool,int,double,String, or a handle (LuaTable,LuaFunction,LuaThread,LuaUserdata); a DartUint8Listargument becomes a Lua string, and DartMapandListarguments are copied into new tables. - Errors never crash the process: every operation runs protected, and a
failure is a
LuaBridgeExceptionwithstatus,messageandtraceback. - Sandboxing: the default
LuaLibrary.safeleaves outio,os,debugand native module loading; otherLuaLibraryflags add them. Memory limits and interrupts are available on the runtime. - Threading: calls are synchronous and confined to the isolate that
created the runtime.
LuaWorkerruns a runtime on a background isolate instead (see below).
Background isolate #
Heavy or untrusted Lua blocks the isolate it runs on. A LuaWorker owns a
runtime on its own isolate; calls return Futures, run one at a time in
order, and can be stopped from outside:
// Runs in the worker isolate: a top-level or static function.
void loadRules(LuaRuntime lua) {
lua.loadModule('rules', source: rulesSource);
lua.run('rules = require("rules")');
}
final worker = await LuaWorker.spawn(setup: loadRules, memoryLimit: 32 << 20);
try {
final results = await worker.call(
'rules.score',
[board],
timeout: const Duration(milliseconds: 200),
);
print(results.first);
} on LuaBridgeException catch (e) {
// LuaStatus.interrupted when the timeout stopped it.
} finally {
await worker.close();
}
runandcalltake and return plain data (null,bool,int,double,String,Uint8List,List,Map); a returned table arrives as aListorMap. Handles cannot leave the worker.timeoutandinterrupt()stop the running call; Lua checks every 1000 VM instructions, so a Dart function Lua is calling finishes first.- Lua can call the asynchronous Dart functions of the setup (see below) and
waits for them; the next call starts when this one has ended. The time
spent waiting counts for
timeout, and a call that waits is stopped at once. - Errors arrive as
LuaBridgeException; a Dart error thrown in the worker arrives as itstoString()incause. - Keep cheap calls on a plain
LuaRuntime: a worker call costs a message round trip. close()frees the isolate and its Lua state; call it when you are done, for example indispose. Forgetting it is not fatal: an idle worker does not keep the program running, and an unreferenced one is closed when it is garbage collected.
Asynchronous Dart functions #
A Dart function given to Lua may return a Future. Lua calls it as an
ordinary function and waits for the result without blocking the isolate,
when Dart runs that Lua code asynchronously:
lua['fetch'] = lua.function((args) async {
await Future.delayed(const Duration(milliseconds: 10)); // a network call, say
return 'body of ${args.single}';
});
final length = lua.load('''
local body = fetch(...) -- waits here; other Dart code keeps running
return #body
''');
print(await length.callAsync(['/home'])); // [13]
- A failed future raises a Lua error at the call, which
pcallcan catch. - Lua code that Dart runs synchronously (
call,run,eval) cannot wait: the Dart function raises an error that says so. With generated contracts, declare the method as returning aFuture; see Asynchronous methods. - Lua waits only in the code
callAsyncruns and the Lua functions it calls. A coroutine that Lua created, a function called by a C function (the comparison oftable.sort, the replacement ofstring.gsub) and Lua that a Dart function called synchronously cannot wait; the Dart function raises an error there too. - While a call waits, the runtime stays usable and other calls run in between; they share the same Lua globals.
lua.interrupt()fails the calls that wait withLuaStatus.interrupted, andlua.close()with aStateError, both at once. The work behind the future is not cancelled; its result is dropped.
Typed contracts #
Describe the API in Dart and let the generator write both sides:
@LuaApi(module: 'battle')
abstract class BattleApi {
int calculateDamage(Fighter attacker, Fighter defender);
}
This library re-exports the annotations, so a contract imports only
package:flutter_lua_bridge/flutter_lua_bridge.dart. See
flutter_lua_bridge_codegen
and the step-by-step
Getting started.
Lua from a server #
The Lua source is plain text loaded at runtime, so it can be delivered without an app release. It must implement the contract the app was built with, as source text (bytecode is rejected) within the sandbox you open. See Loading Lua at runtime.
Lua version #
Lua 5.3, 5.4 (default) and 5.5 are bundled. Pick one in the workspace root
pubspec.yaml:
hooks:
user_defines:
flutter_lua_bridge:
lua_version: "5.5"
A local source tree or a downloaded archive works too; see Choosing the Lua source.