git.iko.soy/typeable/pandoc
on master help sign in
Lua.Util: avoid altering the stack if peeking fails
9ddf840Albert Krewinkel
src/Text/Pandoc/Lua/Util.hs+12−4
@@ -67,7 +67,7 @@ getTable :: (ToLuaStack a, FromLuaStack b) => StackIndex -> a -> Lua b
67getTable idx key = do
67getTable idx key = do
68 push key
68 push key
69 rawget (idx `adjustIndexBy` 1)
69 rawget (idx `adjustIndexBy` 1)
70− peek (-1) <* pop 1
70+ popValue
71
71
72-- | Add a key-value pair to the table at the top of the stack.
72-- | Add a key-value pair to the table at the top of the stack.
73addValue :: (ToLuaStack a, ToLuaStack b) => a -> b -> Lua ()
73addValue :: (ToLuaStack a, ToLuaStack b) => a -> b -> Lua ()
@@ -86,10 +86,9 @@ addFunction name fn = do
86
86
87-- | Get value behind key from table at given index.
87-- | Get value behind key from table at given index.
88getRawInt :: FromLuaStack a => StackIndex -> Int -> Lua a
88getRawInt :: FromLuaStack a => StackIndex -> Int -> Lua a
89−getRawInt idx key =
89+getRawInt idx key = do
90 rawgeti idx key
90 rawgeti idx key
91− *> peek (-1)
91+ popValue
92− <* pop 1
93
92
94-- | Set numeric key/value in table at the given index
93-- | Set numeric key/value in table at the given index
95setRawInt :: ToLuaStack a => StackIndex -> Int -> a -> Lua ()
94setRawInt :: ToLuaStack a => StackIndex -> Int -> a -> Lua ()
@@ -106,6 +105,15 @@ raiseError e = do
106 Lua.push e
105 Lua.push e
107 fromIntegral <$> Lua.lerror
106 fromIntegral <$> Lua.lerror
108
107
108+-- | Get, then pop the value at the top of the stack.
109+popValue :: FromLuaStack a => Lua a
110+popValue = do
111+ resOrError <- Lua.peekEither (-1)
112+ pop 1
113+ case resOrError of
114+ Left err -> Lua.throwLuaError err
115+ Right x -> return x
116+
109-- | Newtype wrapper intended to be used for optional Lua values. Nesting this
117-- | Newtype wrapper intended to be used for optional Lua values. Nesting this
110-- type is strongly discouraged and will likely lead to a wrong result.
118-- type is strongly discouraged and will likely lead to a wrong result.
111newtype OrNil a = OrNil { toMaybe :: Maybe a }
119newtype OrNil a = OrNil { toMaybe :: Maybe a }