Skip to main content

flutter_lua_bridge 0.3.0 copy "flutter_lua_bridge: ^0.3.0" to clipboard
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 Dart Uint8List argument becomes a Lua string, and Dart Map and List arguments are copied into new tables.
  • Errors never crash the process: every operation runs protected, and a failure is a LuaBridgeException with status, message and traceback.
  • Sandboxing: the default LuaLibrary.safe leaves out io, os, debug and native module loading; other LuaLibrary flags add them. Memory limits and interrupts are available on the runtime.
  • Threading: calls are synchronous and confined to the isolate that created the runtime. LuaWorker runs 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();
}
  • run and call take and return plain data (null, bool, int, double, String, Uint8List, List, Map); a returned table arrives as a List or Map. Handles cannot leave the worker.
  • timeout and interrupt() 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 its toString() in cause.
  • 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 in dispose. 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 pcall can 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 a Future; see Asynchronous methods.
  • Lua waits only in the code callAsync runs and the Lua functions it calls. A coroutine that Lua created, a function called by a C function (the comparison of table.sort, the replacement of string.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 with LuaStatus.interrupted, and lua.close() with a StateError, 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.

0
likes
160
points
197
downloads

Documentation

API reference

Publisher

verified publishereplab.top

Weekly Downloads

Typed Dart / Lua interoperability with annotation-based code generation.

Repository (GitHub)
View/report issues

Topics

#lua #interop

License

MIT (license)

Dependencies

archive, code_assets, crypto, ffi, flutter_lua_bridge_codegen_annotation, hooks, native_toolchain_c

More

Packages that depend on flutter_lua_bridge