Chapter IV ·
Lua.ex integration
/
Lesson 21 of 27
Host integration
Exposing Elixir with deflua
You'll learn: Define a module with
use Lua.API + deflua, then load it with Lua.load_api/2.
deflua turns an Elixir function into a Lua-callable. The
optional scope: puts it under a namespace — scope:
"pricing" exposes pricing.discount(…).
Lua.load_api(lua, MyModule) registers the module on the VM.
The Lua side just calls a function; the Elixir side runs the
body.
Elixir · your app
Reference only
defmodule Pricing do
use Lua.API, scope: "pricing"
deflua discount(amount, pct) do
amount * (1 - pct / 100)
end
end
lua = Lua.new() |> Lua.load_api(Pricing)
{[total], _} = Lua.eval!(lua, ~S|return pricing.discount(100, 15)|)
# total = 85.0
Output
idle
Hit Run to execute.
Try it:
Add
deflua tax(amount, rate) to Pricing, returning amount * rate. Call pricing.tax(85, 0.08) from Lua — remember to extend the playground stub too.