@@ -74,8 +74,22 @@ defmodule Lua.API do
7474 ~LUA[print("Hello at install time!")]c
7575 end
7676 end
77+
78+ ## Guards
79+
80+ When doing `use Lua.API`, we also import the guards documented in this API.
81+ This can be useful for having different function heads that match on encoded
82+ values. E.g.
83+
84+ deflua say_type(value) when is_table(value), do: "table"
85+ deflua say_type(value) when is_userdata(value), do: "table"
86+
87+ Keep in mind that if you want to work with values passed to `deflua` functions,
88+ they still need to be decoded first.
7789 """
7890
91+ require Record
92+
7993 defmacro __using__ ( opts ) do
8094 scope = opts |> Keyword . get ( :scope , "" ) |> String . split ( "." , trim: true )
8195
@@ -85,7 +99,17 @@ defmodule Lua.API do
8599 @ before_compile Lua.API
86100
87101 import Lua.API ,
88- only: [ runtime_exception!: 1 , deflua: 2 , deflua: 3 , validate_func!: 3 ]
102+ only: [
103+ runtime_exception!: 1 ,
104+ deflua: 2 ,
105+ deflua: 3 ,
106+ validate_func!: 3 ,
107+ is_table: 1 ,
108+ is_userdata: 1 ,
109+ is_lua_func: 1 ,
110+ is_erl_func: 1 ,
111+ is_mfa: 1
112+ ]
89113
90114 @ impl Lua.API
91115 def scope do
@@ -100,6 +124,32 @@ defmodule Lua.API do
100124 @ callback install ( Lua . t ( ) , scope_def ( ) , any ( ) ) :: Lua . t ( ) | Lua.Chunk . t ( ) | String . t ( )
101125 @ optional_callbacks [ install: 3 ]
102126
127+ @ doc """
128+ Is the value a reference to a Lua table?
129+
130+ """
131+ defguard is_table ( record ) when Record . is_record ( record , :tref )
132+
133+ @ doc """
134+ Is the value a reference to userdata?
135+ """
136+ defguard is_userdata ( record ) when Record . is_record ( record , :usdref )
137+
138+ @ doc """
139+ Is the value a reference to a Lua function?
140+ """
141+ defguard is_lua_func ( record ) when Record . is_record ( record , :funref )
142+
143+ @ doc """
144+ Is the value a reference to an Erlang / Elixir function?
145+ """
146+ defguard is_erl_func ( record ) when Record . is_record ( record , :erl_func )
147+
148+ @ doc """
149+ Is the value a reference to an Erlang / Elixir mfa?
150+ """
151+ defguard is_mfa ( record ) when Record . is_record ( record , :erl_mfa )
152+
103153 @ doc """
104154 Raises a runtime exception inside an API function, displaying contextual
105155 information about where the exception was raised.
0 commit comments