Lua function tables via luerl and threading through the lua state

Hello elixir friends,

I’ve been playing around with luerl recently, and generally, it’s been trouble-free; straight-forward and easy to use; works well with elixir.

The corner case I ran into is when fetching function tables from lua. I can call the returned function but I cannot find a way to thread through the lua state.

Given this example lua;

function get_function_table()
  table = {}
  table["increment"] = increment
  return table
end

state = 0
function increment()
  state = state + 1
  print("state is "..state)
  return state
end

And this elixir code;

# setup state, load script etc.
lua_state = :luerl.init()
script = File.read!("sample.lua")
{:ok, chunk, lua_state} = :luerl.load(script, lua_state)
{_, lua_state} = :luerl.do(chunk, lua_state)

# get the function table and call whatever "increment" points to
{[lua_map], _lua_state} = :luerl.call_function([:get_function_table], [], lua_state)
ex_map = Map.new(lua_map)
function = ex_map["increment"]
[number] = function.([]) # How can lua_state be threaded through?

It calls “increment”. But since the lua_state isn’t threaded through, side effects are lost. I cannot find a way to pass through the state.

function is a #Function with arity /1, and it’s env seems to include the lua state at the time get_function_table was called.

I’ve read through the luerl code to try and figure out how to accomplish this since I assume that internally it must be doing something similar in luerl_emul.erl. But I haven’t been able to figure it out.

There are workarounds, such as returning the function name as a string instead. But I’m curious about this.

My question is; is there a supported way in luerl, to call function and thread through the lua state?

There’s a complete example escript at https://github.com/eskil/luerl_map_to_function that demonstrates it.

Thanks!

3 Likes