{-# LANGUAGE CPP #-}
module Foreign.Lua.Raw.Call
( HsFunction
, hslua_newhsfunction
, hslua_pushhsfunction
) where
import Foreign.C (CInt (CInt))
import Foreign.Ptr (Ptr, castPtr, nullPtr)
import Foreign.StablePtr (StablePtr, deRefStablePtr, newStablePtr)
import Foreign.Storable (peek)
import Foreign.Lua.Raw.Types
( NumResults (NumResults)
, State (State)
)
#ifdef ALLOW_UNSAFE_GC
#define SAFTY unsafe
#else
#define SAFTY safe
#endif
type HsFunction = State -> IO NumResults
foreign import ccall SAFTY "hslua.h hslua_hs_fun_ptr"
hslua_hs_fun_ptr :: State -> IO (Ptr ())
foreign import ccall SAFTY "hslua.h hslua_newhsfunction"
hslua_newhsfunction :: State -> StablePtr a -> IO ()
hslua_pushhsfunction :: State -> HsFunction -> IO ()
hslua_pushhsfunction :: State -> HsFunction -> IO ()
hslua_pushhsfunction State
l HsFunction
preCFn =
HsFunction -> IO (StablePtr HsFunction)
forall a. a -> IO (StablePtr a)
newStablePtr HsFunction
preCFn IO (StablePtr HsFunction)
-> (StablePtr HsFunction -> IO ()) -> IO ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= State -> StablePtr HsFunction -> IO ()
forall a. State -> StablePtr a -> IO ()
hslua_newhsfunction State
l
{-# INLINABLE hslua_pushhsfunction #-}
hslua_call_wrapped_hs_fun :: HsFunction
hslua_call_wrapped_hs_fun :: HsFunction
hslua_call_wrapped_hs_fun State
l = do
Ptr ()
udPtr <- State -> IO (Ptr ())
hslua_hs_fun_ptr State
l
if Ptr ()
udPtr Ptr () -> Ptr () -> Bool
forall a. Eq a => a -> a -> Bool
== Ptr ()
forall a. Ptr a
nullPtr
then [Char] -> IO NumResults
forall a. HasCallStack => [Char] -> a
error [Char]
"Cannot call function; corrupted Lua object!"
else do
HsFunction
fn <- Ptr (StablePtr HsFunction) -> IO (StablePtr HsFunction)
forall a. Storable a => Ptr a -> IO a
peek (Ptr () -> Ptr (StablePtr HsFunction)
forall a b. Ptr a -> Ptr b
castPtr Ptr ()
udPtr) IO (StablePtr HsFunction)
-> (StablePtr HsFunction -> IO HsFunction) -> IO HsFunction
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= StablePtr HsFunction -> IO HsFunction
forall a. StablePtr a -> IO a
deRefStablePtr
HsFunction
fn State
l
foreign export ccall hslua_call_wrapped_hs_fun :: HsFunction