%% Copyright (C) 2020-2022 by Marcel Krueger
%%
%% This file may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License, either
%% version 1.3c of this license or (at your option) any later
%% version. The latest version of this license is in:
%%
%% http://www.latex-project.org/lppl.txt
%%
%% and version 1.3 or later is part of all distributions of
%% LaTeX version 2005/12/01 or later.

\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage
  {docstrip-luacode}
  [2021/05/12 v0.1.4 Directly execute Lua code from DocStrip files]
\RequirePackage{iftex}
\RequireLuaTeX
\expanded{%
  \def\noexpand\docstrip@luacode@argscanner#1\directlua{
  tex.sprint(\the\catcodetable@string, "\string\\end{docstrip-luacode}")
  local scanner = token.create'docstrip@luacode@argscanner'
  local file = lpeg.Ct((lpeg.P'\csstring\%' * (1-lpeg.P'\string\r')^0 + lpeg.C((1-lpeg.P'\string\r')^0) * '\string\r')^0)/function(s)return table.concat(s,'\string\n')end
  local func = luatexbase.new_luafunction'docstrip-luacode'
  token.set_lua('docstrip-luacode', func, 'protected')
  lua.get_functions_table()[func] = function()
    local name = token.scan_string()
    tex.catcodetable = \the\catcodetable@string
    tex.setcatcode(32, 12)
    token.put_next(scanner)
    token.scan_token()
    package.preload[name], msg = loadstring(file:match(token.scan_string()))
  end
}{\relax{#1}\noexpand\end{docstrip-luacode}}}
\endinput
