git.iko.soy/typeable/pandoc
on master help sign in
Text.Pandoc.Lua: keep element unchanged if filter returns nil

This was suggested by jgm and is consistent with the behavior of other filtering libraries.

commit4282abbd0781cf5e6731a9b43dc8cfeb1dca58fa authorAlbert Krewinkel <albert.krewinkel@tourstream.eu> dateTue 27 Jun 2017, 17:11 (9 years ago) parentbeb78a5
1 file changed+13−8
src/Text/Pandoc/Lua.hs+13−8
src/Text/Pandoc/Lua.hs+13−8
@@ -189,19 +189,24 @@ instance StackValue LuaFilter where
189189 peek lua idx = fmap (LuaFilter lua) <$> Lua.peek lua idx
190190
191191-- | Push a value to the stack via a lua filter function. The filter function is
192−-- called with all arguments that are passed to this function and is expected to
193−-- return a single value.
192+-- called with given element as argument and is expected to return an element.
193+-- Alternatively, the function can return nothing or nil, in which case the
194+-- element is left unchanged.
194195runFilterFunction :: StackValue a => LuaState -> LuaFilterFunction -> a -> IO a
195196runFilterFunction lua lf x = do
196197 pushFilterFunction lua lf
197198 Lua.push lua x
198199 Lua.call lua 1 1
199− mbres <- Lua.peek lua (-1)
200− case mbres of
201− Nothing -> throwIO $ LuaException
202− ("Error while trying to get a filter's return "
203− ++ "value from lua stack.")
204− Just res -> res <$ Lua.pop lua 1
200+ resType <- Lua.ltype lua (-1)
201+ case resType of
202+ Lua.TNIL -> Lua.pop lua 1 *> return x
203+ _ -> do
204+ mbres <- Lua.peek lua (-1)
205+ case mbres of
206+ Nothing -> throwIO $ LuaException
207+ ("Error while trying to get a filter's return "
208+ ++ "value from lua stack.")
209+ Just res -> res <$ Lua.pop lua 1
205210
206211-- | Push the filter function to the top of the stack.
207212pushFilterFunction :: Lua.LuaState -> LuaFilterFunction -> IO ()