Skip to content

deflua/2 (no-state) drops the function name for guarded heads, registering it as when #343

Closed

Description

@davydog187

Summary

A deflua function defined with a guard but without the state/lua argument (i.e. the 2-arity deflua/2 form) is registered under the name when instead of its real name. As a result the function is never exposed to Lua under its intended name — calling it from a script raises attempt to call a nil value.

Reproduction

defmodule MyAPI do
  use Lua.API, scope: "my"

  # guarded, no state arg -> uses deflua/2
  deflua clamp(n) when is_number(n) do
    n
  end
end

MyAPI.__lua_functions__()
#=> [{:when, false, false}]      # expected: [{:clamp, false, false}]
lua = Lua.new() |> Lua.load_api(MyAPI)
Lua.eval!(lua, "return my.clamp(1)")
# ** (Lua.RuntimeException) attempt to call a nil value (field 'clamp' on global 'my')

The Elixir function clamp/1 is defined correctly (it can be called directly); only its Lua registration name is wrong.

Root cause

The 2-arity deflua/2 macro extracts the name with:

{name, _, _} = fa

For a guarded head the AST is {:when, _, [{name, _, _} | _]}, so this binds name = :when.

The 3-arity deflua/3 (state) form already handles this case:

name =
  case fa do
    {:when, _, [{name, _, _} | _]} -> name
    {name, _, _} -> name
  end

Suggested fix

Use the same case-based name extraction in deflua/2 that deflua/3 already uses, so guards are supported regardless of whether the state arg is present.

Workaround

Move the guard out of the function head and validate inside the body (or add the state arg so the deflua/3 path is taken).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions