# Bind Lwt functions in ocaml-lua

**URL:** <https://discuss.ocaml.org/t/bind-lwt-functions-in-ocaml-lua/14376>\
**Category:** Learning\
**Tags:** lua, lwt\
**Created:** [March 28, 2024, 2:04pm UTC](https://discuss.ocaml.org/t/bind-lwt-functions-in-ocaml-lua/14376 "2024-03-28T14:04:22Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![intermet](https://avatars.discourse-cdn.com/v4/letter/i/85f322/32.png) [@intermet](https://discuss.ocaml.org/u/intermet)\
**Post date:** [March 28, 2024, 2:04pm UTC](https://discuss.ocaml.org/t/bind-lwt-functions-in-ocaml-lua/14376/1 "2024-03-28T14:04:22Z")

</div>

Hello,  
I am embeding the Lua interpreter [ocaml-lua](https://github.com/pdonadeo/ocaml-lua) into my application. I want to bind an ocaml function returning a `Lwt` promise `f : unit -> int Lwt.t`. The execution of the lua script will be made by `Lwt_main.run`. My attempt was to bind the function

```auto
function () -> Lwt_main.run @@ f ()

```

as follows

```auto
val f : unit -> int Lwt.t

let g (lua : Lua.state) = 
  let n = Lwt_main.run (f ()) in
  let () = Lua.pushinteger lua n in
  1

let open_api (lua : Lua.state) =
  let () = Lua.pushocamlfunction lua g in
  let () = Lua.setglobal lua "f" in
  ()

let script = {eos|
  x = f()
  print(x)
|eos}

let run_script () =
  let lua = LuaL.newstate () in
  let () = LuaL.openlibs lua in
  let () = open_api lua in
  let _status = LuaL.loadbuffer lua script "my_script" in
  match Lua.pcall lua 0 0 0 with
  | Lua.LUA_OK -> ()
  | _ -> let () = Lua.pop lua 1 in
         failwith "ERROR"

```

But `run_script` will be called in `Lwt_main.run` and we will have nested calls to `Lwt_main.run`, which is not allowed.

Any idea on how to bind the function `f`? In the lua script, the expected behavior is that `f()` waits until the promise is resolved.

Thank you!
