From 3a57c598b43508f7242ad8e5b0e731d58de8a575 Mon Sep 17 00:00:00 2001 From: Dave Lucia Date: Wed, 10 Jun 2026 12:53:44 -0700 Subject: [PATCH] fix(api): deflua/2 preserves function name for guarded heads For a guarded head like `deflua clamp(a) when is_integer(a) do ... end`, the AST passed to deflua/2 is `{:when, _, [{:clamp, _, _} | _]}`. The single binding `{name, _, _} = fa` matched the outer tuple and bound `name` to `:when`, so the function was registered in `@lua_function` (and `__lua_functions__/0`) as `:when`, making it unreachable from Lua. Use the same case-based extraction deflua/3 already uses to unwrap the `:when` node and reach the real function name, falling back to the plain head for non-guarded definitions. The existing "deflua functions can have guards" test only asserted the generated Elixir function worked and never checked the Lua registration name, which is why this slipped through; a new test asserts `__lua_functions__/0` contains the real name (not `:when`) and that the guarded function is callable from Lua. Closes #343 --- lib/lua/api.ex | 6 +++++- test/lua/api_test.exs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/lib/lua/api.ex b/lib/lua/api.ex index bf702a48..9cb262de 100644 --- a/lib/lua/api.ex +++ b/lib/lua/api.ex @@ -262,7 +262,11 @@ defmodule Lua.API do See `deflua/3` """ defmacro deflua(fa, rest) do - {name, _, _} = fa + name = + case fa do + {:when, _, [{name, _, _} | _]} -> name + {name, _, _} -> name + end quote do @lua_function validate_func!( diff --git a/test/lua/api_test.exs b/test/lua/api_test.exs index fed72281..9ac023c7 100644 --- a/test/lua/api_test.exs +++ b/test/lua/api_test.exs @@ -333,6 +333,38 @@ defmodule Lua.APITest do assert {1, _} = module.with_state(1, Lua.new()) assert {"not a int", _} = module.with_state(true, Lua.new()) end + + test "guarded deflua heads register under their real name, not :when" do + assert [{module, _}] = + Code.compile_string(""" + defmodule GuardedRegistration do + use Lua.API + + deflua has_a_guard(a) when is_integer(a) do + a + end + + deflua has_a_guard(_) do + "not a int" + end + + deflua with_state(a) when is_integer(a), state do + {a, state} + end + end + """) + + names = Enum.map(module.__lua_functions__(), &elem(&1, 0)) + + assert :has_a_guard in names + assert :with_state in names + refute :when in names + + lua = Lua.load_api(Lua.new(), module) + + assert {[1], _} = Lua.eval!(lua, "return has_a_guard(1)") + assert {["not a int"], _} = Lua.eval!(lua, "return has_a_guard('foo')") + end end describe "guards" do