arcticfox1919 / LuaDardo

A Lua virtual machine written in Dart
Apache License 2.0
172 stars 32 forks source link

Exposing Dart functions or methods to Lua side #4

Open johannphilippe opened 3 years ago

johannphilippe commented 3 years ago

Hello, and congratulations for your work. I have been looking for something similar for a long time, it is very exciting. I'm wondering if it is feasable to expose Dart functions and methods to Lua (like we can do with the Lua C API) ? I guess that would be possible to implement since you wrote the VM in Dart itself, it could be something like a Map associating strings to Dart Functions ?

Thanks again for this work

Also, not related : do you plan to work on null safety ?

Thanks

arcticfox1919 commented 3 years ago

@johannphilippe It supports the Lua C API, for which you can refer to the flutter_lua_dardo.

I already have plans to upgrade null safety, but it may take some time

johannphilippe commented 3 years ago

Great, thank you. I will try that !

johannphilippe commented 3 years ago

It's all working great. Thanks for your time and your work !

arcticfox1919 commented 2 years ago

An example:

import 'package:lua_dardo/lua.dart';
import 'dart:math';

//  wrapper function must use this signature:int Function(LuaState ls)
int randomInt(LuaState ls) {
  int max = ls.checkInteger(1);
  ls.pop(1);

  var random = Random();
  var randVal = random.nextInt(max);
  ls.pushInteger(randVal);
  return 1;
}

void main(List<String> arguments) {
  LuaState state = LuaState.newState();
  state.openLibs();

  state.pushDartFunction(randomInt);
  state.setGlobal('randomInt');

  // execute the Lua script to test the randomInt function
  state.loadString('''
rand_val = randomInt(10)
print('random value is '..rand_val)
''');
  state.call(0, 0);
}