Foreign.Lua: provide stack index helpers nthTop, nthBottom, nth, top
@@ -10,11 +10,17 @@ Extend Haskell programs with a Lua interpreter.
-}
module Foreign.Lua
( withNewState
+ -- * Stack index helpers
+ , nthTop
+ , nthBottom
+ , nth
+ , top
) where
+import Foreign.C (CInt)
import Foreign.Lua.Auxiliary (hsluaL_newstate)
import Foreign.Lua.Functions (lua_close)
-import Foreign.Lua.Types (State)
+import Foreign.Lua.Types (StackIndex (StackIndex), State)
-- | Runs operations on a new Lua @'Lua.State'@. The state is created
-- when the function is called and closed on return. The state, and all
@@ -26,3 +32,27 @@ withNewState f = do
result <- f l
lua_close l
return result
+
+--
+-- Stack index helpers
+--
+
+-- | Stack index of the nth element from the top of the stack.
+nthTop :: CInt -> StackIndex
+nthTop n = StackIndex (-n)
+{-# INLINABLE nthTop #-}
+
+-- | Stack index of the nth element from the bottom of the stack.
+nthBottom :: CInt -> StackIndex
+nthBottom = StackIndex
+{-# INLINABLE nthBottom #-}
+
+-- | Alias for 'nthTop'.
+nth :: CInt -> StackIndex
+nth = nthTop
+{-# INLINABLE nth #-}
+
+-- | Index of the topmost stack element.
+top :: StackIndex
+top = nthTop 1
+{-# INLINABLE top #-}
