{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module HsLua.Class.Invokable
( Invokable (..)
, invoke
) where
import Data.ByteString (append)
import HsLua.Core as Lua
import HsLua.Class.Peekable
import HsLua.Class.Pushable
import HsLua.Class.Util (popValue)
class Invokable a where
addArg :: Name -> (forall e. LuaError e => LuaE e ()) -> NumArgs -> a
instance (LuaError e, Peekable a) => Invokable (LuaE e a) where
addArg :: Name -> (forall e. LuaError e => LuaE e ()) -> NumArgs -> LuaE e a
addArg Name
fnName forall e. LuaError e => LuaE e ()
pushArgs NumArgs
nargs = do
Status
_ <- ByteString -> LuaE e Status
forall e. ByteString -> LuaE e Status
dostring (ByteString -> LuaE e Status) -> ByteString -> LuaE e Status
forall a b. (a -> b) -> a -> b
$ ByteString
"return " ByteString -> ByteString -> ByteString
`append` Name -> ByteString
Lua.fromName Name
fnName
LuaE e ()
forall e. LuaError e => LuaE e ()
pushArgs
NumArgs -> NumResults -> LuaE e ()
forall e. LuaError e => NumArgs -> NumResults -> LuaE e ()
call NumArgs
nargs NumResults
1
LuaE e a
forall e a. (LuaError e, Peekable a) => LuaE e a
popValue
instance (Pushable a, Invokable b) => Invokable (a -> b) where
addArg :: Name -> (forall e. LuaError e => LuaE e ()) -> NumArgs -> a -> b
addArg Name
fnName forall e. LuaError e => LuaE e ()
pushArgs NumArgs
nargs a
x =
Name -> (forall e. LuaError e => LuaE e ()) -> NumArgs -> b
forall a.
Invokable a =>
Name -> (forall e. LuaError e => LuaE e ()) -> NumArgs -> a
addArg Name
fnName (LuaE e ()
forall e. LuaError e => LuaE e ()
pushArgs LuaE e () -> LuaE e () -> LuaE e ()
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> a -> LuaE e ()
forall a e. (Pushable a, LuaError e) => a -> LuaE e ()
push a
x) (NumArgs
nargs NumArgs -> NumArgs -> NumArgs
forall a. Num a => a -> a -> a
+ NumArgs
1)
invoke :: Invokable a => Name -> a
invoke :: Name -> a
invoke Name
fname = Name -> (forall e. LuaError e => LuaE e ()) -> NumArgs -> a
forall a.
Invokable a =>
Name -> (forall e. LuaError e => LuaE e ()) -> NumArgs -> a
addArg Name
fname (() -> LuaE e ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()) NumArgs
0