Warning: this is an htmlized version!
The original is across this link,
and the conversion rules are here.
#######
#
# E-scripts on Lua.
#
# Note 1: use the eev command (defined in eev.el) and the
# ee alias (in my .zshrc) to execute parts of this file.
# Executing this file as a whole makes no sense.
#
# Note 2: be VERY careful and make sure you understand what
# you're doing.
#
# Note 3: If you use a shell other than zsh things like |&
# and the for loops may not work.
#
# Note 4: I always run as root.
#
# Note 5: some parts are too old and don't work anymore. Some
# never worked.
#
# Note 6: the definitions for the find-xxxfile commands are on my
# .emacs.
#
# Note 7: if you see a strange command check my .zshrc -- it may
# be defined there as a function or an alias.
#
# Note 8: the sections without dates are always older than the
# sections with dates.
#
# This file is at <http://angg.twu.net/e/lua5.e>
#           or at <http://angg.twu.net/e/lua5.e.html>.
#        See also <http://angg.twu.net/emacs.html>,
#                 <http://angg.twu.net/.zshrc[.html]>,
#                 <http://angg.twu.net/escripts.html>,
#             and <http://angg.twu.net/>.
#
#######



# «.lua-l»		(to "lua-l")
# «.message-id»		(to "message-id")
# «.gmane»		(to "gmane")
# «.reddit»		(to "reddit")
# «.install-4.0.1»	(to "install-4.0.1")
# «.install-5.0.2»	(to "install-5.0.2")
# «.install-5.0.3»	(to "install-5.0.3")
# «.install-5.1.1»	(to "install-5.1.1")
# «.install-5.1.2»	(to "install-5.1.2")
# «.install-5.1.3»	(to "install-5.1.3")
# «.install-5.1.4»	(to "install-5.1.4")
# «.compile-5.1.4-lua_O0»  (to "compile-5.1.4-lua_O0")
# «.install-5.2-beta»	(to "install-5.2-beta")
# «.install-5.2»	(to "install-5.2")
# «.minimal_GCW_SUGAR»	(to "minimal_GCW_SUGAR")
# «.compile-5.1.2-lua_O0»  (to "compile-5.1.2-lua_O0")
# «.install-5.1+ext»	(to "install-5.1+ext")
# «.build-simple»	(to "build-simple")
# «.build»		(to "build")
# «.argpatch»		(to "argpatch")
# «.argpatch-gdb»	(to "argpatch-gdb")
# «.argpatch-recompile»	(to "argpatch-recompile")

# «.lua50ref.e»		(to "lua50ref.e")
# «.lua50betaref.e»	(to "lua50betaref.e")
# «.invoking-arrays»	(to "invoking-arrays")
# «.string.find»	(to "string.find")
# «.string.gfind»	(to "string.gfind")
# «.emptycaptures»	(to "emptycaptures")
# «.0-based»		(to "0-based")
# «.vararg»		(to "vararg")
# «.lua-arg»		(to "lua-arg")
# «.pack-and-unpack»	(to "pack-and-unpack")
# «.pack-and-unpack-test»	(to "pack-and-unpack-test")
# «.envsubst»		(to "envsubst")
# «.readfile»		(to "readfile")
# «.writefile»		(to "writefile")
# «.mytostring»		(to "mytostring")
# «.split»		(to "split")
# «.for»		(to "for")
# «.each2»		(to "each2")
# «.require»		(to "require")
# «.lua5.1-require»	(to "lua5.1-require")
# «.lua5.1-package»	(to "lua5.1-package")

# «.loadlib2»		(to "loadlib2")
# «.luaL_openlib»	(to "luaL_openlib")
# «.pio_fontx»		(to "pio_fontx")
# «.mailing-list-archive»  (to "mailing-list-archive")
# «.hash»		(to "hash")

# «.io.output»		(to "io.output")
# «.vmmerge5.lua»	(to "vmmerge5.lua")
# «.vmmerge»		(to "vmmerge")
# «.suggestions»	(to "suggestions")
# «.tolua-5.0»		(to "tolua-5.0")
# «.tolua-5.1»		(to "tolua-5.1")
# «.etags»		(to "etags")
# «.readline»		(to "readline")
# «.linenoise»		(to "linenoise")
# «.stringtolines»	(to "stringtolines")
# «.lua-lpeg-wheezy»	(to "lua-lpeg-wheezy")
# «.lpeg-rock»		(to "lpeg-rock")
# «.lua-posix-wheezy»	(to "lua-posix-wheezy")
# «.luaposix-2012»	(to "luaposix-2012")
# «.luaposix»		(to "luaposix")
# «.posix-lua51»	(to "posix-lua51")
# «.posix»		(to "posix")
# «.posix-new»		(to "posix-new")
# «.posix-install»	(to "posix-install")
# «.load_posix»		(to "load_posix")
# «.posix-old»		(to "posix-old")
# «.posix-ls»		(to "posix-ls")
# «.pushglobals-popglobals»  (to "pushglobals-popglobals")
# «.gsub-with-alternatives»  (to "gsub-with-alternatives")
# «.C-calls-lua»	(to "C-calls-lua")
# «.lua-calls-C»	(to "lua-calls-C")
# «.luastackPP»		(to "luastackPP")
# «.composes»		(to "composes")
# «.stdlib»		(to "stdlib")
# «.stdlib2»		(to "stdlib2")
# «.ricilake-parser»	(to "ricilake-parser")
# «.reuben-thomas-libs»	(to "reuben-thomas-libs")
# «.compat-5.1»		(to "compat-5.1")
# «.cgilua»		(to "cgilua")
# «.quick-presentation»	(to "quick-presentation")
# «.string.gsub»	(to "string.gsub")
# «.makewith»		(to "makewith")
# «.pil»		(to "pil")
# «.pil1.tgz»		(to "pil1.tgz")
# «.pil2»		(to "pil2")
# «.lua51gtk»		(to "lua51gtk")
# «.luagtk»		(to "luagtk")
# «.luagtk_pixmaps»	(to "luagtk_pixmaps")

# «.bitlib»		(to "bitlib")
# «.bitlib-51»		(to "bitlib-51")
# «.luabitop»		(to "luabitop")
# «.rexlib»		(to "rexlib")
# «.io.popen»		(to "io.popen")
# «.txt2html_in_blogme»	(to "txt2html_in_blogme")
# «.luasocket-static-aix»  (to "luasocket-static-aix")
# «.luasocket-on-linux»	(to "luasocket-on-linux")
# «.luasocket-lua51»	(to "luasocket-lua51")
# «.lua2c»		(to "lua2c")
# «.calling-Lua-from-C»	(to "calling-Lua-from-C")
# «.monitored_p_C»	(to "monitored_p_C")
# «.debug.debug»	(to "debug.debug")
# «.getoutput»		(to "getoutput")
# «.signal»		(to "signal")
# «.captured-variables»	(to "captured-variables")
# «.objective-lua»	(to "objective-lua")
# «.tokenf»		(to "tokenf")
# «.ex»			(to "ex")
# «.xpcall»		(to "xpcall")
# «.traceback»		(to "traceback")
# «.stacktraceplus»	(to "stacktraceplus")
# «.metamethods-pseudocode»  (to "metamethods-pseudocode")
# «.generators-pseudocode»   (to "generators-pseudocode")
# «.pil24.1»		(to "pil24.1")
# «.pixeltoaster»	(to "pixeltoaster")
# «.compressing-jpgs»	(to "compressing-jpgs")
# «.matrix.lua»		(to "matrix.lua")
# «.lpeg»		(to "lpeg")
# «.lpeg-0.6»		(to "lpeg-0.6")
# «.lpeg-precaptures»	(to "lpeg-precaptures")
# «.lpeg-0.7»		(to "lpeg-0.7")
# «.lpeg-0.8.1»		(to "lpeg-0.8.1")
# «.lpeg-0.9»		(to "lpeg-0.9")
# «.lpeg-0.10.2»	(to "lpeg-0.10.2")
# «.lpeg-metatable»	(to "lpeg-metatable")
# «.lpeg-Cg-and-Cb»	(to "lpeg-Cg-and-Cb")
# «.lpeg-0.12»		(to "lpeg-0.12")
# «.lpeg-re»		(to "lpeg-re")
# «.lpeg-re-find»	(to "lpeg-re-find")
# «.lpeg-quickref»	(to "lpeg-quickref")
# «.lpeg-trace»		(to "lpeg-trace")
# «.lpeg.Cmt»		(to "lpeg.Cmt")
# «.lpeg-ex-arith-1»	(to "lpeg-ex-arith-1")
# «.lpeg-ex-arith-2»	(to "lpeg-ex-arith-2")
# «.lpeg-layers»	(to "lpeg-layers")
# «.lpeg-elisp-hyperlinks»  (to "lpeg-elisp-hyperlinks")
# «.lpeg-debug»		(to "lpeg-debug")
# «.lpeglabel»		(to "lpeglabel")
# «.sheadsymbol-roberto»    (to "sheadsymbol-roberto")
# «.lpeg-0.5-bug»	(to "lpeg-0.5-bug")
# «.loadstring_and_eof»	(to "loadstring_and_eof")
# «.incompletep»	(to "incompletep")
# «.ldb-from-tgz»	(to "ldb-from-tgz")
# «.ldb»		(to "ldb")
# «.lua-mode.el»	(to "lua-mode.el")
# «.risclua»		(to "risclua")
# «.functionnames»	(to "functionnames")
# «.cinvoke»		(to "cinvoke")
# «.cinvoke-libtcl»	(to "cinvoke-libtcl")
# «.tlbridge.c»		(to "tlbridge.c")
# «.luatclbridge»	(to "luatclbridge")
# «.lunatic-python»	(to "lunatic-python")
# «.kepler»		(to "kepler")
# «.helper-threads»	(to "helper-threads")
# «.loona»		(to "loona")
# «.pseudo-spreadsheet»	(to "pseudo-spreadsheet")
# «.CGI.lua»		(to "CGI.lua")
# «.lua-filesystem»	(to "lua-filesystem")
# «.kepler-1.1»		(to "kepler-1.1")
# «.kepler-1.1-hasbang»	(to "kepler-1.1-hasbang")
# «.markdown.lua»	(to "markdown.lua")
# «.lua-discount»	(to "lua-discount")
# «.ctrace»		(to "ctrace")
# «.coroutines»		(to "coroutines")
# «.luacoco»		(to "luacoco")
# «.chunkspy»		(to "chunkspy")
# «.mav»		(to "mav")
# «.lpeg-links-ascii-diags»  (to "lpeg-links-ascii-diags")
# «.lua-ex»		(to "lua-ex")
# «.lua-api-from-gdb»	(to "lua-api-from-gdb")
# «.lua-datatypes-gdb»	(to "lua-datatypes-gdb")
# «.lua-numbers-gdb»	(to "lua-numbers-gdb")
# «.lua-strings-gdb»	(to "lua-strings-gdb")
# «.lua-closures-gdb»	(to "lua-closures-gdb")
# «.lbci»		(to "lbci")
# «.numlua»		(to "numlua")
# «.clue»		(to "clue")
# «.reader»		(to "reader")
# «.interactor»		(to "interactor")
# «.interactor-prefixes»	(to "interactor-prefixes")
# «.debug.getinfo»		(to "debug.getinfo")
# «.getlocal-and-setlocal»	(to "getlocal-and-setlocal")
# «.metalua»		(to "metalua")
# «.gradual-typing»	(to "gradual-typing")
# «.setvbuf»		(to "setvbuf")
# «.luarocks-mailing-list»	(to "luarocks-mailing-list")
# «.luarocks»			(to "luarocks")
# «.luarocks-interactively»	(to "luarocks-interactively")
# «.luarocks-my-email-1»	(to "luarocks-my-email-1")
# «.luarocks-fosdem2015»	(to "luarocks-fosdem2015")
# «.luarocks-chat»	(to "luarocks-chat")
# «.alien»		(to "alien")
# «.lexpect»		(to "lexpect")
# «.lpty»		(to "lpty")
# «.shells-in-lua»	(to "shells-in-lua")
# «.coxpcall»		(to "coxpcall")
# «.elua-and-grub»	(to "elua-and-grub")
# «.elua»		(to "elua")
# «.apairs-and-print»	(to "apairs-and-print")
# «.LUA_COMPAT_VARARG»	(to "LUA_COMPAT_VARARG")
# «.coroutine-iterator»	(to "coroutine-iterator")
# «.modal.lua»		(to "modal.lua")
# «.lpeg.Cmt»		(to "lpeg.Cmt")
# «.lpeg.Cmt-2»		(to "lpeg.Cmt-2")
# «.preproc»		(to "preproc")
# «.ee_loadlib»		(to "ee_loadlib")
# «.shake»		(to "shake")
# «.ctemplate»		(to "ctemplate")
# «.string.__call»	(to "string.__call")
# «.wordgrinder»	(to "wordgrinder")
# «.primemover»		(to "primemover")
# «.vectors»		(to "vectors")
# «.love»		(to "love")
# «.love-deb-src»	(to "love-deb-src")
# «.tableauxprover»	(to "tableauxprover")
# «.love-vilua»		(to "love-vilua")
# «.lua-gnuplot»	(to "lua-gnuplot")
# «.lua5.1-tests»	(to "lua5.1-tests")
# «.lua5.2-tests»	(to "lua5.2-tests")
# «.ltcl»		(to "ltcl")
# «.ltcltk»		(to "ltcltk")
# «.ltcltk-new»		(to "ltcltk-new")
# «.addlayer»		(to "addlayer")
# «.phyzios»		(to "phyzios")
# «.bison-and-lua»	(to "bison-and-lua")
# «.luainspect»		(to "luainspect")
# «.sticky-metatables»	(to "sticky-metatables")
# «.metatable-reductions»  (to "metatable-reductions")
# «.rima»		(to "rima")
# «.mult-table»		(to "mult-table")
# «.LA.lua»		(to "LA.lua")
# «.oop.lua»		(to "oop.lua")
# «.closure-reductions»	(to "closure-reductions")
# «.luatcc»		(to "luatcc")
# «.ao»			(to "ao")
# «.vlists»		(to "vlists")
# «.environments»	(to "environments")
# «.luajit»		(to "luajit")
# «.luadist»		(to "luadist")
# «.package.path»	(to "package.path")
# «.gsl-shell»		(to "gsl-shell")
# «.lua-codegen»	(to "lua-codegen")
# «.jnlua»		(to "jnlua")
# «.goto»		(to "goto")
# «.lua_getstack»	(to "lua_getstack")
# «.xctrl»		(to "xctrl")
# «.leg»		(to "leg")
# «.nan-and-inf»	(to "nan-and-inf")
# «.zerobrane»		(to "zerobrane")
# «.printable-functions» (to "printable-functions")
# «.NamedFunction»	(to "NamedFunction")
# «.string.format»	(to "string.format")
# «.histogram»		(to "histogram")
# «.histograms»		(to "histograms")
# «.64-bit-integers»	(to "64-bit-integers")
# «.penlight»		(to "penlight")
# «.pl.pretty»		(to "pl.pretty")
# «.pl.wrap»		(to "pl.wrap")
# «.pl.text.wrap»	(to "pl.text.wrap")
# «.penlight-git»	(to "penlight-git")
# «.pl.pretty-fix»	(to "pl.pretty-fix")
# «.penlight-old»	(to "penlight-old")
# «.microlight»		(to "microlight")
# «.lua-repl»		(to "lua-repl")
# «.lua-repl-rock»	(to "lua-repl-rock")
# «.lua-repl-0.5»	(to "lua-repl-0.5")
# «.lua-repl-0.8»	(to "lua-repl-0.8")
# «.lua-repl-2016»	(to "lua-repl-2016")
# «.luarepl-2016»	(to "luarepl-2016")
# «.luarepl-2017»	(to "luarepl-2017")
# «.luarepl-2017-latex»	(to "luarepl-2017-latex")
# «.luarepl-displayresults»	(to "luarepl-displayresults")
# «.luaprompt»		(to "luaprompt")
# «.Repl»		(to "Repl")
# «.over»		(to "over")
# «.follow»		(to "follow")
# «.icollect»		(to "icollect")
# «.lua-innards-gdb»	(to "lua-innards-gdb")
# «.Sexp»		(to "Sexp")
# «.kslua»		(to "kslua")
# «.luaforwindows»	(to "luaforwindows")
# «.hex»		(to "hex")
# «.latex-parsing»	(to "latex-parsing")
# «.coroutine-for»	(to "coroutine-for")
# «.cow-and-coy»	(to "cow-and-coy")
# «.video_fnames_js»	(to "video_fnames_js")
# «.thijs-threads»	(to "thijs-threads")
# «.worp»		(to "worp")
# «.rawtostring»	(to "rawtostring")
# «.re»			(to "re")
# «.lbc»		(to "lbc")
# «.html-parsers»	(to "html-parsers")
# «.gumbo-parser»	(to "gumbo-parser")
# «.lua-gumbo-build»	(to "lua-gumbo-build")
# «.lua-gumbo»		(to "lua-gumbo")
# «.pegdebug»		(to "pegdebug")
# «.syntax-trees»	(to "syntax-trees")
# «.pkg-config»		(to "pkg-config")
# «.pluto»		(to "pluto")
# «.serpent»		(to "serpent")
# «.ldoc»		(to "ldoc")
# «.firestar»		(to "firestar")
# «.debug.lua»		(to "debug.lua")
# «.graph-toolkit»	(to "graph-toolkit")
# «.debug2»		(to "debug2")
# «.debug2-compile-0»	(to "debug2-compile-0")
# «.30log»		(to "30log")
# «.lua5.2-debian»	(to "lua5.2-debian")
# «.utf8»		(to "utf8")
# «.utf8-to-html»	(to "utf8-to-html")
# «.mult-as-comp»	(to "mult-as-comp")
# «.free-hosting»	(to "free-hosting")
# «.ElispHF»		(to "ElispHF")
# «.getsexpskel»	(to "getsexpskel")
# «.SexpLine»		(to "SexpLine")
# «.SetL»		(to "SetL")
# «.Tos»		(to "Tos")
# «.Tos-indented»	(to "Tos-indented")
# «.VerticalTable»	(to "VerticalTable")
# «.getdefs»		(to "getdefs")
# «.web-frameworks»	(to "web-frameworks")
# «.lua-version»	(to "lua-version")
# «.tekui»		(to "tekui")
# «.relative-require»	(to "relative-require")
# «.underlined-lines»	(to "underlined-lines")
# «.creating-solid-apis»  (to "creating-solid-apis")





#####
#
# Mailing list
# 2012apr04
#
#####

# «lua-l» (to ".lua-l")
# http://lua-users.org/lists/lua-l/

# «message-id» (to ".message-id")
http://lua-users.org/lists/lua-l/2013-07/msg00816.html

You can query by message-id. Use this form:
	+Message-ID: <20130725151210.GA22303@magritte.tecgraf.puc-rio.br>

Note the + at the beginning.

# «gmane»  (to ".gmane")
# http://news.gmane.org/gmane.comp.lang.lua.general
# GitHub offer:
# http://article.gmane.org/gmane.comp.lang.lua.general/89931

# «reddit» (to ".reddit")
# http://www.reddit.com/r/lua/






#####
#
# building lua-5.0.2 and installing it locally
# 2004jul31
#
#####

# Build with loadlib and readline, and without "-g", and install as:
#  ~/bin/lua50
#  ~/bin/luac50
#  ~/lib/liblua.so.5.0
#  ~/lib/liblualib.so.5.0
# Note that these lua50 and luac50 won't depend on the "liblib...so.5.0"s.

# http://www.lua.org/ftp/lua-5.0.2.tar.gz

# «install-5.0.2»  (to ".install-5.0.2")
# «install-5.0.3»  (to ".install-5.0.3")
# (code-c-d "lua5"  "~/usrc/lua-5.0.2/")
# (code-c-d "lua50" "~/usrc/lua-5.0.3/")
# (code-c-d "luaftp" "$S/http/www.lua.org/ftp/")
# (find-luaftpfile "")
# (find-lua50file "")
# http://www.lua.org/ftp/
# http://www.lua.org/ftp/lua-5.0.2.tar.gz
# http://www.lua.org/ftp/lua-5.0.3.tar.gz
#*
mkdir  ~/usrc/
rm -Rv ~/usrc/lua-5.0.3/
mkdir  ~/usrc/lua-5.0.3/
tar -xvzf $S/http/www.lua.org/ftp/lua-5.0.3.tar.gz -C ~/usrc/
cd     ~/usrc/lua-5.0.3/

find * -name '*.[ch]' | sort > .files.ch
etags $(<.files.ch)

# (find-lua5file "INSTALL")
# (find-lua5file "config")
# (find-lua5file "etc/README")
# (find-lua5file "src/lib/loadlib.c")
cat >> config <<'%%%'

# --- Edrx's changes
# (find-lua5file "config" "dynamic loading on Unix systems")
LOADLIB= -DUSE_DLOPEN=1
DLLIB= -ldl
MYLDFLAGS= -Wl,-E
MYCFLAGS=-g
#
# (find-lua5file "config" "\n#USERCONF=")
USERCONF=-DLUA_USERCONFIG='"$(LUA)/etc/saconfig.c"' -DUSE_READLINE
EXTRA_LIBS= -lm -lreadline -ldl

INSTALL_EXEC= cp -v
INSTALL_DATA= cp -v
STRIP=echo NOT stripping:
# INSTALL_BIN=$(HOME)/bin
INSTALL_BIN=/tmp/bin
INSTALL_INC=$(HOME)/include/lua5
INSTALL_LIB=$(HOME)/ulocal/lib
INSTALL_MAN=$(HOME)/ulocal/man/man1
%%%

make test	2>&1 | tee omt
ldd  bin/lua	2>&1 | tee ol
make so		2>&1 | tee oms
make install	2>&1 | tee omi
make soinstall	2>&1 | tee omsi
# (find-lua5file "om")
# (find-lua5file "omi")
# (find-lua5file "omsi")

#*
cd ~/usrc/lua-5.0.3/
cp -v bin/lua  ~/bin/lua50
cp -v bin/luac ~/bin/luac50
cp -v lib/liblua.so.5.0    ~/lib/liblua.so.5.0
cp -v lib/liblualib.so.5.0 ~/lib/liblualib.so.5.0

#*

#*
# (find-lua5file "src/lib/lmathlib.c")
# (find-efunction 'eegdb)
# (find-eev "eev-gud.el")
# (find-efunction 'eegud-gdb)
# (eegud-gdb t ee-luadir "bin/lua")
br luaopen_math
run

#*
cp bin/lua ~/bin/lua50noargpatch

#*



#####
#
# lua-4.0.1 (for checking incompatibilities)
# 2011oct12
#
#####

# «install-4.0.1»  (to ".install-4.0.1")
# http://www.lua.org/ftp/lua-4.0.1.tar.gz
#*
rm -Rfv ~/usrc/lua-4.0.1/
tar -C  ~/usrc/ -xvzf \
  $S/http/www.lua.org/ftp/lua-4.0.1.tar.gz
cd      ~/usrc/lua-4.0.1/

make   |& tee om
cp -v bin/lua  ~/bin/lua40
cp -v bin/luac ~/bin/luac40

#*
# (code-c-d "lua40" "~/usrc/lua-4.0.1/")
# (find-lua40file "")





#####
#
# building lua-5.1.1
# 2006jul18
#
#####

# «install-5.1.1»  (to ".install-5.1.1")
# http://www.lua.org/ftp/lua-5.1.1.tar.gz
See below; it's the same as for installing 5.1.2, with some ".1"s in
place of the ".2"s.



#####
#
# building lua-5.1.2
# 2007apr04
#
#####

# «install-5.1.2»  (to ".install-5.1.2")
# http://www.lua.org/ftp/lua-5.1.2.tar.gz
# (code-c-d "lua51" "~/usrc/lua-5.1.2/")
# (find-lua51file "")
# (find-lua51file "INSTALL")
# (find-lua51file "oml")
# (find-lua51file "src/Makefile")
# (find-node "(make)Phony Targets" "`.PHONY'")
#*
mkdir   ~/usrc/
rm -Rfv ~/usrc/lua-5.1.2/
mkdir   ~/usrc/lua-5.1.2/
tar  -C ~/usrc/ -xvzf $S/http/www.lua.org/ftp/lua-5.1.2.tar.gz
cd      ~/usrc/lua-5.1.2/

find * -name '*.[ch]' | sort > .files.ch
etags $(<.files.ch)

# (find-angg "bin/patch-lua-5.1.3")

# (to "risclua")
# «minimal_GCW_SUGAR»  (to ".minimal_GCW_SUGAR")
# (find-lua51file "src/llex.c" "#ifdef GCW_SUGAR")
# (find-lua51file "src/llex.c.orig" "case '=':")
# (find-tkdiff (ee-lua51file "src/llex.c") (ee-lua51file "src/llex.c.orig"))
#
cp -iv src/llex.c src/llex.c.orig
patch -p0 src/llex.c <<'%%%'
370a371,376
> #ifdef GCW_SUGAR
>         switch(ls->current) {
>          case '=': next(ls); return TK_EQ; break;
>          case '>': next(ls); return TK_RETURN; break;
>          default: return '=';  } 
> #else
372a379
> #endif
373a381,386
> #ifdef GCW_SUGAR
>       case '\\': {
>         next(ls);
>         return TK_FUNCTION;
>         }
> #endif
%%%

# Pre-compile llex.c with GCW_SUGAR=1
# cd src; gcc -O2 -Wall -DLUA_USE_LINUX -DGCW_SUGAR -c -o llex.o llex.c; cd ..
# Instead:

# (find-lua51file "src/Makefile")
patch -p0 src/Makefile <<'%%%'
11c11
< CFLAGS= -O2 -Wall $(MYCFLAGS)
---
> CFLAGS= -O2 -Wall $(MYCFLAGS) -g $(MYEXTRACFLAGS) -DGCW_SUGAR
%%%

# «compile-5.1.2-lua_O0»  (to ".compile-5.1.2-lua_O0")
# (find-angg ".emacs" "eepitch-gdb-lua")
# This block (optional) produces an unoptimized "lua" - "lua_O0" - for gdb.
# Note that its last (=3rd) line is a "make clean"...
{ make linux test MYEXTRACFLAGS="-ggdb -O0"
  mv -v src/lua src/lua_O0
  make clean
} |& tee oml0

make linux test |& tee oml

# Make a .so
# (find-lua50file "Makefile" "so:")
# (find-lua51file "src/Makefile" "CORE_O=")
cd src; ld -o liblua.so -shared $(ar t liblua.a); cd ..

# (find-lua51file "oml")
# (find-lua51file "oml2")

#*
cd ~/usrc/lua-5.1.2/src/
cp -iv lua  ~/bin/lua51
cp -iv luac ~/bin/luac51

#*
# Test dlopen on lpeg
# (to "lpeg")
cd ~/usrc/lpeg-0.5/
~/usrc/lua-5.1.1/src/lua test.lua
~/usrc/lua-5.1.2/src/lua test.lua

#*



# (find-lua51file "src/Makefile")
# (find-lua51file "src/Makefile" "linux:")
# (find-lua51file "Makefile")
# (find-lua51file "oml")


make MYCFLAGS=-DGCW_SUGAR linux test |& tee oml




#####
#
# building lua-5.1.3
# 2008jul21
#
#####

# «install-5.1.3»  (to ".install-5.1.3")
# http://www.lua.org/ftp/lua-5.1.3.tar.gz
# (code-c-d "lua51" "~/usrc/lua-5.1.3/")
# (find-lua51file "")
# (find-lua51file "INSTALL")
# (find-lua51file "oml")
# (find-lua51file "src/Makefile")
# (find-node "(make)Phony Targets" "`.PHONY'")
#*
mkdir   ~/usrc/
rm -Rfv ~/usrc/lua-5.1.3/
mkdir   ~/usrc/lua-5.1.3/
tar  -C ~/usrc/ -xvzf $S/http/www.lua.org/ftp/lua-5.1.3.tar.gz
cd      ~/usrc/lua-5.1.3/

find * -name '*.[ch]' | sort > .files.ch   ;# (find-lua51file ".files.ch")
etags $(<.files.ch)			   ;# (find-lua51file "TAGS")
~/bin/patch-lua-5.1.3			   ;# (find-angg "bin/patch-lua-5.1.3")
make linux test local |& tee omltl	   ;# (find-lua51file "omltl")

cd src; ld -o liblua.so -shared $(ar t liblua.a); cd ..
cd src; install -p -m 0644 liblua.so ../lib; cd ..

#*
cd ~/usrc/lua-5.1.4/src/
cp -iv lua  ~/bin/lua51
cp -iv luac ~/bin/luac51

#*
# (find-lua51file "Makefile")
# (find-lua51file "Makefile" "local:")
# (find-lua51file "")
# (find-lua51sh "find bin include lib man share | sort")

# I have not adapted this to lua-5.1.3 yet:
#   (find-es "lua5" "compile-5.1.2-lua_O0")





#####
#
# building lua-5.1.4
# 2008jul21
#
#####

# «install-5.1.4»  (to ".install-5.1.4")
# http://www.lua.org/ftp/lua-5.1.4.tar.gz
# (code-c-d "lua51" "~/usrc/lua-5.1.4/")
# (find-lua51file "")
# (find-lua51file "INSTALL")
# (find-lua51file "oml")
# (find-lua51file "src/Makefile")
# (find-node "(make)Phony Targets" "`.PHONY'")
#*
mkdir   ~/usrc/
rm -Rfv ~/usrc/lua-5.1.4/
mkdir   ~/usrc/lua-5.1.4/
tar  -C ~/usrc/ -xvzf $S/http/www.lua.org/ftp/lua-5.1.4.tar.gz
cd      ~/usrc/lua-5.1.4/

find * -name '*.[ch]' | sort > .files.ch   ;# (find-lua51file ".files.ch")
etags $(<.files.ch)			   ;# (find-lua51file "TAGS")
~/bin/patch-lua-5.1.3			   ;# (find-angg "bin/patch-lua-5.1.3")
#make linux test local |& tee omltl	   ;# (find-lua51file "omltl")

# «compile-5.1.4-lua_O0»  (to ".compile-5.1.4-lua_O0")
# (to "lua-api-from-gdb")
# (find-es "gdb" "macros")
# This block (optional) produces an unoptimized "lua" - "lua_O0" - for gdb.
# Note that its last (=3rd) line is a "make clean"...
{ make linux test MYEXTRACFLAGS="-gdwarf-2 -g3 -O0"
# make linux test MYEXTRACFLAGS="-ggdb -O0"
  mv -v src/lua src/lua_O0
  make clean
} |& tee oml0

make linux test local |& tee omltl	   ;# (find-lua51file "omltl")

cd src; ld -o liblua.so -shared $(ar t liblua.a); cd ..
cd src; install -p -m 0644 liblua.so ../lib; cd ..

#*
cd ~/usrc/lua-5.1.4/src/
cp -iv lua  ~/bin/lua51
cp -iv luac ~/bin/luac51

#*
# (find-lua51file "Makefile")
# (find-lua51file "Makefile" "local:")
# (find-lua51file "")
# (find-lua51sh "find bin include lib man share | sort")

# I have not adapted this to lua-5.1.4 yet:
#   (find-es "lua5" "compile-5.1.2-lua_O0")




#####
#
# Install lua-5.2.0-beta
# 2010nov21
#
#####

# «install-5.2-beta»  (to ".install-5.2-beta")
# http://www.lua.org/work/
# http://www.lua.org/work/lua-5.2.0-work2.tar.gz
# http://www.lua.org/work/lua-5.2.0-alpha-rc2.tar.gz
# http://www.lua.org/work/lua-5.2.0-alpha.tar.gz
# http://www.lua.org/work/lua-5.2.0-beta.tar.gz
#*
rm -Rv ~/usrc/lua-5.2.0-beta/
tar -C ~/usrc/ -xvzf \
  $S/http/www.lua.org/work/lua-5.2.0-beta.tar.gz
cd     ~/usrc/lua-5.2.0-beta/

find * -name '*.[ch]' | sort > .files.ch   ;# (find-lua52file ".files.ch")
etags $(<.files.ch)			   ;# (find-lua52file "TAGS")
# ~/bin/patch-lua-5.2			   ;# (find-angg "bin/patch-lua-5.2")
make linux test local |& tee omltl	   ;# (find-lua51file "omltl")

cd ~/usrc/lua-5.2.0-beta/src/
cp -v lua  ~/bin/lua52
cp -v luac ~/bin/luac52

#*
# (code-c-d "lua52" "~/usrc/lua-5.2.0-beta/")
# (find-lua52file "")
# (find-lua52file "src/lbitlib.c")
# (find-lua52file "src/lbitlib.c" "bitlib[] =")
* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
lua52
PP(bit32)


#*
* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
#*
rm -Rv ~/usrc/lua-5.2.0-work2/
tar -C ~/usrc/ -xvzf \
  $S/http/www.lua.org/work/lua-5.2.0-work2.tar.gz
cd     ~/usrc/lua-5.2.0-work2/

find * -name '*.[ch]' | sort > .files.ch   ;# (find-lua51file ".files.ch")
etags $(<.files.ch)			   ;# (find-lua51file "TAGS")
~/bin/patch-lua-5.2			   ;# (find-angg "bin/patch-lua-5.2")
make linux test local |& tee omltl	   ;# (find-lua51file "omltl")

cd ~/usrc/lua-5.2.0-work2/src/
cp -v lua  ~/bin/lua52
cp -v luac ~/bin/luac52

#*
# (code-c-d "lua52" "~/usrc/lua-5.2.0-work2/")
# (find-lua52file "")
# (find-lua52file "install")

* (eepitch-lua52)
* (eepitch-kill)
* (eepitch-lua52)
P(1, 2, 3)
PP(bit)




#####
#
# lua-5.2.0
# 2011dec16
#
#####

# «install-5.2»  (to ".install-5.2")
# (find-angg ".emacs" "lua-5.2")
# http://www.lua.org/ftp/lua-5.2.0.tar.gz
#*
rm -Rv ~/usrc/lua-5.2.0/
tar -C ~/usrc/ -xvzf \
  $S/http/www.lua.org/ftp/lua-5.2.0.tar.gz
cd     ~/usrc/lua-5.2.0/

find * -name '*.[ch]' | sort > .files.ch   ;# (find-lua52file ".files.ch")
etags $(<.files.ch)			   ;# (find-lua52file "TAGS")
# ~/bin/patch-lua-5.2			   ;# (find-angg "bin/patch-lua-5.2")
make linux test local |& tee omltl	   ;# (find-lua51file "omltl")

cd ~/usrc/lua-5.2.0/src/
cp -v lua  ~/bin/lua52
cp -v luac ~/bin/luac52

#*
# (code-c-d "lua52" "~/usrc/lua-5.2.0/")
# (find-lua52file "")






#####
#
# Rici Lake's lua-5.1+extensions
# 2006sep09
#
#####

# «install-5.1+ext»  (to ".install-5.1+ext")
# http://primero.ricilake.net/lua-5.1+extensions.tgz
# (find-fline "~/LOGS/2006sep08.lua" "lua-5.1+extensions.tgz")
# (code-c-d "lua51ext" "~/usrc/lua-5.1+extensions/")
# (find-lua51extfile "")
# (find-lua51extfile "README.patches")
# (find-lua51extfile "src/print.c" "static void PrintCodeRange")
# (find-lua51extfile "INSTALL")
# (find-lua51extfile "oml")
# (find-lua51extfile "src/")
# (find-lua51extfile "src/Makefile")
# (find-node "(make)Phony Targets" "`.PHONY'")
#*
mkdir   ~/usrc/
rm -Rfv ~/usrc/lua-5.1+extensions/
mkdir   ~/usrc/lua-5.1+extensions/
tar  -C ~/usrc/ -xvzf $S/http/primero.ricilake.net/lua-5.1+extensions.tgz
cd      ~/usrc/lua-5.1+extensions/

find * -name '*.[ch]' | sort > .files.ch
etags $(<.files.ch)

# (find-lua5file "INSTALL")
# (find-lua5file "config")
# (find-lua5file "etc/README")
# (find-lua5file "src/lib/loadlib.c")
cat >> config <<'%%%'

# --- Edrx's changes
# (find-lua5file "config" "dynamic loading on Unix systems")
LOADLIB= -DUSE_DLOPEN=1
DLLIB= -ldl
MYLDFLAGS= -Wl,-E
MYCFLAGS=-g
#
# (find-lua5file "config" "\n#USERCONF=")
USERCONF=-DLUA_USERCONFIG='"$(LUA)/etc/saconfig.c"' -DUSE_READLINE
EXTRA_LIBS= -lm -lreadline -ldl

INSTALL_EXEC= cp -v
INSTALL_DATA= cp -v
STRIP=echo NOT stripping:
INSTALL_BIN=$(HOME)/bin
INSTALL_INC=$(HOME)/include/lua5
INSTALL_LIB=$(HOME)/ulocal/lib
INSTALL_MAN=$(HOME)/ulocal/man/man1
%%%

make test	2>&1 | tee omt
ldd  bin/lua	2>&1 | tee ol
#make so	2>&1 | tee oms
#make install	2>&1 | tee omi
#make soinstall	2>&1 | tee omsi
# (find-lua5file "om")
# (find-lua5file "omi")
# (find-lua5file "omsi")

#*
make linux test |& tee oml

#*
cd ~/usrc/lua-5.1.1/src/
cp -iv lua  ~/bin/lua51
cp -iv luac ~/bin/luac51

#*





#####
#
# lua5.0beta with my patch to build `arg' before doing the options
# 2003jan18
#
#####

# «argpatch»  (to ".argpatch")
# (find-angg "LUA/lua50beta-argpatch.sh")
# (find-angg "LFORTH/README" "build-lua")
#*
rm -Rv ~/tmp/lua-5.0-beta/
mkdir  ~/tmp/lua-5.0-beta/
tar -xvzf $S/http/www.lua.org/ftp/lua-5.0-beta.tar.gz -C ~/tmp/
cd     ~/tmp/lua-5.0-beta/

# (find-lua50file "src/lua/lua.c" "other arguments; loop over them")
# (find-lua50file "src/lua/lua.c" "collect arguments")
# (find-lua50file "src/lua/lua.c" "lua.c-argpatch")
# (find-lua50file "src/lua/lua.c" "lua.c-argpatch2")
#
cp -iv src/lua/lua.c src/lua/lua.c.orig
cat ~/LUA/lua50beta-argpatch.sh
.   ~/LUA/lua50beta-argpatch.sh

# (find-lua50file "INSTALL")
# (find-lua50file "config")
# (find-lua50file "etc/README")
# (find-lua50file "etc/loadlib.c")
#
cat >> config <<'%%%'

# --- Edrx's changes
# (find-fline "config" "\n#USERCONF=")
USERCONF=-DLUA_USERCONFIG='"$(LUA)/etc/config.c"' -DUSE_READLINE -DUSE_LOADLIB
EXTRA_LIBS= -lm -lreadline -ldl
%%%

# To compile with debug information use the line with the `-g'.
make test
# make MYCFLAGS=-g test

# Ckeck if the patch works:
cd ~/tmp/lua-5.0-beta/
bin/lua -e 'print(arg and arg[1]) -- should print "foo"' /dev/null foo

cp bin/lua ~/bin/lua50argpatch

#*
# «argpatch-gdb»  (to ".argpatch-gdb")
set args -e 'print(arg and arg[1])' /dev/null foo
br handle_argv
run
p "argv[2]:"
p  argv[2]
p "argv[3]:"
p  argv[3]
# (eegud-gdb 'do-bounded "~/tmp/lua-5.0-beta/" "bin/lua")

#*
# «argpatch-recompile»  (to ".argpatch-recompile")
# (find-lua50file "src/lua/lua.c" "other arguments; loop over them")
# (find-lua50file "src/lua/lua.c" "collect arguments")
# (find-lua50file "src/lua/lua.c" "lua.c-argpatch")
# (find-lua50file "src/lua/lua.c" "lua.c-argpatch2")
cd ~/tmp/lua-5.0-beta/
touch src/lua/lua.c
make MYCFLAGS=-g test
bin/lua -e 'print(arg and arg[1])' /dev/null foo bar

#*




#####
#
# lua5.0: making an e-script version of the manual
# 2003jun29
#
#####

# «lua50ref.e»  (to ".lua50ref.e")
# (find-angg "LUA/lua50ref.e")
#*
lynx http://www.lua.org/ftp/
#*
gv $S/http/www.lua.org/ftp/refman-5.0.ps.gz &
#*
tar -tvzf $S/http/www.lua.org/ftp/lua-5.0.tar.gz
#*
cd $S/http/www.lua.org/ftp/
zcat refman-5.0.ps.gz | pstotext | tee refman-5.0.txt
# (find-fline "$S/http/www.lua.org/ftp/refman-5.0.txt")
#*
# (find-fline "~/LUA/lua50ref.e")
cp -iv $S/http/www.lua.org/ftp/refman-5.0.txt ~/LUA/lua50ref.e
#*

(find-shttpfile "www.lua.org/ftp/")
(find-es "lua5" "lua50ref.e")

(code-ps "lua50" "$S/http/www.lua.org/ftp/refman-5.0.ps.gz")
(find-lua50page 1)
emacs ~/LUA/lua50ref.e &

(progn
(fooi "’e" "é" "›c" "ç" "”a" "ã" "”o" "õ" "’o" "ó"
      "‘a" "à" "“a" "â" "’" "í" "’a" "á")
(fooi "Di#erent" "Different" "di#erent" "different" "o#cial" "official"
      "e#ects" "effects" "e#ectively" "effectively" "a#ecting" "affecting"
      " # " " -> " "a#ect" "affect" "e#cient" "efficient" "o#ers" "offers"
      "o#set" "offset" "di#erence" "difference" "turns o# " "turns off "
      "su#x" "suffix" "o#er" "offer")
(fooi "+ ­\n" "+ -\n" "MERCHANTABIL­\nITY" "MERCHANTABILITY"
      "proce­\ndural" "procedural" "auto­\nmatically" "automatically"
      "con­\ncatenation" "concatenation" "discus­\nsion" "discussion"
      "con­\nventional" "conventional" "assign­\nments" "assignments"
      "state­\nment" "statement" "arith­\nmetic" "arithmetic"
      "oper­\nadors" "operadors" "multipli­\ncation" "multiplication"
      "appro­\npriate" "appropriate" "garbage­\ncollection"
      "garbage-collection" "pseudo­\nindices" "pseudo-indices"
      "ready­\nto­use" "ready-to-use" "termi­\nnating" "terminating"
      "stan­\ndard" "standard" "imple­\nmented" "implemented"
      "mod­\nules" "modules" "ap­\nplication" "application"
      "char­\nacters" "characters" "repre­\nsents" "represents"
      "cap­\ntured" "captured" "nec­\nessary" "necessary"
      "genera­\ntor" "generator" "compil­\ners" "compilers"
      "de­\nscribing" "describing" "comple­\ntion" "completion"
      "unpro­\ntected" "unprotected" "pre­compile" "pre-compile"
      "re­\nturning" "returning" "oth­\nerwise" "otherwise"
      "mes­\nsage" "message" "pro­\ngrams" "programs" "func­\ntional"
      "functional" "corou­\ntines" "coroutines" "declara­\ntions"
      "declarations" "oper­\nators" "operators" "op­\neration"
      "operation" "com­\npared" "compared" "collec­\ntion"
      "collection" "trans­\nlates" "translates" "zero­\nterminated"
      "zero-terminated" "distribu­\ntion" "distribution"
      "environ­\nment" "environment" "infor­\nmation" "information"
      "pseudo­\nrandom" "pseudo-random" "de­\npends" "depends"
      "in­\nstead" "instead")
)

(progn
(fooi-re "\n\\([0-9]+\\)\n" "\n\n# «p\\1» (find-lua50page \\1)\n")
(fooi-re "§\\([0-9]+\\(\\.[0-9]+\\)*\\)" "(to \"sec\\1\")")
(save-excursion
  (ee-goto-position "\nIncompatibilities with")
  (fooi-re "\n\\([0-9]+\\(\\.[0-9]+\\)*\\) \\([A-Z][-­A-Za-z ]*\\)"
           "\n\n# «sec\\1»\n# «\\3»\n\n\\1 \\3\n")
  )
(save-excursion
  (ee-goto-position "\nStandard Libraries")
  (fooi-re "\n\n\\(\\. \\([a-zA-Z_.:]+\\)\\)"
           "\n\n# «\\2»\n\\1")
  )
(fooi-re "\n\\(``\\([a-z]*\\)'':\\)" "\n# «__\\2»\n\\1")
)

(ee-isearch "­\n")
(ee-isearch "­")
(fooi "­\n" "")
(fooi "­\n" "-")

(fooi "­" "-")

(fooi-re (concat "\n\\([0-9]+\\(?:\\.[0-9]+\\)*\\) \\([^\n]*\\)"
		 "\\(?: \\.\\)\\{7\\} \\([0-9]+\\)")
	 "\n\\1 \\2 \\3 (to \"sec\\1\")")



(progn (jump-to-register ?a) (ee-isearch "­\n"))

egrep '^[0-9]+$' ~/tmp/luaref.txt | l -S

#*
cd
tclsh ~/TH/Generate LUA/lua50ref.e.html "a2html LUA/lua50ref.e"
cp -v ~/LUA/lua50ref.e{,.html} ~/TH/L/LUA/
#*
lynx ~/TH/L/LUA/lua50ref.e.html
#*
cd ~/LUA/
echo 'l $passwd(puc)' > $EEG
Scp -C lua50ref.e{,.html} edrx@${SUCURI}:slow_html/LUA/
#*
cd ~/LUA/
anonftp angg.twu.net 'cd ~/slow_html/LUA/' \
  'put lua50ref.e' \
  'put lua50ref.e.html' \
  quit
#*
# Then do the usual "makepage"/"makepage; makeindexhtmls" at twu and
# at mat.puc-rio to copy from slow_html to public_html, and...
#
lynx "http://angg.twu.net/LUA/lua50ref.e.html#For Statement"
lynx "http://www.mat.puc-rio.br/~edrx/LUA/lua50ref.e.html#For Statement"





#####
#
# Invoking arrays
# 2003jan08
#
#####

# «invoking-arrays»  (to ".invoking-arrays")
# (find-lua50ref "__call")
# (find-lua50ref "setmetatable")
# (find-lua50ref "sec3.7")
#*
lua50 -e '
  arr = {}				-- (find-lua50ref "sec3.7")
  setmetatable(arr, arr)		-- (find-lua50ref "setmetatable")
  arr.__call = print			-- (find-lua50ref "__call")
  arr(20, 30, 40)			--> table:0xxxxxxxxx 20 30 40

  arr.name = "<arr>"
  arr.__call = function (arr, ...)
      print(arr.name, unpack(arg))
    end
  arr(20, 30, 40)			--> <arr> 20 30 40
'
#*
lua50 -e '
  a = {}
  mt = {}
  setmetatable(a, mt)
  mtset = function (mtfield)
      mt[mtfield] = function (...) P(mtfield, unpack(arg)) end
    end
  mtset("__add"); b = a + 1
  mtset("__sub"); b = a - 2
  mtset("__mul"); b = a * 3
  mtset("__div"); b = a / 4
  mtset("__pow"); b = a ^ 5
  mtset("__unm"); b =   - a
  mtset("__concat"); b = a .. 6
  mtset("__eq");  b = a == a
  mtset("__lt");  b = a <  9
  mtset("__le");  b = a <= 10
'
#*

  mtset("__concat"); b = a[20]
  mtset("__eq"); b = a[20]
  mtset("__lt"); b = a[20]
  mtset("__le"); b = a[20]
  mtset("__index"); b = a[20]
  mtset("__newindex"); b = a[20]
  b = a[20]



# (find-lua50file "src/")

# (find-lua50file "src/lapi.c" "lua_getmetatable")
# (find-lua50file "src/lobject.h" "typedef struct Table")
# (find-lua50file "src/ltests.c" "static int metatable")
# (find-lua50file "src/ltm.c")
# (find-lua50file "src/lvm.c")
# (find-lua50file "src/lvm.c" "case OP_CALL:")

# (find-lua50file "src/lobject.h" "#define hvalue(o)")



#####
#
# string.find
# 2003mar12
#
#####

# «string.find»  (to ".string.find")
# (find-lua50ref "String Manipulation" "string.find")
# string.find (s, pattern [, init [, plain]])
#   --> begpos endpos captstr1 captstr2 ...
#*
lua50e 'P(string.find("0123456789", "3(45)(67)", 4))	--> 4 8 "45" "67"'
lua50e 'P(string.find("0123456789", "3(45)(67)", 5))	-->'
#*
# «string.gfind»  (to ".string.gfind")
# (find-lua50ref "String Manipulation" "string.gfind")
lua50e 'for w,s in string.gfind("aa!b!!c", "([^!]*)(!?)") do P(w, s) end'
lua50e 'for w,s in string.gfind("aa!b!!c!", "([^!]*)(!?)") do P(w, s) end'
#*



#####
#
# empty captures in patterns
# 2004jan14
#
#####

# «emptycaptures»  (to ".emptycaptures")
# (find-lua50ref "String Manipulation" ". string.find")
# (find-lua50ref "Captures" "the empty capture ()")
# (to "split")
#*
lua50e '
  P(string.find("abbc", "()(b+)()", 1))   --> 2 3  2 "bb" 4
  P(string.find("abbc", "()(b+)()", 2))   --> 2 3  2 "bb" 4
  P(string.find("abbc", "()(b+)()", 3))   --> 3 3  3 "b" 4
  P(string.find("abbc", "()(b+)()", 4))   -->
'
#*
lua50e '
split = function (str)
    local arr, pos = {}, 1
    while 1 do
      local _, __, word, newpos = string.find(str, "^[%s]*([^%s]+)()", pos)
      if newpos then table.insert(arr, word); pos = newpos
      else return arr
      end
    end
  end
PP(split(" abc  de "))
'
#*



#####
#
# 0-based string positions
# 2003mar14
#
#####

# «0-based»  (to ".0-based")
# (find-angg "LUA/lua50init.lua" "0-based")
# (find-lua50ref "string.sub")
# (find-lua50ref "string.find")
# (find-lua50ref "string.byte")
#*
lua50e 'P(string.sub("012345678", 1+2, 7))		--> "23456"'
lua50e 'P(string.find("012345678", "^(23456)", 1+2))	--> 1+2 7 "23456"'
lua50e 'P(string.byte("012345678", 1+4))		--> ?0+4'
#*

* (eepitch-lua)
P(string.sub("012345678", 1+2, 7))             --> "23456"
P(string.find("012345678", "^(23456)", 1+2))   --> 1+2 7 "23456"
P(string.byte("012345678", 1+4))               --> ?0+4







#####
#
# Functions with a variable number of parameters
# 2003mar13
#
#####

# «vararg»  (to ".vararg")
# (find-lua50ref "__call")
# (find-lua50ref "Function Definitions" "arg={5, 8; n=2}")




#####
#
# arg
# 2004sep07
#
#####

# «lua-arg»  (to ".lua-arg")
# (find-man "1 lua")
# (find-luafile "src/lua/lua.c" "\"arg\"")
# (find-zshnode "Process Substitution")
#*
lua50   -e 'PP(arg)'
lua50 =(<<<'PP(arg)') Arg1 Arg2
lua50 =(<<<'print(unpack(arg))') Arg1 Arg2
#*




#####
#
# pack and unpack
# 2007nov26
#
#####

# «pack-and-unpack»  (to ".pack-and-unpack")
# (find-angg "LUA/lua50init.lua" "pack-and-unpack")
# (find-luamanualw3m "#pdf-unpack")
# (find-luamanualw3m "#7.1" "pseudo-argument arg")
# (find-lua51grep "grep -nH -e LUA_COMPAT_VARARG $(cat .files.ch)")
# (find-lua51file "src/ldo.c" "LUA_COMPAT_VARARG")
# (find-lua51file "src/luaconf.h" "LUA_COMPAT_VARARG")
# http://www.lua.org/source/5.1/ldo.c.html#adjust_varargs
# (find-pilw3m "index.html")
# (find-pilw3m "5.2.html" "Variable Number of Arguments" "arg={5, 8; n=2}")

The "arg" table is not discussed much in the reference manual for
lua-5.1... I haven't checked this very thoroughly, but I think that
"arg" is mentioned only at the "Incompatibilities with the Previous
Version" section.

For some reason people don't like the old idea of keeping the size of
an array at its ".n" field, and weird alternatives like having a
different kind of "nil" that is not seen as a "hole" pop up at the
mailing list all the time.

To do: find a link to some recent thread about these "alternative
nils" at the mailing list archive.

  http://lua-users.org/lists/lua-l/

To do: replace the "unpack"s in the init file by "myunpack"s, and the
"return unpack(arg)"s by "return ..."s; also, check for 5.0-isms, and
and for old scripts still lying around that may still be lua-5.0
based.

# «pack-and-unpack-test»  (to ".pack-and-unpack-test")
# (find-lua50manualw3m "#pdf-type" "unpack (list)")
# (find-lua50manualw3m "#getn")
# (find-lua51manualw3m "#pdf-unpack")
# (find-lua52manualw3m "#pdf-table.unpack")
# (find-lua52manualw3m "#pdf-table.pack")
# (find-lua50manualw3m "" "LUA_INIT")
# (find-lua51manualw3m "" "LUA_INIT")
# (find-lua52manualw3m "" "LUA_INIT")

# (find-fline "~/usrc/lua-5.0.3/bin/")
# (find-fline "~/usrc/lua-5.1.4/bin/")
# (find-fline "~/usrc/lua-5.2.0/install/bin/")








#####
#
# Some librarish functions
# 2003jan18
#
#####

#*
# «envsubst»  (to ".envsubst")
# (find-angg "LUA/lua50init.lua" "envsubst")
# (find-lua50ref "String Manipulation" "string.gsub")
# (find-lua50ref "Character Class")
# (find-lua50ref "Basic Functions" "ipairs")
# (find-lua50ref "Operating System Facilities" "os.getenv")
#
lua50e 'P(arg[1], string.gsub(arg[1], "%$(%w+)", os.getenv))' '$HOME/LUA/'
lua50e 'setenv_ = {}
        setenv = function (varname, value) setenv_[varname] = value end
        envsubst = function (str)
            return string.gsub(str, "%$([%a_][%w_]*)", function (e)
                return (setenv_ and setenv_[e]) or os.getenv(e) or ""
              end)
          end
        for i,v in ipairs(arg) do P(arg[i], envsubst(arg[i])) end
       ' '$HOME/LUA/' '$BADVAR/foo' '$0w$_Ax0y$//'

#*
# «readfile»  (to ".readfile")
# «writefile»  (to ".writefile")
# (find-angg "LUA/lua50init.lua" "readfile")
# (find-lua50ref "file:read")
# (find-lua50ref "io.open")
# (find-lua50file "src/lib/liolib.c" "io_open")
#
echo hi > /tmp/smallfile
rm -v     /tmp/smallfile-w
lua50e 'readfile = function (fname)
            local f = assert(io.open(fname, "r"))
            local bigstr = f:read("*a")
            f:close()
            return bigstr
          end
        writefile = function (fname, bigstr)
            local f = assert(io.open(fname, "w+"))
            f:write(bigstr)
            f:close()
          end
        P(readfile("/tmp/smallfile"))
	P(writefile("/tmp/smallfile-w", "www\n"))
        P(readfile("/tmp/doesnotexist"))
       '

#*
# «mytostring»  (to ".mytostring")
# (find-angg "LUA/lua50init.lua" "mytostring")
# (find-lua50ref "table.sort")
# (find-lua50ref "tostring")
# (find-lua50ref "string.format")
lua50e '
mysort = function (origtable)
    local tmptable = {}
    for key,val in pairs(origtable) do
      table.insert(tmptable, {key=key, val=val})
    end
    local comp = function (item1, item2)
        local key1, key2 = item1.key, item2.key
        local type1, type2 = type(key1), type(key2)
        if type1==type2 then
          if type1=="number" then return key1 < key2 end
          if type1=="string" then return key1 < key2 end
          return tostring(key1) < tostring(key2)
        else
          return type1<type2
        end
      end
    table.sort(tmptable, comp)
    return tmptable
  end
mytostring = function (v)
    local t = type(v)
    if t=="number" then return tostring(v) end
    if t=="string" then return format("%q", v) end
    if t=="table" then
      local tmptable = mysort(v)
      local bigstring = "{"
      local sep = ""
      for i = 1, table.getn(tmptable) do
        local entry = tmptable[i]
        local keystr, valstr = mytostring(entry.key), mytostring(entry.val)
        bigstring = bigstring..sep..keystr.."="..valstr
        sep = ", "
      end
      return bigstring .. "}"
    end
    return "<"..tostring(v)..">"
  end

print(mytostring({30, "a", [function () end]={true, false}}))
'
#*
# «split»  (to ".split")
# (find-angg "LUA/lua50init.lua" "split")
# (to "emptycaptures")
lua50e '
split = function (str)
    local arr = {}, 1
    string.gsub(str, "([^%s]+)", function (word)
        table.insert(arr, word)
      end)
    return arr
  end
PP(split(" abc  de "))
'
#*




#####
#
# the several flavors of "for"
# 2003feb27
#
#####

# «for»  (to ".for")
# (find-luamanualw3m+ "for")
#*
lua50e 'for i=1,4 do P(i) end'                          ;# 1 2 3 4
lua50e 'for i=5,-2,-2 do P(i) end'                      ;# 5 3 1 -1
lua50e 'for i=2,2 do P(i) end'                          ;# 2
lua50e 'for i=2,0 do P(i) end'                          ;#
lua50e 'for key,val in {4,5,k="K"} do P(key, val) end'  ;# 1 4 / 2 5 / "k" "K"
lua50e 'a={4,5,k="K"}; for i=1,table.getn(a) do P(i, a[i]) end'  ;# 1 4 / 2 5

#*
# (find-lua50ref "next")
#
lua50e 'a={4,5,k="K"}; P(next(a))'
lua50e 'a={4,5,k="K"}; i=nil
        P(next(a,i)); i=next(a,i)
        P(next(a,i)); i=next(a,i)
        P(next(a,i)); i=next(a,i)
        P(next(a,i)); i=next(a,i)
       '
#*
# (find-luamanualw3m+ "for")
# (find-luamanualw3m+ "#2.4.5")
# (find-lua50ref "For Statement" "generators")
# (find-lua50ref "For Statement" "generators" "equivalent to")
# (find-lua50ref "Basic Functions" ". ipairs")
# (find-lua50ref "Basic Functions" ". pairs")
#
lua50e 'a={4,5,k="K"}; for key,val in        a  do P(key,val) end'
lua50e 'a={4,5,k="K"}; for key,val in  pairs(a) do P(key,val) end'
lua50e 'a={4,5,k="K"}; for key,val in ipairs(a) do P(key,val) end'
lua50e 'a={4,5,k="K"}; P(ipairs(a))'
lua50e 'a={4,5,k="K"}; f,state,key=ipairs(a); PP(ipairs(a))
        key,val=f(state,key); PP(f,state,key,val)
        key,val=f(state,key); PP(f,state,key,val)
        key,val=f(state,key); PP(f,state,key,val)
'
#*
# (find-lua50ref "table.foreach")
# (find-lua50ref "table.foreachi")
# (find-lua50ref "io.lines")

  * explist is evaluated only once. Its results are an iterator function, a 
    state, and an initial value for the first iterator variable.
  * _f and _s are invisible variables. The names are here for explanatory
    purposes only.
  * The behavior is undefined if you assign to var_1 inside the block.
  * You can use break to exit a for loop.
  * The loop variables var_i are local to the statement; you cannot use their
    values after the for ends. If you need these values, then assign them to
    other variables before breaking or exiting the loop.

#*
# (find-luamanualw3m+ "for" "The generic for statement")
# (find-luamanualw3m+ "for" "iterator function,")
# (find-luamanualw3m+ "next")
# (find-lua50tag "luaB_next")
# (find-lua50tag "lua_next")
# (find-lua50tag "luaH_next")
lua50e '
  PP(ipairs({10, 20}))    --> <function> {1=10,2=20} 0
  itf, state, v = ipairs({10, 20})
  PP(itf 
'

#*
lua50e '
  T = {10,20}
  f, s, a0 = ipairs(T);  PP(f, s, a0)      --> <function> {1=10,2=20} 0
  a1, b1, c1 = f(s, a0); PP(a1, b1, c1)	   --> 1 10 nil
  a2, b2, c2 = f(s, a1); PP(a2, b2, c2)	   --> 2 20 nil
  a3, b3, c3 = f(s, a2); PP(a3, b3, c3)	   --> nil
'
#*
lua50e '
  T = {b="B", a="A"}
  f, s, a0 = pairs(T);  PP(f, s, a0)      --> <function> {"a"="A","b"="B"}
  a1, b1, c1 = f(s, a0); PP(a1, b1, c1)	   --> "a" "A" nil
  a2, b2, c2 = f(s, a1); PP(a2, b2, c2)	   --> "b" "B" nil
  a3, b3, c3 = f(s, a2); PP(a3, b3, c3)	   --> nil
'
#*
# «each2»  (to ".each2")
# (find-angg "LUA/lua50init.lua" "each2")
# (find-pilw3m "7.1.html" "Iterators and Closures")

* (eepitch-lua51)

each2 = function (tbl)
    local i = 1
    return function ()
        if i <= table.getn(tbl) then
          i = i + 2
          return tbl[i - 2], tbl[i - 1]
        end
      end
  end

for a,b in each2(split("aa bb cc dd ee ff")) do print(a, b) end






f, s, a0 = iterator(); PP(f, s, a0)
a1, b1, c1 = f(s, a0); PP(a1, b1, c1)
a2, b2, c2 = f(s, a1); PP(a2, b2, c2)
a3, b3, c3 = f(s, a2); PP(a3, b3, c3)

while true do



#*
       do
         local _f, _s, var_1 = explist
         local var_2, ... , var_n
         while true do
           var_1, ..., var_n = _f(_s, var_1)
           if var_1 == nil then break end
           block
         end
       end



it, st, iv

#*







#####
#
# LUA_PATH and require
# 2003mar16
#
#####

# «require»  (to ".require")
# (find-angg "dednat/dednat3.lua" "luahead" "LUA_PATH")
# (find-lua50ref "require")
# (find-lua50file "src/lib/lbaselib.c" "static int luaB_require")
# (find-lua50file "src/lib/lbaselib.c" "#define LUA_PATH_DEFAULT")
# (find-lua50file "src/lib/lbaselib.c" "getenv(LUA_PATH)")
# (find-lua50file "src/lib/lbaselib.c" "static const char *getpath")
# (find-lua50file "src/lua/lua.c")
#*
echo 'PP(arg)' > /tmp/t.lua
lua50 /tmp/t.lua
cd /tmp/
lua50 t.lua
lua50e 'PP(string.find("/tmp/t.lua", "^(.*)/([^/]*)$"))'
lua50e 'PP(string.find(     "t.lua", "^(.*)/([^/]*)$"))'
#*
cat > /tmp/t.lua <<'%%%'
do local _, __, arg0path = string.find(arg[0], "^(.*)/[^/]*$")
   if arg0path then
     LUA_PATH = (LUA_PATH or getenv("LUA_PATH") or "?;?.lua")..
                ";"..arg0path.."/?"
   end
end
PP(arg)
require "u.lua"
%%%

cat > /tmp/u.lua <<'%%%'
PP(_REQUIREDNAME)
print "u!"
%%%

lua50 /tmp/t.lua
#*

# For, e.g., ".so"s for loadlib:
# scriptpwd = arg0path or "."




#####
#
# "require" and the "package" table in lua5.1
# 2007mar06
#
#####

# «lua5.1-require»  (to ".lua5.1-require")
# http://www.inf.puc-rio.br/~roberto/pil2/chapter15.pdf
# (find-books "__comp/__comp.el" "ierusalimschy")
# (find-pil2page (+ 19 137)  "15. Modules and Packages")
# (find-pil2page (+ 19 138)   "15.1 The require Function")
# (find-pil2text (+ 19 138)   "15.1 The require Function")
# (find-lua51manual "#pdf-require")
# (to "compat-5.1")

# (find-compat51file "")
# (find-compat51file "compat-5.1.lua")
# (find-compat51file "compat-5.1.lua" "LUA_PATH")
# (find-lua51file "")
# (find-lua51tag "ll_require")

# «lua5.1-package»  (to ".lua5.1-package")
* (eepitch-lua51)
loadcinvoke()
for k,v in pairs(package) do print(k) end
PP(package.preload)
PP(package.loadlib)
for k,v in pairs(package.loaded) do print(k) end
= package.loaded.cinvoke_lua
PP(package.loaders)
= package.cpath
= package.config
= package.path
= package.seeall






#####
#
# Recompiling .so's for lua4.0 for lua5.0
# 2003mar18
#
#####

# (find-lua50file "include/lauxlib.h" "Compatibility macros")
#*
rm -Rv ~/include/lua50/
mkdir  ~/include/lua50/
cd     ~/include/lua50/
cp -iv $LUA50SRC/include/* .
cp -iv lauxlib.h lauxlib.h.orig
# (find-fline "~/include/lua50/lauxlib.h" 122)
# (find-fline "~/include/lua50/lauxlib.h.orig" 122)
patch -p0 lauxlib.h <<'%%%'
122c122
< /*
---
> #ifdef LAUXLIBCOMPAT
134c134
< */
---
> #endif
%%%

#*




#####
#
# loadlib on lua-5.0
# 2003sep19
#
#####

# «loadlib2»  (to ".loadlib2")
# (find-lua50file "src/lib/loadlib.c")
# (find-lua50file "include/")
#*
cd /tmp/
export LUA50SRC=$HOME/tmp/lua-5.0

cat > so.c <<'%%%'
#include <lauxlib.h>
#include <stdio.h>
static int my_foo(lua_State* L) {
  int n = lua_gettop(L);
  int isnum = lua_isnumber(L, 1);
  int m = lua_tonumber(L, 1);
  printf("Hi hi!\n");
  printf("%d %d %d!\n", n, isnum, m);
  return 0;
}

LUALIB_API int my_init(lua_State *L) {
  lua_register(L, "foo", my_foo);
  return 0;
}
%%%
gcc -g -Wall -shared -I$LUA50SRC/include -o so.so so.c

# (find-lua50ref "Defining C Functions" "lua_register")

cat > loadso.lua <<'%%%'
assert(loadlib("/tmp/so.so", "my_init"))()
foo(22)
%%%

$LUA50SRC/bin/lua /tmp/loadso.lua

#*
# (find-efunction 'eegud-gdb)
# (eegud-gdb t ee-lua50dir "bin/lua")
set args /tmp/loadso.lua
# br main
br loadlib
run
n
n
n
br my_foo
cont

#*





#####
#
# luaL_openlib - for lua_register'ing each function in an array
# 2004jan06
#
#####

# «luaL_openlib»  (to ".luaL_openlib")
# (find-lua50file "src/lib/lbaselib.c" "luaL_reg base_funcs[] =")
# (find-lua50file "src/lib/lbaselib.c" "luaL_openlib(L, NULL, base_funcs, 0)")
# (find-lua50file "include/lauxlib.h" "luaL_openlib")
# (find-lua50tag "luaL_openlib")

# (find-lua50file "src/lib/loadlib.c")
# (find-lua50file "include/")
# (find-lua50ref "Defining C Functions" "#define lua_register(L,n,f)")
# (find-fline "/tmp/luabit/lbitlib.c")
#*
rm -Rv /tmp/dummylib/
mkdir  /tmp/dummylib/
cd     /tmp/dummylib/

cat > dummylib.c <<'%%%'
#include "lauxlib.h"
#include <stdio.h>
static int my_foo(lua_State* L) {
  lua_pushnumber(L, 33);
  lua_pushnumber(L, 333);
  return 2;
}
static const struct luaL_reg bitlib[] = {
{"foo", my_foo},
{NULL,  NULL}
};
LUALIB_API int my_init(lua_State *L) {
  lua_pushvalue(L, LUA_GLOBALSINDEX);
  luaL_openlib(L, NULL, bitlib, 0);
  return 0;
}
%%%

# (find-lua50tag "luaL_openlib")

export LUA50SRC=$HOME/tmp/lua-5.0
gcc -g -Wall -shared -I$LUA50SRC/include -o dummylib.so dummylib.c

cat > testlib.lua <<'%%%'
assert(loadlib("/tmp/dummylib/dummylib.so", "my_init"))()
print(foo(44))
print("ok")
%%%

lua50 /tmp/dummylib/testlib.lua

#*




#####
#
# pio_fontx on lua-5.0
# 2003sep19
#
#####

# «pio_fontx»  (to ".pio_fontx")
# (find-fline "~/vtutil/")
# (find-fline "~/vtutil/Makefile")
# (find-fline "~/vtutil/vtutil.lua" "loadextension")
# (find-fline "~/vtutil/pio_fontx.c")
# (find-fline "$LUA50SRC/")
#*
# (find-fline "~/vtutil/Makefile" "pio_fontx.so:")
cd ~/vtutil/
gcc -Wall -shared -I$HOME/include/lua50 -DLAUXLIBCOMPAT \
  -o /tmp/pio_fontx50.so pio_fontx.c
#*
# (find-lua50file "")
# (find-lua50file "etc/loadlib.c")
lua50e 'assert(loadlib("/tmp/pio_fontx50.so", "pio_fontx_init"))()'
#*
# (find-fline "~/include/lua50/")
#*
cd /tmp/

cat > pio_fontx.c <<'%%%'
#include <lua.h>
#include <lauxlib.h>
#include <sys/ioctl.h>
#include <linux/kd.h>

#include <unistd.h>
#include <string.h>
#include <errno.h>
/* #include <fcntl.h>
 * #include <stdio.h>
 * (find-lua50ref "Querying the Stack")
 * (find-lua50ref "Getting Values from the Stack")
 * (find-lua50file "src/lib/loadlib.c" "luaL_checkstring")
 * (find-lua50file "src/lib/")
 * (find-lua50file "include/")
 * (find-lua50file "include/lua.h")
 * (find-lua50file "include/lauxlib.h" "checkint")
 * (find-vtutilfile "pio_fontx.c")
 */

static int lua_pio_fontx(lua_State* L) {
  struct consolefontdesc cfd;
  int len;
  cfd.chardata = (char *) luaL_checklstring(L, 1, &len);
  cfd.charcount = luaL_checkint(L, 2);
  cfd.charheight = luaL_checkint(L, 3);
  if(ioctl(STDIN_FILENO, PIO_FONTX, &cfd)) {
    lua_pushstring(L, strerror(errno));
    return 1;
  }
  return 0;
}

LUALIB_API int pio_fontx_init(lua_State *L) {
  lua_register(L, "pio_fontx", lua_pio_fontx);
  return 0;
}
%%%
gcc -g -Wall -shared -I$LUA50SRC/include -o pio_fontx.so pio_fontx.c

# (find-lua50ref "Defining C Functions" "lua_register")

cat > loadso.lua <<'%%%'
assert(loadlib("/tmp/pio_fontx.so", "pio_fontx_init"))()
print(pio_fontx)
%%%

$LUA50SRC/bin/lua /tmp/loadso.lua

#*





#####
#
# mailing list archive
# 2003mar01
#
#####

# «mailing-list-archive»  (to ".mailing-list-archive")
# http://www.lua.org/ftp/
#*
cd $S/http/www.lua.org/ftp/
zcat lua-l-archive.gz > /tmp/lua-l-archive
cd /tmp/
laf /tmp/lua-l-archive
#*
mutt -R -f /tmp/lua-l-archive
#*
rm -v /tmp/lua-l-archive
#*
# (find-fline "/tmp/lua-l-archive")





####
#
# Lua's magical hash algorithm
# 2003mar01
#
####

# «hash»  (to ".hash")
# (find-lua50file "src/ltable.c" "then the colliding element")

# (find-shttpw3 "www.citi.umich.edu/projects/linux-scalability/reports/hash-email.html")

i re-read Knuth over dinner last night. unfortunately, he is
discussing hashes where you store data elements right in the hash
table, and can then easily do linear probing [i heard that, you in the
second row]. i can't think of a good way to apply his double hashing
algorithm (algorithm D, p. 528) or Brent's variation (p. 532) to help
improve the hash function without using a multiplicative hash.

cd /tmp/
wget http://www-cs-faculty.stanford.edu/~knuth/err3-1e.ps.gz
gv -page 52 /tmp/err3-1e.ps.gz

Page 526 new paragraph after line 19 29 Nov 1977

E. G. Mallach [Comp. J. 20 (1977), 137-140] has experimented with
refinements of Brent's variation, and further results have been
obtained by Gaston H. Gonnet and J. Ian Munro [SICOMP 8 (1979),
463-478].




#####
#
# how efficient is table.insert(tbl, x, 1)?
# 2003mar13
#
#####

# (find-lua50file "src/ltable.c")
# (find-lua50file "src/lib/ltablib.c" "\nstatic int luaB_tinsert")
# Well, it's not linear time stuff...




#####
#
# io.output
# 2003jul10
#
#####

# «io.output»  (to ".io.output")
# (find-lua50ref "sec5.6" ". io.open (filename [, mode])")
# (find-lua50file "src/lib/liolib.c" "static int io_open")
# (find-node "(libc)Opening Streams")

# (find-lua50ref "sec5.6" ". io.output ([file])")
# (find-lua50ref "sec5.6" ". io.input ([file])")
# (find-lua50file "src/lib/liolib.c" "static int io_output")
# (find-lua50file "src/lib/liolib.c" "static int g_iofile")
# (find-lua50file "src/lib/liolib.c" "static int io_write")
# (find-lua50file "src/lib/liolib.c" "static int g_write")
# (find-lua50file "src/lib/lbaselib.c" "static int luaB_print")
#*
rm -Rv /tmp/io.output/
mkdir  /tmp/io.output/
cd     /tmp/io.output/
lua50e '
  print   ("hi")
  io.write("hi 2\n")
  io.flush()
  io.output("out")	-- same as io.output(assert(io.open("out", "w")))
  print   ("hi 3\n")	-- not redirected; uses fputs(s, stdout)
  io.write("hi 4\n")	-- redirected; uses g_write(L, getiofile(...), ...)
  io.flush()
'
laf
#*

# (find-lua50ref "sec5.6" ". file:write (value1, ...)")
# (find-lua50ref "sec5.6" ". io.write (value1, ...)")





#####
#
# vmmerge5.lua
# 2006aug10
#
#####

# «vmmerge5.lua»  (to ".vmmerge5.lua")
# http://lua-users.org/wiki/VmMerge
# http://lua-users.org/files/wiki_insecure/users/theoddone33/vmmerge5.lua
#*
# Install at ~/bin/ (2006aug10)
{
  echo '#!/usr/bin/env lua50'
  echo '-- (find-es "lua5" "vmmerge5.lua")'
  echo
  cat $S/http/lua-users.org/files/wiki_insecure/users/theoddone33/vmmerge5.lua
}       > ~/bin/vmmerge5.lua
chmod 755 ~/bin/vmmerge5.lua

#*
# Inspect and test:
# (find-fline "~/bin/vmmerge5.lua")
# (find-sh "vmmerge5.lua --file ~/blogme/blogme2.lua")
# (find-sh          "luac -p -l ~/blogme/blogme2.lua")
# (find-fline "~/blogme/blogme2.lua")

<edrx> ok, I'm inspecting the disassembled bytecode for a lua script
       to try to understand how a closure gets the name that is
       displayed on tracebacks...
<Keffo> hmm, wtf is this.. http://www.ubuntu.org/
<Keffo> edrx: Why do you care? :)
<edrx> my only guess at the moment - if the disassembled bytecode
       really shows everything that the bytecode has - is that
       closures are born without names, and "setglobal" notice when
       they are assigning unnamed closures to (named) variables and
       set the name of the closure...
<edrx> but that seems a bit inneficient
<edrx> Keffo: I care because this is one of the two main things that I
       don't understand about Lua and that I have to confess that I
       don't know when I explian Lua to people or give talks about it
       (I gave a few at free software events)

# (find-lua50file "")
# (find-lua50grep "grep -nH -e closure $(cat .files.ch)")
# (find-lua50grep "grep -nH -e LClosure $(cat .files.ch)")
# (find-lua50tag "LClosure")
# (find-lua50grep "grep -nH -e traceback $(cat .files.ch)")
# (find-lua50tag "errorfb")
# (find-lua50file "src/lib/ldblib.c" "\" in function `%s'\", ar.name")

setglobal
closure




#####
#
# vmmerge
# 2003jan08
#
#####

# «vmmerge»  (to ".vmmerge")
# http://lua-users.org/wiki/VmMerge
# http://lua-users.org/files/wiki_insecure/users/ntrout/vmmerge.lua
#*
cat $S/http/lua-users.org/files/wiki_insecure/users/ntrout/vmmerge.lua \
  | tr -d '\r' \
  > ~/LUA/vmmerge5.lua
#*
# (find-fline "~/LUA/vmmerge5.lua")
# (find-fline "~/LUA/vmmerge5.lua" "local cmd = \"luac")
ln -sf ../tmp/lua-5.0-beta/bin/luac ~/bin/luac50
#*
cd ~/LUA/
cat > /tmp/test.lua <<'%%%'
print(1+2)
%%%
lua50 -l ~/tmp/lua-5.0-beta/test/compat.lua vmmerge5.lua \
  --file /tmp/test.lua
#*
cat > /tmp/test.lua <<'%%%'
a = {
  1+2,
  3
}
print(a[2])
%%%
lua -f $S/http/lua-users.org/files/wiki_insecure/users/ntrout/vmmerge.lua \
  --file /tmp/test.lua --fmt merge
#*
echo 'a={}; a(4)' | luac50 -
rm luac.out
cat luac.txt
#*
# (find-lua50file "")
# (find-lua50file "src/lvm.c" "case OP_CALL:")




#####
#
# Suggestions
# 2003mar18
#
#####

# «suggestions»  (to ".suggestions")

Add #ifdefs that activate the compatibily block of lauxlib.h.

Build the array "arg" before running the first "-e".

Allow things like ``while a=f() do ... end'', and maybe something
similar for `if' and `elseif' too.

Power patch: add a way to let the interpreter be a pointer to a
function instead of a fixed function

Power patch: add a keyword that when parsed interrupts the execution
of the interpreter, to let us examine its state

Power patch: create an interpreter that can be interrupted and resumed

Power patch: add a "tfunction" keyword that behaves like "function",
but if a certain global variable ("tfunctionfunction"?) exists it
invokes it just after building the bytecode for the function. For
example, in ``unnamedfunctions["3"] = tfunction return 1+2 end'' we
would have the call ``tfunctionfunction(bytecode, chunk, begpos,
endpos)'', where bytecode is the code for ``function return 1+2 end'',
chunk is the string from where that all came and begpos and endpos are
the positions of the ``tfunction return 1+2 end'' in the string. By
the way: the reason why I want such a beast (tfunction) is that I'd
like to keep a weak table with the source code of the ``user-defined
primitives'' in LForth, that are built from strings in complicated
way.

# (find-lua50file "src/")
# (find-lua50file "src/lparser.c")
# (find-lua50file "src/lcode.c")
# (find-lua50file "src/lib/lbaselib.c" "luaB_loadstring")





#####
#
# tolua-5.0
# 2003dec27
#
#####

# «tolua-5.0»  (to ".tolua-5.0")
# (code-c-d "tolua" "~/usrc/tolua-5.0/")
# (find-toluafile "")
# (find-toluafile "src/tests/")
#*
rm -Rv ~/usrc/tolua-5.0/
cd ~/usrc/
tar -xvzf $S/ftp/ftp.tecgraf.puc-rio.br/pub/users/celes/tolua/tolua-5.0.tar.gz
cd ~/usrc/tolua-5.0/
patch -p0 config <<'%%%'
24c24
< LUA=/home/celes/lua-5.0
---
> LUA=$(HOME)/tmp/lua-5.0
%%%

make |& tee om

# (find-toluafile "Makefile")

#*
cd ~/usrc/tolua-5.0/
make tests |& tee omtests
# Fails and aborts at the "tvariable" test,
# so below we redo it in a more careful way.
# (find-toluafile "omtests")

#*
cd ~/usrc/tolua-5.0/src/tests/
# (find-toluafile "src/tests/Makefile")
make clean klean
rm -fv *.log
rm -fv *.log.FAILED
for i in tmodule tnamespace tclass tconstant tfunction tarray; do
  (setopt -v; make $i && ./$i) |& tee $i.log
done
for i in tvariable tdirective; do
  (setopt -v; make $i && ./$i) |& tee $i.log.FAILED
done
# (find-toluafile "src/tests/")

#*
eev-cd tolua
lynx doc/tolua-3.2.html

#*




#####
#
# tolua-5.1b
# 2007aug08
#
#####

# «tolua-5.1»  (to ".tolua-5.1")
# http://www.tecgraf.puc-rio.br/~celes/tolua/
# http://www.tecgraf.puc-rio.br/~celes/tolua/tolua-3.2.html
# ftp://ftp.tecgraf.puc-rio.br/pub/users/celes/tolua/tolua-5.1b.tar.gz
#*
rm -Rv ~/usrc/tolua-5.1b/
tar -C ~/usrc/ -xvzf \
  $S/ftp/ftp.tecgraf.puc-rio.br/pub/users/celes/tolua/tolua-5.1b.tar.gz
cd     ~/usrc/tolua-5.1b/

#*
# (code-c-d "tolua" "~/usrc/tolua-5.1b/")
# (find-toluafile "")
# (find-toluash "find * | sort")
# (find-toluafile "src/bin/lua/")
# (find-toluafile "src/tests/")





#####
#
# tagging lua programs with etags
# 2003dec30
#
#####

# «etags»  (to ".etags")
# (find-man "1 etags" "Tag the DEFVAR")
# (find-man "1 etags" "regexps are cumulative")
# (find-man "1 etags" "/\\1/")
# (find-man "1 etags" "regex files")
# (find-progoutput "etags --help")
#*
cd ~/dednat4/
etags --lang=none --regex="/[a-zA-Z_0-9.]+[ \t]+=/" *.lua
mv -v TAGS TAGS0
etags --lang=none --regex='/\([a-zA-Z_0-9.]+\)[ \t]+=/\1/' *.lua
mv -v TAGS TAGS1

cat > /tmp/regex-lua-etags <<'%%%'
/\([a-zA-Z_0-9.]+\)[ \t]+=/\1/
%%%
etags --lang=none --regex=@/tmp/regex-lua-etags *.lua
mv -v TAGS TAGS2

#*
cat > /tmp/regex-lua-etags <<'%%%'
  (find-es "lua5" "etags")
  (find-man "1 etags" "/\\1/")
  (find-man "1 etags" "regex files")
  (find-anchor "Makefile" "TAGS")

  Regexps for tagging lua files:

/\([a-zA-Z_0-9.]+\)[ \t]+=/\1/
/\([a-zA-Z_0-9.]+\),/\1/
/forths\["\([^ ]*\)"\] =/\1/
%%%

#*
# (find-fline "~/dednat4/TAGS0")
# (find-fline "~/dednat4/TAGS1")
# (find-fline "~/dednat4/TAGS2")

# Note: this only works because I always define functions with a
# syntax like this...
# myfunction = function (arg1, arg2)
#     ...
#   end




#####
#
# readline support
# 2004jan04
#
#####

# «readline»  (to ".readline")
# (find-lua50file "om" "-DUSE_READLINE")
# (find-lua50file "om" "-DLUA_USERCONFIG=")
# (find-lua50file "Makefile" "all clean co klean:" "cd src/lua; $(MAKE) $@")
# (find-lua50file "src/lua/Makefile" "EXTRA_DEFS= $(USERCONF)")
# (find-lua50file "src/lua/Makefile" "include $(LUA)/config")
# (find-lua50file "config"  "#USERCONF=-DLUA_USERCONFIG=")
# (find-lua50file "config" "\nUSERCONF=-DLUA_USERCONFIG=" "saconfig.c")
# (find-lua50file "src/lua/lua.c" "#include LUA_USERCONFIG")
# (find-lua50file "etc/saconfig.c" "#ifdef USE_READLINE")

# (find-node "(make)Catalogue of Rules" "$(CC) -c $(CPPFLAGS) $(CFLAGS)")
# (find-lua50file "config" "CFLAGS= $(MYCFLAGS) $(WARN) $(INCS) $(DEFS)")
# (find-lua50file "config" "DEFS= $(NUMBER) $(EXTRA_DEFS)")

# (find-lua50file "etc/saconfig.c" "static int myreadline")
# (find-node "(readline)Basic Behavior" "char *readline (const char *PROMPT)")
# (find-node "(readline)Basic Behavior" "add_history (line)")
# (find-node "(history)Top")

#*
eev-cd lua50
grep USERCONF $(find * -type f); echo
grep EXTRA_DEFS $(find * -type f); echo
grep lua_readline $(find * -type f); echo
grep lua_saveline $(find * -type f); echo

#*



#####
#
# linenoise
# 2012apr17
#
#####

# «linenoise»  (to ".linenoise")
# https://github.com/stevedonovan/luabuild/blob/master/modules/lua-linenoise/example.lua
# http://lua-users.org/lists/lua-l/2010-03/msg00865.html





####
#
# stringtolines - split a string at "\n"s
# 2004jan11
#
####

# «stringtolines»  (to ".stringtolines")
# (find-lua50ref "String Manipulation" ". string.gsub")
#*
lua50e '
stringtolines = function (str)
    local lines = {}
    local rest = string.gsub (str, "([^\n]*)\n", function (line)
        table.insert(lines, line)
      end)
    if rest ~= "" then table.insert(lines, rest) end
    return lines
  end
PP(stringtolines("line1\nline2\nline3"))
PP(stringtolines("line1\nline2\n"))
'
#*



#####
#
# lua-lpeg on Debian Wheezy
# 2014aug30
#
#####

# «lua-lpeg-wheezy» (to ".lua-lpeg-wheezy")
# (find-zsh "installeddebs | sort | grep lpeg")
# (find-zsh "availabledebs | sort | grep lpeg")
# (find-available "lua-lpeg")
# (find-status   "lua-lpeg")
# (find-vldifile "lua-lpeg:i386.list")
# (find-udfile   "lua-lpeg/")
# (find-status   "lua-lpeg-dev")
# (find-vldifile "lua-lpeg-dev:i386.list")
# (find-udfile   "lua-lpeg-dev/")
# file:///usr/share/doc/lua-lpeg-dev/lpeg.html
# file:///usr/share/doc/lua-lpeg-dev/re.html
# file:///usr/share/doc/lua-lpeg-dev/re.html#basic
# file:///usr/share/doc/lua-lpeg-dev/re.html#func
# file:///usr/share/doc/lua-lpeg-dev/re.html#ex



#####
#
# lpeg as a rock
# 2014oct15
#
#####

# «lpeg-rock» (to ".lpeg-rock")
# (find-luarocks-links "lpeg" "0.12" "-1" "lpeg")
# (find-lpegfile "")
# (find-sh "locate re.lua")
# (find-sh "locate lpeg.so")
# (find-fline "/usr/lib/i386-linux-gnu/lua/5.1/" "lpeg.so")
# (find-fline "/usr/share/lua/5.1/" "re.lua")
# (find-fline "~/usrc/luarocks/lib/lua/5.1/" "lpeg.so")
# (find-fline "~/usrc/luarocks/share/lua/5.1/" "re.lua")


* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
= lpeg
= package.cpath
= package.path

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
= lpeg
package.cpath = "/usr/lib/i386-linux-gnu/lua/5.1/?.so"
package.path  = "/usr/share/lua/5.1/?.lua"
require "lpeg"
require "re"
= lpeg.version()

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
= lpeg
package.cpath = "/home/edrx/usrc/luarocks/lib/lua/5.1/?.so"
package.path  = "/home/edrx/usrc/luarocks/share/lua/5.1/?.lua"
require "lpeg"
require "re"
= lpeg.version()








#####
#
# lua-posix on Debian Wheezy
# 2014aug30
#
#####

# «lua-posix-wheezy» (to ".lua-posix-wheezy")
# (find-zsh "installeddebs | sort | grep lua")
# (find-zsh "availabledebs | sort | grep lua")
# (find-status   "lua-posix")
# (find-status   "lua-posix" "Lua-Versions: 5.1 5.2")
# (find-vldifile "lua-posix:i386.list")
# (find-vldifile "lua-posix:amd64.list")
# (find-udfile   "lua-posix/")
# (find-fline "/usr/share/lua/5.1/posix.lua")




#####
#
# luaposix-2012
# 2012sep14
#
#####

# «luaposix-2012»  (to ".luaposix-2012")
# https://github.com/rrthomas/luaposix
# https://github.com/downloads/luaposix/luaposix/luaposix-5.1.22.tar.gz




#####
#
# the posix library on lua-5.1 (luaposix-5.1.4)
# 2008jul18
#
#####

# «luaposix»  (to ".luaposix")
# http://luaforge.net/frs/download.php/3572/luaposix-5.1.4.tar.gz
#*
rm -Rv ~/usrc/luaposix-5.1.4/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/3572/luaposix-5.1.4.tar.gz
cd     ~/usrc/luaposix-5.1.4/
make PREFIX=$LUA51SRC

#*
# (code-c-d "lposix" "~/usrc/luaposix-5.1.4/")
# (find-lposixfile "")
# (find-lposixfile "Makefile")
# (find-lposixfile "lposix.c" "luaopen_posix")
# (find-lposixsh "objdump -Ssax  posix.so")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
ee_loadlib("~/usrc/luaposix-5.1.4/posix.so", "luaopen_posix")





#####
#
# the posix library on lua-5.1
# 2007may14
#
#####

# «posix-lua51»  (to ".posix-lua51")
# (find-angg "LUA/lua50init.lua" "loadposix")
# (code-c-d "lposix" "~/usrc/posix/")
# (find-lposixfile "")
# (find-lposixfile "omxx")
# (find-lposixfile "Makefile")
# (find-lposixfile "posix.lua" "LUA_SOPATH")
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/index.html#lposix
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.0/lposix.tar.gz
# http://lua-users.org/lists/lua-l/2007-05/msg00087.html
#*
rm -Rv ~/usrc/posix/
tar -C ~/usrc/ -xvzf \
  $S/http/www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.0/lposix.tar.gz
cd     ~/usrc/posix/

# Patch to make it run on Lua-5.1:
# http://lua-users.org/lists/lua-l/2007-05/msg00087.html
patch -p0 lposix.c <<'%%%'
67,68c67,69
< 		int j=luaL_findstring(luaL_checkstring(L, i), S);
< 		if (j==-1) luaL_argerror(L, i, "unknown selector");
---
> 		/* int j=luaL_findstring(luaL_checkstring(L, i), S);   */
> 		/* if (j==-1) luaL_argerror(L, i, "unknown selector"); */
> 		int j=luaL_checkoption(L, i, NULL, S);	    /* lua 5.1 */
%%%

# (find-lposixfile "om")
# (find-node "(libc)CPU Time" "CLK_TCK")

etags *.c

cp -iv posix.lua posix.lua.orig
cat > posix.lua <<'%%%'
assert(package.loadlib("./lposix.so", "luaopen_posix"))()
%%%

cp -v tree.lua tree.lua.orig
patch -p0 tree.lua <<'%%%'
22c22
<     for i, name in files do
---
>     for i, name in ipairs(files) do
55c55
< directory = (arg.n > 0) and arg[1] or '.'
---
> directory = (table.getn(arg) > 0) and arg[1] or '.'
%%%

cd ~/usrc/posix/
make LUAINC=$LUA51SRC/src lposix.so  |& tee om
make LUABIN=$LUA51SRC/src tree       |& tee omtree
make LUABIN=$LUA51SRC/src x          |& tee omx
make LUABIN=$LUA51SRC/src xx         |& tee omxx

#*

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
loadposix()
PP(posix)

* (defun eepitch-lua51posix () (interactive) (eepitch-at-dir-comint "~/usrc/posix/" "lua51posix" "lua51"))
* (eepitch-lua51posix)
dofile "posix.lua"
files = posix.dir(".")
= files
PP(files)
PP(posix)


-- (find-lposixfile "posix.lua")
-- (find-lposixfile "tree.lua")

#*
# «posix-install»  (to ".posix-install")
# Obsolete - now (lua-5.1) I load the ".so" from ~/usrc/posix/".
cd ~/usrc/posix/
cp -v ~/usrc/posix/lposix.so ~/.lua50/
lua50 -e 'load_posix(); PP(posix)'

#*
# «load_posix»  (to ".load_posix")
# (find-angg "LUA/lua50init.lua" "load_posix")
# (find-lposixfile "posix.lua" "function so(x)")
# (find-lposixfile "")








#####
#
# posix functions (new; the old block is below)
# 2004jan14
#
#####

# «posix»      (to ".posix")
# «posix-new»  (to ".posix-new")
# (code-c-d "lposix" "~/usrc/posix/")
# (find-lposixfile "")
# (find-lposixfile "oxx")
# (find-lposixfile "Makefile")
# (find-lposixfile "posix.lua" "LUA_SOPATH")
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.0/lposix.tar.gz
# Patch to make it run on Lua-5.1:
# http://lua-users.org/lists/lua-l/2007-05/msg00087.html
#*
rm -Rv ~/usrc/posix/
cd     ~/usrc/
tar -xvzf $S/http/www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.0/lposix.tar.gz
cd ~/usrc/posix/

etags *.c

# (find-angg ".zshrc" "lua" "LUASRC")
# maybe I should use $LUASRC/bin/lua as the binary...
export LUASRC=$HOME/usrc/lua-5.0.2

make LUA=$LUASRC lposix.so  |& tee om
make LUA=$LUASRC tree       |& tee omtree
make LUA=$LUASRC x          |& tee omx
make LUA=$LUASRC xx         |& tee omxx |& tee oxx

#*
# «posix-install»  (to ".posix-install")
cd ~/usrc/posix/
cp -v ~/usrc/posix/lposix.so ~/.lua50/
lua50 -e 'load_posix(); PP(posix)'

#*
# «load_posix»  (to ".load_posix")
# (find-angg "LUA/lua50init.lua" "load_posix")
# (find-lposixfile "posix.lua" "function so(x)")
# (find-lposixfile "")







#####
#
# posix functions (old; the new block is above)
# 2004jan14
#
#####

# «posix-old»  (to ".posix-old")
# (code-c-d "lposix" "~/usrc/posix/")
# (find-lposixfile "")
# (find-lposixfile "oxx")
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/lposix.tar.gz
#*
# 2005jan01: trying to use sarge's lua package

rm -Rv ~/usrc/posix/
cd     ~/usrc/
tar -xvzf $S/http/www.tecgraf.puc-rio.br/~lhf/ftp/lua/lposix.tar.gz
cd ~/usrc/posix/

# (find-lposixfile "Makefile")
# (find-lposixfile "posix.lua" "LUA_SOPATH")
make LUAINC=/usr/include/lua50  lposix.so
make LUABIN=/usr/bin            tree

# oops! it segfauls...

#*
# Build with an upstream lua-5.0.2 instead.

rm -Rv ~/usrc/posix/
cd     ~/usrc/
tar -xvzf $S/http/www.tecgraf.puc-rio.br/~lhf/ftp/lua/lposix.tar.gz
cd ~/usrc/posix/

# (find-angg ".zshrc" "lua" "LUASRC")
export LUASRC=$HOME/usrc/lua-5.0.2

# make LUA=$HOME/tmp/lua-5.0 |& tee om
make LUA=$LUASRC lposix.so
make LUA=$LUASRC tree
make LUA=$LUASRC x
make LUA=$LUASRC xx | tee oxx

#*
# (find-angg ".zshrc")
# (find-lposixfile "posix.lua")
cd ~/usrc/posix/
cp -v lposix.so ~/.lua50/

#*
lua50 -e '
HOME = os.getenv("HOME")
assert(loadlib(HOME.."/.lua50/lposix.so", "luaopen_posix"))()
f = posix.files()
while 1 do
  fname = f()
  if fname == nil then break end
  print(fname)
end
'

#*
# (find-lposixfile "lposix.c" "static int Pstat")
# (find-k24file "Documentation/devices.txt" "hda")
# (find-k24file "Documentation/devices.txt" "hdc")
lua50 -e '
  HOME = os.getenv("HOME")
  assert(loadlib(HOME.."/lib/lposix.so", "luaopen_posix"))()
  fname = "/tmp/o"
  s = posix.stat(fname)
  PP(s)
  dev = s.dev
  devmod64 = math.mod(dev, 64)
  hdname = {}
  hdname[256*3+0]   = "hda"
  hdname[256*3+64]  = "hdb"
  hdname[256*22+0]  = "hdc"
  hdname[256*22+64] = "hdd"
  print(fname, hdname[dev-devmod64], devmod64)
'
#*
lua50 -e '
  LIBDIR = os.getenv("HOME").."/lib/lua5"
  assert(loadlib(LIBDIR.."/lposix.so", "luaopen_posix"))()
  fname = "/home/edrx/o"
  s = posix.stat(fname)
  PP(s)
  dev = s.dev; low = math.mod(dev, 256); hi = (dev-low)/256
  str = string.format(" %d,%4d", hi, low)
  print(str)
  command = format("cd /dev/; ls -l hd* | grep \"%s\"", str)
  print(command)
  os.execute(command, str)
'
#*



#####
#
# posix-ls
# 2014apr29
#
#####

# «posix-ls» (to ".posix-ls")
# (find-angg "LUA/lua50init.lua" "ee_ls")
# (find-luarocks-links "lposix" "20031107" "-1")
# (find-luarocks-links "lposix" "20031107-1" "")
# (find-luarocks-links "lposix" "" "20031107-1")
(code-c-d "lposix" "~/usrc/posix/")
;; (find-lposixfile "")
# (find-lposixfile "tree.lua")
# (find-lposixfile "lposix.c" "static int Pdir")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
userocks()
require "posix"
D = posix.dir "/home/edrx/ferramentas/"
= D
PP(D)

ee_ls = function (dir)
    userocks()
    require "posix"
    return posix.dir(ee_expand(dir))
  end

D = ee_ls "/sda5/videos/"
= ee_ls "/sda5/videosaaa/"
= D
print(table.concat(sorted(D), "\n"))





#####
#
# pushglobals and popglobals
# 2004feb21
#
#####

# «pushglobals-popglobals»  (to ".pushglobals-popglobals")
#*
lua50e '
tinsert = table.insert
tremove = table.remove
getn    = table.getn
_vars = {n=0}
pushglobals = function (...)
    for i=1,getn(arg) do
      local varname = arg[i]
      tinsert(_vars, {varname, _G[varname]})
    end
  end
popglobals = function (...)
    for i=getn(arg),1,-1 do
      local varname, pair = arg[i], tremove(_vars)
      if varname ~= pair[1] then
        error("tried to pop "..varname.." but _vars had "..pair[1].." on top")
      end
      _G[varname] = pair[2]
    end
  end

foo = "FOO"
bar = "BAR"
pushglobals("foo", "bar")
foo = "Foo"
bar = "Bar"
popglobals("foo", "bar")
P(foo, bar)
'
#*




#####
#
# string.gsub with multiple alternatives
# 2004feb21
#
#####

# «gsub-with-alternatives»  (to ".gsub-with-alternatives")
# (find-lua50ref "string.gsub")

# (find-luafile "src/lib/lstrlib.c")
# (find-luafile "src/lib/lstrlib.c" "static int str_gsub")
# (find-luafile "src/lib/lstrlib.c" "char *match " "char *match ")

Idea: string.gsub(s, pat1, repl1,
                     pat2, repl2,
                     pat3, repl3, ...)

would, at each char, test the string "s" against pat1, pat2, ...; the
first one to match would be replaced - and, as usual, each repln is
either a string or a function.

That would be a cheap way to implement a simple form of "|".



####
#
# C calling lua
# 2004feb25
#
####

# «C-calls-lua»  (to ".C-calls-lua")
#*
rm -Rv ~/tmp/ccallslua/
mkdir  ~/tmp/ccallslua/
cd     ~/tmp/ccallslua/
cat > script.lua <<'%%%'
luafunction = function (a, b)
    return "<"..a.." "..b..">"
  end
%%%

# (find-lua50ref "Getting Values from the Stack")
# (find-lua50ref "The Stack and Indices" "negative index")
# (find-lua50ref "Pushing Values onto the Stack")
# (find-lua50ref "Calling Functions" "a = f(\"how\", t.x, 14)")
# (find-lua50ref "Manipulating Tables")
# (find-luatag "luaopen_base")
# (find-luatag "openstdlibs")
# (find-luatag "lualibs")
# (find-lua50ref "Standard Libraries" "luaopen_string")

cat > callit.c <<'%%%'
#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>

void PP(lua_State *L, int index) {
  lua_pushstring(L, "PP");
  lua_gettable(L, LUA_GLOBALSINDEX);
  lua_pushvalue(L, index<0?index-1:index);
  lua_call(L, 1, 0);
}

int main(int argc, char **argv) {
  lua_State *L;
  char *rslt;
  L = lua_open();
  luaopen_base(L);                   /* pushes 1 thing */
  luaopen_string(L);                 /* pushes 1 thing */
  luaopen_table(L);                  /* pushes 1 thing */
  luaopen_io(L);                     /* pushes 3 things */
  lua_pop(L, 6);                     /* removes these 1+1+1+3 things */
  lua_dofile(L, "/home/edrx/LUA/lua50init.lua"); /* for "PP" and debug stuff */
  lua_dofile(L, "script.lua");
  lua_pushstring(L, "luafunction");  /* function name: "luafunction" */
  lua_gettable(L, LUA_GLOBALSINDEX); /*   -> function:  luafunction  */
  lua_pushstring(L, "foo");          /* argument 1: "foo" */
  lua_pushnumber(L, 45);             /* argument 2: 45 */
  lua_call(L, 2, 1);                 /* call with 2 args and 1 result */
  rslt = lua_tostring(L, -1);        /* rslt = "<foo 45>" */
  lua_pop(L, 1);                     /* remove rslt */
  printf("rslt = \"%s\"\n", rslt);
  lua_close(L);
}
%%%

# (find-node "(gcc-300)Link Options")
# -L$HOME/usrc/lua-5.0.2/lib -llualib -llua

gcc -g -o callit callit.c -ldl -lm \
    -I$HOME/usrc/lua-5.0.2/include \
    ~/usrc/lua-5.0.2/lib/liblua.a \
    ~/usrc/lua-5.0.2/lib/liblualib.a \

./callit

#*
# (eegud-gdb t "/home/edrx/tmp/ccallslua/" "callit")
# (find-node "(gdb)Calling")
# (find-node "(gdb)Define")

define depth
  p lua_gettop(L)
end
define PP
  call PP(L, $arg0)
end

br main
run

#*



#####
#
# lua-calls-C
# 2014apr03
#
#####

# «lua-calls-C» (to ".lua-calls-C")
# (find-blogme3grep "grep -nH -e .c anggmake.lua")
# (find-angg "peek/")
# (find-angg "peek/peek.c")
# (find-books "__comp/__comp.el" "ierusalimschy")
# (find-pil2page (+ 19 241) "26. Calling C from Lua")
# (find-pil2text (+ 19 241)     "Calling C from Lua")
# (find-pil2page (+ 19 241) "26.1. C Functions")
# (find-pil2page (+ 19 242)   "lua_setglobal(L, \"mysin\");")
# (find-pil2text (+ 19 242)   "lua_setglobal(L, \"mysin\");")
# (find-pil2page (+ 19 244) "26.2. C Modules")
# (find-pil2page (+ 19 245)   "luaL_register(L, \"mylib\", mylib);")
# (find-pil2text (+ 19 245)   "luaL_register(L, \"mylib\", mylib);")
# (find-pil2page (+ 19 245)   "int luaopen_mylib")
# (find-pil2text (+ 19 245)   "int luaopen_mylib")
# (find-pil2page (+ 19 245)   "require \"mylib\"")
# (find-pil2text (+ 19 245)   "require \"mylib\"")
# (find-pil2page (+ 19 247) "27. Techniques for Writing C Functions")

# (find-pil2page (+ 19 259) "28. User-Defined Types in C")





#####
#
# inspecting the Lua stack
# 2004sep02
#
#####

# «luastackPP»  (to ".luastackPP")
#*
rm -Rv ~/tmp/luastackPP/
mkdir  ~/tmp/luastackPP/
cd     ~/tmp/luastackPP/
cat > luastackPP.c <<'%%%'
#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>
void PP(lua_State *L, int index) {
  lua_pushstring(L, "PP");
  lua_gettable(L, LUA_GLOBALSINDEX);
  lua_pushvalue(L, index<0?index-1:index);
  lua_call(L, 1, 0);
}
LUALIB_API int luastackPP_init(lua_State *L) {
  /* nothing to do on the Lua side; we're only adding C functions */
  return 0;
}
%%%
gcc -g -Wall -shared -I$LUASRC/include -o luastackPP.so luastackPP.c
cp -v ~/tmp/luastackPP/luastackPP.so \
            ~/lib/lua5/luastackPP.so

#*
cat > /tmp/testPP.lua <<'%%%'
  LIBDIR = os.getenv("HOME").."/lib/lua5"
  assert(loadlib(LIBDIR.."/luastackPP.so", "luastackPP_init"))()
  math.sin(0)
  -- print(1, 2+"3", string.sub)
  print("aa", "bb", "cc", "dd", "ee")
%%%
cat /tmp/testPP.lua        >  /tmp/testPP.lst
luac -p -l /tmp/testPP.lua >> /tmp/testPP.lst
lua50 /tmp/testPP.lua

#*
# (let ((eebd-function-is nil)) (eegud-gdb t ee-luadir "bin/lua"))
# (find-fline "/tmp/testPP.lst")
# (find-node "(gdb)Calling")
# (find-node "(gdb)Define")

define depth
  p lua_gettop(L)
end
define PP
  call PP(L, $arg0)
end

set args /tmp/testPP.lua
# br main
br math_sin
run

#*



#*

# (find-fline "/tmp/luabit/lbitlib.c")






#####
#
# composes (for compose.el)
# 2004jan14
#
#####

# «composes»  (to ".composes")
# (find-angg "compose.el")
# (find-angg "compose-new.el")
#*
cat > /tmp/prc.lua <<'%%%'
quote = function (str)
    return string.gsub(str, "([\\\"])", "\\%1")
  end
composes = function (str)
    local compstr = ""
    for _,w in split(str) do
      if string.len(w) == 1 then 
        compstr = compstr .. " ?" .. quote(w)
      else
        compstr = compstr .. "  \"" .. quote(w) .."\""
      end
    end
    return compstr
  end
prc = function (str)
    print(composes(str))
  end

prc " `A À  `E È  `I Ì  `O Ò  `U Ù"
prc " `a à  `e è  `i ì  `o ò  `u ù"
prc " 'A Á  'E É  'I Í  'O Ó  'U Ú"
prc " 'a á  'e é  'i í  'o ó  'u ú"
prc " ^A Â  ^E Ê  ^I Î  ^O Ô  ^U Û"
prc " ^a â  ^e ê  ^i î  ^o ô  ^u û"
prc " ~A Ã              ~O Õ      "
prc " ~a ã              ~o õ      "
prc "\"A Ä \"E Ë \"I Ï \"O Ö \"U Ü"
prc "\"a ä \"e ë \"i ï \"o ö \"u ü"
prc " 'C Ç  CC Ç  ~N Ñ"
prc " 'c ç  cc ç  ~n ñ"
prc " _a ª  _o º  AE Æ  ae æ      "
prc " !! ¡  ?? ¿  SS §  << «  >> »"
prc " 00 °  11 ¹  22 ²  33 ³      "
prc " 14 ¼  12 ½  34 ¾            "
prc " +- ±  :- ÷  cd ·  xx ×      "
%%%
lua50 /tmp/prc.lua | tee ~/o
#*

(defvar composes-accents '(
   "`A" ?À   "`E" ?È   "`I" ?Ì   "`O" ?Ò   "`U" ?Ù
   "`a" ?à   "`e" ?è   "`i" ?ì   "`o" ?ò   "`u" ?ù
   "'A" ?Á   "'E" ?É   "'I" ?Í   "'O" ?Ó   "'U" ?Ú
   "'a" ?á   "'e" ?é   "'i" ?í   "'o" ?ó   "'u" ?ú
   "^A" ?   "^E" ?Ê   "^I" ?Î   "^O" ?Ô   "^U" ?Û
   "^a" ?â   "^e" ?ê   "^i" ?î   "^o" ?ô   "^u" ?û
   "~A" ?Ã                       "~O" ?Õ
   "~a" ?ã                       "~o" ?õ
  "\"A" ?Ä  "\"E" ?Ë  "\"I" ?Ï  "\"O" ?Ö  "\"U" ?Ü
  "\"a" ?ä  "\"e" ?ë  "\"i" ?ï  "\"o" ?ö  "\"u" ?ü
   "'C" ?Ç   "CC" ?Ç   "~N" ?Ñ
   "'c" ?ç   "cc" ?ç   "~n" ?ñ
))
(defvar composes-otheriso '(
   "_a" ?ª   "_o" ?º   "AE" ?Æ   "ae" ?æ
   "!!" ?¡   "??" ?¿   "SS" ?§   "<<" ?«   ">>" ?»
   "00" ?°   "11" ?¹   "22" ?²   "33" ?³
   "14" ?¼   "12" ?½   "34" ?¾
   "+-" ?±   ":-" ?÷   "cd" ?·   "xx" ?×
))
(defvar composes-globalmath nil)
(defvar composes-localmath nil)
(defvar composes-all nil)
(defun composes-update ()
  (setq composes-all (append composes-localmath composes-globalmath
			     composes-accents composes-otheriso)))
(composes-update)


# (find-fline "~/vtutil4/vtfontlib.lua")




####
#
# stdlib (from the CVS)
# 2004mar01
#
####

# «stdlib»  (to ".stdlib")
# See <http://lua-users.org/wiki/StandardLibraries>
# (code-c-d "luastdlib" "~/usrc/lua-users/stdlib/")
# (code-c-d "luastd" "~/usrc/lua-users/stdlib/modules/")
# (find-luastdlibfile "")
# (find-luastdlibfile "README")
# (find-luastdlibfile "utils/ldoc")
# (find-luastdfile "")
# (find-luastdfile "std.parser.lua")
# (find-luastdfile "std.object.lua")
# (find-luastdfile "std.io.io.lua")
# (find-luastdfile "std.io.env.lua")
# (find-luastdfile "std.rex.lua")
# (find-luastdfile "std.string.regex.lua")
# (find-luastdfile "std.string.string.lua")
#*
rm -Rv ~/usrc/lua-users/
mkdir  ~/usrc/lua-users/
cd     ~/usrc/lua-users/
cvs     -d:pserver:anonymous@cvs.lua-users.sourceforge.net:/cvsroot/lua-users login 
cvs -z3 -d:pserver:anonymous@cvs.lua-users.sourceforge.net:/cvsroot/lua-users co stdlib

#*
# http://optusnet.dl.sourceforge.net/sourceforge/lua-users/luastdlib-2.zip
rm -Rv   ~/usrc/lua-users/
mkdir -p ~/usrc/lua-users/stdlib/
cd       ~/usrc/lua-users/stdlib/
unzip $S/http/optusnet.dl.sourceforge.net/sourceforge/lua-users/luastdlib-2.zip

cd ~/usrc/lua-users/stdlib/modules/
tar -xvzf ~/tmp/rrt.tgz

cd ~/usrc/lua-users/stdlib/modules/
# lua50 clue
lua50 -e 'bit={}' std.lua

#*
# New way (untested), from a message by Richard Simes at lua-l, 2006sep18:
# cvs -d :pserver:anonymous@luaforge.net:/cvsroot/stdlib login
# (press enter when prompted for a password)
# cvs -d :pserver:anonymous@luaforge.net:/cvsroot/stdlib checkout stdlib




# «stdlib2»  (to ".stdlib2")

# http://luaforge.net/frs/download.php/2086/stdlib-2.tar.gz
#*
rm -Rv ~/usrc/lua-users/
mkdir  ~/usrc/lua-users/
cd     ~/usrc/lua-users/
tar -C ~/usrc/lua-users/ -xvzf \
  $S/http/luaforge.net/frs/download.php/2086/stdlib-2.tar.gz

#*
# See <http://lua-users.org/wiki/StandardLibraries>
# (code-c-d "luastdlib" "~/usrc/lua-users/stdlib/")
# (code-c-d "luastd"    "~/usrc/lua-users/stdlib/modules/")
# (find-luastdlibfile "")
# (find-luastdlibfile "README")
# (find-luastdlibfile "utils/ldoc")
# (find-luastdfile "")





#####
#
# rici lake's parser
# 2004aug02
#
#####

# «ricilake-parser»  (to ".ricilake-parser")
# http://lua-users.org/wiki/RiciLake
# http://lua-users.org/files/wiki_insecure/users/rici/blex.lua
# http://lua-users.org/files/wiki_insecure/users/rici/parser.tgz
# (code-c-d "riciparser" "~/usrc/parser/")
# (find-riciparserfile "")
# (find-riciparserfile "preprocess.lua")
# (find-riciparserfile "tnt.lua")
#*
rm -Rv ~/usrc/parser/
tar -C ~/usrc/ \
  -xvzf $S/http/lua-users.org/files/wiki_insecure/users/rici/parser.tgz
cd ~/usrc/parser/
rm -v *.html
rm -v lparse.lua

#*
cd ~/usrc/parser/
lua50 preprocess.lua < lparse.lpp > lparse.lua
for i in *; do
  echo $i
  lua50 tnt.lua $i
done

#*





#####
#
# libluaRRT
# 2004aug30
#
#####

# «reuben-thomas-libs»  (to ".reuben-thomas-libs")
# http://www.mupsych.org/~rrt/Lua
# http://rrt.sc3d.org/download/software/lualibs.zip
# (code-c-d "rrtlibs" "~/usrc/lualibs/")
# (find-rrtlibsfile "")
# (find-rrtlibsfile "README")
# (find-rrtlibsfile "Makefile")
#*
rm -Rv ~/usrc/lualibs/
mkdir  ~/usrc/lualibs/
cd     ~/usrc/
unzip -a $S/http/rrt.sc3d.org/download/software/lualibs.zip
cd     ~/usrc/lualibs/

# (find-rrtlibsfile "lrexlib.c" "#include <pcre/pcre.h>")
# (find-vldifile "libpcre3-dev.list")
cp -v  lrexlib.c lrexlib.c.orig
patch -p0 lrexlib.c <<'%%%'
178c178
< #include <pcre/pcre.h>
---
> #include <pcre.h>
%%%

# (find-node "(make)Catalogue of Rules" "Compiling C programs")
# (find-gccnode "Directory Options")
make CFLAGS="-I$LUASRC/include  -W -Wall -DWITH_POSIX -DWITH_PCRE" so

#*
# (find-rrtlibsfile "")
# (find-rrtlibsfile "README" "luaopen_bit")
# (find-rrtlibsfile "README" "luaopen_rex")
cd  ~/usrc/lualibs/
lua50 -e '
  assert(loadlib("./libluaRRT.so", "luaopen_bit"))()
  assert(loadlib("./libluaRRT.so", "luaopen_rex"))()
  PP(bit)
  PP(rex)
'

#*
mkdir ~/lib/lua5/
cd ~/usrc/lualibs/
cp -av libluaRRT.so libluaRRT.so.0 ~/lib/lua5/
cd  ~/lib/lua5/

#*

# (find-status   "libpcre3-dev")
# (find-udfile   "libpcre3-dev/")

# (find-gccnode "Option Summary" "-fPIC")





envsubst = function (str)
     return string.gsub(str, "%$([%a_][%w_]*)", function (e)
         return getenv(e) or ""
       end)
   end




# (find-lua50ref "The Reflexive Debug Interface")
# (find-lua50ref "The Reflexive Debug Interface" ". debug.debug")
# (find-lua50ref "Basic Functions" ". xpcall")
# (find-lua50file "src/lib/ldblib.c")


# (find-lua50file "")



# (find-tkluafile "config")
# (find-tkluafile "src/bin/Makefile")

# (find-toluafile "")

# (find-tkluafile "patches/tolua-4.0a-patch")
# (find-toluafile "src/lib/tolua_gp.c" "tolua_getvalue")

# (find-fline "/usr/src/tklua/")
# (find-tkluaw3 "doc/")
# (find-tkluafile "test/")
# (find-tkluafile "")
# (find-tkluafile "src/bin/")
# (find-tkluafile "src/lib/")

# (find-status "tk8.3-dev")
# (find-vldifile "tk8.3-dev.list")
# (find-fline "/usr/doc/tk8.3-dev/")

# (load-library "~/LUA/lua.el")
# (find-fline "/usr/doc/lua/examples/")

http://toms.net/tomsrtbt-sources/part2/rb/2/bin/




#####
#
# 
# 2005oct27
#
#####

# CGILUALIBPATH=
# (find-luamanualw3m+ "require")
# LUAPATH="?;?.lua;$HOME/usrc/cgilua-5.0/?"



#####
#
# cgilua and compat-5.1
# 2004jul31
#
#####

#*
# «compat-5.1»  (to ".compat-5.1")
# http://luaforge.net/frs/download.php/952/compat-5.1r4.tar.gz
# http://www.keplerproject.org/compat/manual.html#configuration
# (code-c-d "compat51" "~/usrc/compat-5.1r4/")
# (find-compat51file "")
# (find-compat51file "compat-5.1.lua" "LUA_PATH")
# (find-compat51file "compat-5.1.lua" "LUA_CPATH")
#
rm -Rv ~/usrc/compat-5.1r4/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/952/compat-5.1r4.tar.gz
cd     ~/usrc/compat-5.1r4/
gcc -g -Wall -shared -I$LUASRC/include -o compat-5.1.so compat-5.1.c

mkdir ~/usrc/cgilua-5.0/
cp -v compat-5.1.so compat-5.1.lua ~/usrc/cgilua-5.0/

#*
# «cgilua»  (to ".cgilua")
# http://www.keplerproject.org/cgilua/
# http://luaforge.net/frs/download.php/971/cgilua-5.0.tar.gz
# (code-c-d "cgilua" "~/usrc/cgilua-5.0/")
# (find-cgiluafile "")
# (find-cgiluafile "doc/")
# (find-cgiluaw3m  "doc/us/manual.html#installation")
# (find-cgiluafile "src/cgilua/")
# (find-cgiluafile "src/cgilua/Makefile")
# (find-cgiluafile "tests/")
# (find-cgiluafile "tests/Makefile")

rm -Rv ~/usrc/cgilua-5.0/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/971/cgilua-5.0.tar.gz
cd     ~/usrc/cgilua-5.0/

cd     ~/usrc/compat-5.1r4/
cp -v compat-5.1.so compat-5.1.lua          ~/usrc/cgilua-5.0/bin/
cd     ~/usrc/cgilua-5.0/

cd     ~/usrc/cgilua-5.0/src/cgilua/
cp -v cgilua.lua cookies.lua lp.lua         ~/usrc/cgilua-5.0/bin/
cp -v post.lua readuntil.lua                ~/usrc/cgilua-5.0/bin/
cp -v serialize.lua session.lua urlcode.lua ~/usrc/cgilua-5.0/bin/
cp -v config.lua                            ~/usrc/cgilua-5.0/bin/
cd     ~/usrc/cgilua-5.0/

#*
# Not ready...
# (find-cgiluafile "omm")

# (find-cgiluafile "src/cgilua/")
# (find-cgiluafile "tests/")







#####
#
# apresentação super-rápida
# 2004sep02
#
#####

# «quick-presentation»  (to ".quick-presentation")
#*
# Tipos de dados básicos
lua50 -e '
  print(1,     type(1))
  print(1.0,   type(1.0))
  print("abc", type("abc"))
  print(nil,   type(nil))
  print(true,  type(true))
  print(false, type(false))
  print(print, type(print))
  print({2,3,5}, type({}))
'
#*
# Funções são valores
lua50 -e '
  function square(a)     return a*a  end
  square = function (a)  return a*a  end
  print(square, square(2))
'
#*
# Funções podem retornar vários valores
lua50 -e '
  function foo()  return 1, 2, 3  end
  print(1, 2, 3)
  print(foo())
  print(99, foo())
  print(99, foo(), 200)
  print(99, (foo()))
  zero, um, dois, tres, quatro = 0, foo()
  print(zero, um, dois, tres, quatro)
'
#*
# Coerção
lua50 -e '
  print(1+"2")
  print("<".. 11 .. 22 ..">")
'
#*
# Tables
echo $LUA_INIT
lua50 -e '
  a = {10, 20, 30}
  print(200, "um string", a)
  PP   (200, "um string", a)
  b = {11, a, "foo", print}
  PP(b)
'
#*
# Tables (2)
lua50 -e '
  c = {11, 22, 33}
  c[2] = c[2]+c[3]
  c[5] = 55
  c["foo"] = "FOO"
  PP(c)
  d = {11, 22, 33, [5]=555, ["bar"]="BAR", [c]="!"}
  PP(d)
  d[2] = nil
  d[c] = nil
  PP(d)
'
#*
# Variáveis globais
lua50 -e '
  for key,val in _G do
    print(key, val)
  end
'
#*
# Variáveis globais
lua50 -e '
  print(print)
  print(_G["print"])
  print(_G.print)
  print(_G)
  print(_G._G)
'
#*
# Variáveis locais
lua50 -e '
  a = 22
  do print(a)
     local a = 33
     print(a)
  end
  print(a)
'
#*
# assert
lua50 -e '
  print(22)
  print(assert(22, 33))
  print(assert(nil, "Erro! Erro!"))
'
#*
# loadstring
lua50 -e '
  s = [[ print("oi") ]]
  f, err = loadstring(s)
  print(f, err)
  f()
  print(loadstring([[ print("oi ) ]]))
  print(loadstring([[ print("oi ) ]], "nome do bloco"))
  print("ok")
'
#*
# loadstring
lua50 -e '
  s = [[
    print("foo")
    return function (x)  print("bar", x)  end
  ]]
  print(s)
  f = assert(loadstring(s))
  g = f()
  g(223)
'
#*
# Captura de variáveis locais
lua50 -e '
  foo = function ()
    local storage
    return
      function () return storage end,
      function (x) storage = x; return x end
  end
  get1, set1 = foo()
  get2, set2 = foo()
  print(set1(22), get1())          --> 22 22
  print(set2(33), get1(), get2())  --> 33 22 33
'
#*
# Metatables
lua50 -e '
  a = {}  
  PP(getmetatable(a))
  f = io.open("/tmp/o", "w")
  P(getmetatable(f))
  for key,val = 
'
#*




#####
#
# string.sub
# 2004dec24
#
#####

# «string.gsub»  (to ".string.gsub")
# (find-lua50ref "string.gsub")
#*
lua50 -e '
  print(string.gsub("hello world", "(%w+)", "%1 %1"))
    --> "hello hello world world"
  print(string.gsub("hello world", "(%w+)", "%1 %1", 1))
    --> "hello hello world"
  print(string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1"))
    --> "world hello Lua from"
  print(string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv))
    --> "home = /home/roberto, user = roberto"
  print(string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
      return loadstring(s)()
    end))
    --> "4+5 = 9"

  local t = {name="lua", version="5.0"}
  print(string.gsub("$name_$version.tar.gz", "%$(%w+)", function (v)
      return t[v]
    end))
    --> "lua_5.0.tar.gz"
'
#*
# (find-angg "LUA/lua50init.lua" "ee_expand")
lua50 -e '
  print(ee_expand("~/foo"))
  print(ee_expand("foo/~/bar"))
  print(ee_expand("$S/http/www.foo.org/~bar/"))
'
#*



#####
#
# makewith
# 2005jun29
#
#####

# «makewith»  (to ".makewith")
#*
lua50 -e '
_WITH = {}
makewith = function(varnames)
    local s = [[
      return function (_newvalues, _block)
          local _backup = pack(]]..varnames..[[)
          ]]..varnames..[[ = unpack(_newvalues)
          local _result = _block()
          ]]..varnames..[[ = unpack(_backup)
          return _result
        end
      ]]
    _WITH[varnames] = assert(loadstring(s))()
    return _WITH[varnames]
  end
with = function (varnames, newvalues, block)
    return (_WITH[varnames] or makewith(varnames))(newvalues, block)
  end

f = function () print(a, b) end
a,b = "aa", "bb"
f()
with("a,b", {77,88}, f)
f()

'
#*




#####
#
# manual
# 2004sep02
#
#####

#*
# (global-set-key [f11] 'hippie-expand)
# firefox /usr/share/doc/lua50-doc/manual/manual.html &
firefox /usr/share/doc/lua50-doc/manual/contents.html &
#*
# http://www.lua.org/ftp/refman-5.0.ps.gz
gv $S/http/www.lua.org/ftp/refman-5.0.ps.gz &

#*



#####
#
# downloading a local copy of "programming in Lua"
# 2005nov02
#
#####

# «pil»  (to ".pil")
#*
# http://www.lua.org/pil/index.html
# http://www.lua.org/pil/capa.jpg
# http://www.lua.org/lua.css
cat $S/http/www.lua.org/pil/index.html \
  | lua51e '
      f = function (s) print(s); return "" end
      string.gsub(io.read("*a"), "href=\"(.-).html\"", f)
    ' \
  | tee ~/o

#*
cd $S/http/www.lua.org/pil/
for i in $(cat ~/o); do
  j=$i.html
  if [[ ! -e $j ]]; then
    wget http://www.lua.org/pil/$i.html
  fi
done

#*
# (find-fline "$S/http/www.lua.org/")
# (find-sh "cd $S/http/www.lua.org/ && rm -v /tmp/pil.zip && zip /tmp/pil.zip pil/* lua.css")
# (find-fline "/tmp/pil.zip")
# (find-man "zip")

#*
# «pil1.tgz»  (to ".pil1.tgz")
# (find-angg "eev-puro/mini-lua-intro.e" "prep:PiL1")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd $S/http/www.lua.org/
tar -cvzf /tmp/pil1.tgz lua.css pil/*


#*
# (code-c-d "pil" "$S/http/www.lua.org/pil/")
# (find-pilfile "")
# (find-pilw3m "index.html")
# (find-pilw3m "4.3.5.html" "Generic for")
# (find-pilw3m "7.1.html"   "Iterators and Closures")
# (find-pilw3m "9.1.html"   "Coroutine Basics")
# (find-pilw3m "24.2.3.html" "stackDump")

# «pil2»  (to ".pil2")
# PiL2 has some extra chapters, and only chapter 15
# ("Modules and Packages") is online...
# http://www.inf.puc-rio.br/~roberto/pil2/
# http://www.inf.puc-rio.br/~roberto/pil2/chapter15.pdf






#####
#
# funcao em C do Leslie
# 2004sep02
#
#####

#*
rm -Rv /tmp/leslie/
mkdir  /tmp/leslie/
cd     /tmp/leslie/
cat > teste.c <<'%%%'
#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>

int varCint, varCstr_len;
char *varCstr;

static int mandaproC(lua_State *L) {
  varCint = luaL_checkint(L, 1);
  varCstr = (char *) luaL_checklstring(L, 2, &varCstr_len);
  lua_pushstring(L, "recebido");
  return 1;
}
static int imprime(lua_State *L) {
  printf("varCstr: %s\nvarCint: %d\n", varCstr, varCint);
  return 0;
}

LUALIB_API int leslie_init(lua_State *L) {
  lua_register(L, "mandaproC", mandaproC);
  lua_register(L, "imprime", imprime);
  return 0;
}
%%%
gcc -g -Wall -shared -I$LUASRC/include -o teste.so teste.c

#*
cat > /tmp/leslie/teste.lua <<'%%%'
  assert(loadlib("/tmp/leslie/teste.so", "leslie_init"))()
  a = "He" .. "llo"
  mandaproC("203", a)
  a = 233
  imprime()
%%%
lua /tmp/leslie/teste.lua

#*
cat /tmp/testPP.lua        >  /tmp/testPP.lst
luac -p -l /tmp/testPP.lua >> /tmp/testPP.lst
lua50 /tmp/testPP.lua



#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>
void PP(lua_State *L, int index) {
  lua_pushstring(L, "PP");
  lua_gettable(L, LUA_GLOBALSINDEX);
  lua_pushvalue(L, index<0?index-1:index);
  lua_call(L, 1, 0);
}
LUALIB_API int luastackPP_init(lua_State *L) {
  /* nothing to do on the Lua side; we're only adding C functions */
  return 0;
}



#*

# (find-status   "lua50")
# (find-vldifile "lua50.list")
# (find-udfile   "lua50/")
# (find-efunction 'bookmark-set)
# (where-is       'bookmark-set)
# (find-efunction 'bookmark-jump)
# (where-is       'bookmark-jump)
# (find-efunction 'point-to-register)
# (where-is       'point-to-register)
# (find-progoutput "dpkg -l")



echo 'exec xterm' > .xinitrc
ssh 10.0.10.240

(defun eeb-string (sdelim &optional edelim)
  (eeb-invoke 'ee-se-to-string sdelim edelim))

\begin{ambiente}
% arquivo
(let ((str (eeb-string "\n\\begin{ambiente}\n% " "\n\\end{ambiente}\n")))
  (if (string-match "\\(.*\\)" str)
      (list (match-string 1 str)
	    (substring str (1+ (match-end 1))))))
\end{ambiente}

\begin{ambiente}
% /tmp/foo.lst
(let ((str (eeb-string "\n\\begin{ambiente}\n" "\n\\end{ambiente}\n")))
  (if (not (string-match "^% +\\(.*\\)" str))
      (error "First line is not of the form `%% <filename>'")
    (let ((filename (match-string 1 str))
	  (contents (substring str (1+ (match-end 1)))))
      (write-region contents nil filename)
      (format "Wrote %s" filename))))
\end{ambiente}

(defun write-ex (filename) (interactive)
  (let ((contents (eeb-string "\n\\begin{exemplo}\n"
			      "\n\\end{exemplo}\n")))
    (write-region contents nil filename)
    (format "Wrote %s" filename)))

(defun write-exv (filename) (interactive)
  (let ((contents (eeb-string "\n\\begin{exemplovertical}\n"
			      "\n\\end{exemplovertical}\n")))
    (write-region contents nil filename)
    (format "Wrote %s" filename)))

\begin{exemplo}
% (exemplo "/tmp/foo.lst")
% ao inves de: (write-ex "/tmp/foo.lst")
Foo!
FOO!
\end{exemplo}

\begin{exemplovertical}
% (write-exv "/tmp/bar.lst")
Bar!
BAR!
\end{exemplovertical}





#####
#
# lua51gtk (on Lenny)
# 2009oct02
#
#####

# «lua51gtk»  (to ".lua51gtk")
# (find-status   "liblua5.1-gtk-dev")
# (find-vldifile "liblua5.1-gtk-dev.list")
# (find-udfile   "liblua5.1-gtk-dev/")
# (find-udfile "liblua5.1-gtk-dev/README.gz")
# (find-udfile "liblua5.1-gtk-dev/examples/")
# (find-udfile "liblua5.1-gtk-dev/examples/button.lua")
# (find-udfile "liblua5.1-gtk-dev/reference/")

apti liblua5.1-gtk-dev libgtkhtml2-dev

# (find-zsh "dmissing libgtkhtml")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
w lua
lua
require "gtk"
gtk.init(nil, nil)
win = gtk.window_new(gtk.GTK_WINDOW_TOPLEVEL)
win:connect('destroy', gtk.main_quit)
win:show()
gtk.main()

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
require "gtk"
gtk.init(nil, nil)
win = gtk.window_new(gtk.GTK_WINDOW_TOPLEVEL)
win:connect('destroy', gtk.main_quit)
win:show()
gtk.main()




#####
#
# luagtk
# 2005sep10
#
#####

# «luagtk»  (to ".luagtk")
# http://luaforge.net/projects/lua-gtk/
# http://luaforge.net/frs/download.php/989/lua-gtk2-0.3.tar.gz
#*
rm -Rv ~/usrc/lua-gtk2-0.3/
mkdir  ~/usrc/lua-gtk2-0.3/
tar -C ~/usrc/ -xvzf \
      $S/http/luaforge.net/frs/download.php/989/lua-gtk2-0.3.tar.gz
cd ~/usrc/lua-gtk2-0.3/
./configure   |& tee oc
make          |& tee om

mkdir ~/.lua50/
cp -v build-linux/libluagtk2.so ~/.lua50/

#*
cd ~/usrc/lua-gtk2-0.3/
lua50 examples/button.lua
lua50 examples/calculator.lua
lua50 examples/loadlib.lua
lua50 examples/memory.lua
lua50 examples/notebook.lua
lua50 examples/pixmap.lua
lua50 examples/toolbar.lua

#*
cp -iv gtk2.lua gtk2-orig.lua
cat > gtk2.lua <<'%%%'
-- (find-luagtkfile "gtk2-orig.lua")
-- if compiled in, _gtk is set.
if _gtk == nil then
  local init, err = loadlib("build-linux/libluagtk2.so")
  if err then print(err); return end
  gtk = init()
else gtk = _gtk
end
%%%

#*
# (code-c-d "luagtk" "~/usrc/lua-gtk2-0.3/")
# (find-luagtkfile "")
# (find-luagtkfile "doc/")
# (find-luagtkfile "doc/README")
# (find-luagtkfile "examples/")
# (find-luagtkfile "gtk2.lua")
# (find-luagtkfile "examples/pixmap.lua" "draw_rectangle")

#*
cd ~/usrc/lua-gtk2-0.3/
lua50 examples/button.lua

#*
cd ~/usrc/lua-gtk2-0.3/
lua50 -e '
  require "gtk2"
  gtk.init(nil, nil)
  win = gtk.window_new(gtk.GTK_WINDOW_TOPLEVEL)
  win:connect('destroy', gtk.main_quit)
  win:show()
  gtk.main()
'
#*




#####
#
# pixmaps in luagtk
# 2005sep29
#
#####

# «luagtk_pixmaps»  (to ".luagtk_pixmaps")
# (find-angg "LUA/_pixmap.lua")
# (find-angg ".eev/HELP-gtk")
# (find-udw3m "libgtk2.0-doc/gtk-faq/book1.html" "render pixels")
# (find-luagtkfile "data/gtkdata.structs.c" "\"GdkColor\\000\"")

# (find-luagtkfile "examples/pixmap.lua" "draw_rectangle")
# (find-luagtkfile "examples/pixmap.lua")
# (find-luagtkfile "examples/notebook.lua")
#*
cd ~/usrc/lua-gtk2-0.3/
lua50 examples/pixmap.lua

#*

* (eechannel-xterm "A")
cd ~/usrc/lua-gtk2-0.3/
lua50
  PP = function (...)
      for i,v in ipairs(arg) do printf(" %s", mytostring(v)) end; print()
      return unpack(arg)
    end
  -- require "gtk2"
  require(os.getenv("HOME").."/usrc/lua-gtk2-0.3/gtk2.lua")

  gtk.init(nil, nil)
  window = PP(gtk.window_new(gtk.GTK_WINDOW_TOPLEVEL))
  drarea = PP(gtk.drawing_area_new())
  window.add(window, drarea)
  window.show_all(window)
  drawable = PP(window.window)
  pixmap = PP(gtk.call("gdk_pixmap_new", drawable, 320, 200, 16))
  style = PP(window.get_style(window))
  white = PP(style.white_gc)
  black = PP(style.black_gc)
  pixmap.draw_rectangle(pixmap, white, true, 20, 40, 300, 180)

  f_configure = function (...) PP("configure", arg) return true end
  f_expose  = function (...) PP("expose", arg) do_expose(arg) return true end
  f_destroy = function (...) PP("destroy", arg) gtk.main_quit() return true end

  drarea.connect(drarea, "configure-event", f_configure, drarea)
  drarea.connect(drarea, "expose-event",    f_expose,    drarea)
  window.connect(window, "destroy",         f_destroy,   window)

  on_expose = function (win, da, ev)
    PP("on_expose", win, da, ev)
    local area = ev.expose.area
    local x, y, w, h = area.x, area.y, area.width, area.height
    local window = da.window
    local style = win.get_style(win)
    local white_gc = style.white_gc
    gtk.call("gdk_draw_drawable", window, white_gc, win.pixmap,
       x, y, x, y, w, h)
    return false
  end
  drarea.connect(drarea, "expose-event", on_expose, window)

  gtk.main()





  (find-luagtkfile "src/libluagtk2.c")
  (find-luagtksh "cd src/; grep window *")
  (find-luagtksh "cd data/; grep window *")
  (find-luagtkfile "data/gtkdata.structs.c" "\"window\\000\"")

  pixmap.draw_rectangle(nil, white, true, 20, 40, 300, 180)
  drawable.draw_rectangle(drawable, white, true, 20, 40, 300, 180)

=  window.pixmap
= pixmap.draw_rectangle
= drawable.draw_rectangle

PP(style)
PP(white)


  window.connect(window, "destroy", gtk.main_quit, "dummy")
  window.set_title(window, "Pixmap Test")


P(window)
PP(window)

=gtk.main_quit



=pixmap
    self.pixmap:draw_rectangle(white_gc, true, 0, 0, width, height)


  if pixmap then pixmap.unref(pixmap) end
  PP(window.get_size(window, 0, 0))
  pixmap = gtk.call("gdk_pixmap_new", window, 200, 200, -1)


=white
  PP(window)



 200 200

    self.pixmap = gtk.call("gdk_pixmap_new", window, width, height, -1)
    local style = self.win:get_style()

    -- clear the whole pixmap
    self.pixmap:draw_rectangle(white_gc, true, 0, 0, width, height)


    self.pixmap = gtk.call("gdk_pixmap_new", window, width, height, -1)


  c = gtk.call("gdk_color_parse", "#446688", 

    local style = self.win:get_style()
    local white_gc = style.white_gc
    local black_gc = style.black_gc


window, white_gc, self.pixmap,
        x, y, x, y, w, h)
  w = gtk.window_new(gtk.GTK_WINDOW_TOPLEVEL)
  MYWIN = {}
  my_on_expose = function (self, da, ev)
      local area = ev.expose.area
      local x, y, w, h = area.x, area.y, area.width, area.height
      local window = da.window
      local style = self.win:get_style()
      local white_gc = style.white_gc
      gtk.call("gdk_draw_drawable", window, white_gc, self.pixmap,
        x, y, x, y, w, h)
      return false
    end

* (eechannel-xterm "A")
cd ~/usrc/lua-gtk2-0.3/
lua50
  require "gtk2"
  my_delete_event = function (self)
      gtk.main_quit()
    end

  -- (find-luagtkfile "examples/pixmap.lua")
  -- (find-luagtkfile "examples/notebook.lua")

  gtk.init(nil, nil)
  w = gtk.window_new(gtk.GTK_WINDOW_TOPLEVEL)


  stuff = {}
  setmetatable(stuff, MYWIN)
  stuff.w = w
  w:connect('delete-event', my_delete_event, stuff)
  w:set_title('Foo test')
  w:set_default_size(320, 200)
  w:show_all()

  stuff.pixmap = gtk.call("gdk_pixmap_new", window, width, height, -1)
    local style = self.win:get_style()
    local white_gc = style.white_gc
    local black_gc = style.black_gc

    -- clear the whole pixmap
    self.pixmap:draw_rectangle(white_gc, true, 0, 0, width, height)



  gtk.main()



mainwin = Mainwin.init()
gtk.main()
gtk.close()




gtk.init(nil, nil)

function mywin_new()
    local self = { pixmap=nil }
    setmetatable(self, MYWIN)
    self.win = gtk.window_new(gtk.GTK_WINDOW_TOPLEVEL)
    self.win:connect('destroy', MYWIN.on_destroy, self)
    self.win:set_title('Pixmap Test')
    local da = gtk.drawing_area_new()
    self.win:add(da)
    da:connect('configure-event', MYWIN.on_configure, self)
    da:connect('expose-event', MYWIN.on_expose, self)
    self.win:show_all()
    win_count = win_count + 1
    return self
end







mywin1 = mywin_new()







function MYWIN:on_configure(da, ev)
    print "on_configure"
    local window = self.win.window
    local width, height = window:get_size(0, 0)
    -- deallocate previous pixmap
    if (self.pixmap) then self.pixmap:unref() end
    -- allocates memory in X server...
    self.pixmap = gtk.call("gdk_pixmap_new", window, width, height, -1)
    local style = self.win:get_style()
    local white_gc = style.white_gc
    local black_gc = style.black_gc

    -- clear the whole pixmap
    self.pixmap:draw_rectangle(white_gc, true, 0, 0, width, height)

    -- draw a rectangle
    if width > 20 and height > 20 then
	self.pixmap:draw_rectangle(black_gc, false, 10, 10, width - 20,
	    height - 20)
    end




#*




win_count = 0


function mywin_new()
    local self = { pixmap=nil }
    setmetatable(self, MYWIN)
    self.win = gtk.window_new(gtk.GTK_WINDOW_TOPLEVEL)
    -- self.win:connect('destroy', MYWIN.on_destroy, self)
    self.win:set_title('Pixmap Test')
    local da = gtk.drawing_area_new()
    self.win:add(da)
    da:connect('configure-event', MYWIN.on_configure, self)
    da:connect('expose-event', MYWIN.on_expose, self)
    self.win:show_all()
    win_count = win_count + 1
    return self
end





GdkGC* gdk_gc_new (GdkDrawable *drawable);
void gdk_gc_set_foreground (GdkGC *gc, const GdkColor *color);
void gdk_draw_point (GdkDrawable *drawable, GdkGC *gc, gint x, gint y);









# (find-fline "$S/http/ftp.debian.org/debian/pool/main/l/lua50/lua50_5.0.2-5.diff.gz" "/usr/share/lua50")


    self.pixmap = gtk.call("gdk_pixmap_new", window, width, height, -1)






novo gud:
www.nick.uklinux.net



#####
#
# Simple CGIs
# 2005oct27
#
#####

# Rici's way of dealing with POST:
# http://rafb.net/paste/results/Hum5Mk64.html
# http://rafb.net/paste/results/sY4fBg95.html


#####
#
# Reuben Thomas's bitlib
# 2005nov04
#
#####

# «bitlib»  (to ".bitlib")
# (find-man "1 unzip")
# http://rrt.sc3d.org/Software/Lua/
# http://rrt.sc3d.org/Software/Lua/bitlib.zip
# Old: http://rrt.sc3d.org/download/software/bitlib.zip
# (code-c-d "bitlib" "~/usrc/bitlib/")
# (find-bitlibfile "")
#*
rm -Rv   ~/usrc/bitlib/
unzip -d ~/usrc/ \
  $S/http/rrt.sc3d.org/download/software/bitlib.zip
cd       ~/usrc/bitlib/

rm -v lbitlib.o
gcc -g -Wall -shared -I$LUA50SRC/include \
  -o lbitlib.so lbitlib.c

lua50 -e '
  assert(loadlib("./lbitlib.so", "luaopen_bit"))()
  PP(bit)
  print(bit.band(9, 10))
'
#*




#####
#
# Reuben Thomas's bitlib on lua5.1
# 2008jul31
#
#####

# «bitlib-51»  (to ".bitlib-51")
# http://rrt.sc3d.org/Software/Lua/
# http://luaforge.net/projects/bitlib
# http://luaforge.net/frs/download.php/3065/bitlib-25.tar.gz
#*
rm -Rv ~/usrc/bitlib-25/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/3065/bitlib-25.tar.gz
cd     ~/usrc/bitlib-25/

# export L=$HOME/usrc/lua-5.1.3
export L=$LUA51SRC
export LD_LIBRARY_PATH=$L/src

./configure --help   |& tee och
./configure --with-lua-prefix=$L   |& tee oc
gcc -g -Wall -shared -I$L/src -o lbitlib.so lbitlib.c   |& tee og
make   |& tee om

#*
* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
loadbitlib()
print(bit.bxor(6,3))
PP(bit)
os.exit()

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/bitlib-25/
export L=$HOME/usrc/lua-5.1.3
export LD_LIBRARY_PATH=$L/src
ldd ./.libs/bit.so
ldd ./lbitlib.so

lua51
  assert(package.loadlib("./.libs/bit.so", "luaopen_bit"))()
  PP(bit)
  print(bit.bxor(6,3))
  os.exit()

lua51
  assert(package.loadlib("./lbitlib.so", "luaopen_bit"))()
  PP(bit)
  print(bit.bxor(6,3))
  os.exit()

# (find-luamanualw3m "#pdf-package.require")
# (find-luamanualw3m "#pdf-package.loadlib")
# (find-bitlibfile "")
# (find-bitlibfile "lbitlib.c")
# (find-bitlibfile "lbitlib.c" "This code may give warnings")
# (find-bitlibfile "lbitlib.c" "luaopen_bit")
# (find-bitlibfile "oc")
# (find-bitlibfile "och" "--enable-shared")
# (find-bitlibgrep "grep -niH -e shared *")
# (find-bitlibfile "om")
# (find-bitlibfile "bit_limits.h")
# (find-bitlibfile "config.h")
# (find-bitlibfile ".libs/")
# (find-bitlibsh "objdump -xasf .libs/bit.so" "NEEDED")

#*
./configure   |& tee oc

rm -v lbitlib.o
gcc -g -Wall -shared -I$LUA51SRC/src \
  -o lbitlib.so lbitlib.c

lua51 -e '
  assert(package.loadlib("./lbitlib.so", "luaopen_bit"))()
  PP(bit)
  print(bit.band(9, 10))
'
#*
# (code-c-d "bitlib" "~/usrc/bitlib-25/")
# (find-bitlibfile "")
# (find-bitlibfile "och")
# (find-bitlibfile "och" "--with-lua-prefix=")
# (find-bitlibfile "oc")
# (find-bitlibfile "config.log")
# (find-bitlibfile "config.log" "checking for liblua version >= 5.0")
# (find-bitlibfile "config.log" "configure: failed program was:")
# (find-bitlibfile "configure" "checking for liblua version >= 5.0") 

#*




#####
#
# LuaBitOp-1.0.1
# 2009sep07
#
#####

# «luabitop»  (to ".luabitop")
# Bitlib has been declared obsolete ("use luabitop instead")...
# http://luaforge.net/projects/bitlib
# http://bitop.luajit.org/
# http://bitop.luajit.org/download/LuaBitOp-1.0.1.tar.gz
#*
rm -Rv ~/usrc/LuaBitOp-1.0.1/
tar -C ~/usrc/ -xvzf \
  $S/http/bitop.luajit.org/download/LuaBitOp-1.0.1.tar.gz
cd     ~/usrc/LuaBitOp-1.0.1/

make INCLUDES=-I$LUA51SRC/include LUA=$LUA51SRC/bin/lua test  |& tee omt

#*
# (code-c-d "luabitop" "~/usrc/LuaBitOp-1.0.1/")
# (find-luabitopfile "")
# (find-luabitopfile "Makefile")
# (find-luabitopw3m "doc/index.html")
# (find-fline "$LUA51SRC/")
# (find-fline "$LUA51SRC/include/")





#####
#
# rexlib
# 2005nov07
#
#####

# «rexlib»  (to ".rexlib")
# http://lua-users.org/wiki/LibrariesAndBindings
# http://luaforge.net/frs/download.php/389/lrexlib-1.19.zbip
# (code-c-d "rexlib" "~/usrc/lrexlib-1.19/")
# (find-rexlibfile "")
# (find-rexlibfile "README")
# (find-rexlibfile "README" "-- Default constructor")
# (find-rexlibfile "Makefile")
# (find-rexlibfile "config")
# (find-rexlibfile "occ")
#*
rm -Rv   ~/usrc/lrexlib-1.19/
unzip -d ~/usrc/ \
  $S/http/luaforge.net/frs/download.php/389/lrexlib-1.19.zbip
cd       ~/usrc/lrexlib-1.19/

gcc -g -Wall -shared -I$LUA50SRC/include \
  -DLREXLIB_POSIX -o lrexlib.so lrexlib.c

lua50 -e '
  assert(loadlib("./lrexlib.so", "luaopen_rex"))()
  setmetatable(rex,
    {__call = function (self, p, cf, lo) return self.newPOSIX(p, cf, lo) end})
  function rex.find(s, p, st)   return rex(p):match(s, st) end
  function rex.gsub(s, p, f, n) return rex(p):gmatch(s, f, n) end

  PP(rex.find("abcde", "([cd]+)"))
  PP(rex.find("abcde", rex("([cd]+)")))
'

#*
cp -v ~/usrc/lrexlib-1.19/lrexlib.so ~/.lua50/
#*




#####
#
# io.popen
# 2005nov06
#
#####

# «io.popen»  (to ".io.popen")
# http://lua-users.org/lists/lua-l/2005-11/msg00071.html
# (find-lua50file "src/lib/")
# (find-lua50file "src/lib/liolib.c")
# (find-node "(libc)Function Index" "* popen:")
# (find-man "3 popen")
# (find-busyboxtag "popen")
# (find-uclibcfile "libc/stdio/popen.c")
#*
cd ~/eev-current/examples/
lua50 -e '
  pipe = assert(io.popen("ls -la *.e"))
  for li in pipe:lines() do print("("..li..")") end
  pipe:close()
'
#*




#####
#
# txt2html in blogme
# 2005nov07
#
#####

# «txt2html_in_blogme»  (to ".txt2html_in_blogme")
# (find-angg "TH/Generate" "txt2html")
#*
lua50 -e '
  if not rex then load_rex() end
  url_re = rex("(.*)([fh]tt?p://[-%#$&*+,./:;=?@_~0-9A-Za-z]*)(.*)")
  url_f0 = function (str) return format("<a href=\"%s\">%s</a>", str, str) end
  url_f  = function (str)
      local _, _, arr = url_re:match(str)
      if _ then return arr[1]..url_f0(arr[2])..arr[3] end
      return str
    end

  guill_re = "^([^«»]*)«([-+,.:_~0-9A-Za-z]+)»([^«»]*)$"
  guill_f0 = function (str) return "««"..str.."»»" end
  guill_f0 = function (str)
      return [[<a name="]]..a..[["><font color="green"><i>&laquo;</i>]]..
        a..[[<i>&raquo;</i></font></a>]]
    end
  guill_f  = function (str)
      local _, _, a, anchor, b = strfind(str, guill_re)
      if _ then return a..guill_f0(anchor)..b end
      return url_f(str)
    end

  hyperstr_re0 = "[ \t]*(\"([^\"\\]|\\\\.)+\")"
  hyperstr_re  = rex(hyperstr_re0)

  hyperstrsplit_re0 = format("^%s(.*)", hyperstr_re0)
  hyperstrsplit_re  = rex(hyperstrsplit_re0)
  hyperstr_unquote = function (qstr) return (loadstring("return "..qstr))() end
  hyperstrsplit = function (str)
      local _, _, arr = hyperstrsplit_re:match(str)
      if _ then return hyperstr_unquote(arr[1]), hyperstrsplit(arr[3]) end
    end

  hypers = {}
  hypers.to = function (fn, anchor) return anchor and "#"..anchor end

  hyper_re0 = format("^(.*)\\((find-[-+A-Za-z0-9]+|%s)((%s)+)\\)([ \t]*)$",
    "to", hyperstr_re0)
  hyper_re  = rex(hyper_re0)
  hyper_f0 = function (funcname, rest)
      local f = hypers[funcname]
      if f then return f(funcname, hyperstrsplit(rest)) end
    end
  hyper_f1 = function (sexp, funcname, rest)
      if not sexp then sexp = "("..funcname..rest..")" end
      local target = hyper_f0(funcname, rest)
      if target then
        local _, _, left, right = strfind(sexp, "^(.*)(..)$")
        return format("%s<a href=\"%s\">%s</a>", left, target, right)
      end
      return sexp
    end
  hyper_f  = function (str)
      local _, _, arr = hyper_re:match(str)
      if _ then
        local left, funcname, rest, right = arr[1], arr[2], arr[3], arr[7]
        return guill_f(left)..hyper_f1(nil, funcname, rest)..right end
      return str
    end

  print(hyper_f [[ # foo: (to "some" "where") ]])
'
#*


  -- print(hyperstrsplit( [[ "foo" "bar" ]] ))
  -- print(hyperstr_unquote([["+2+3+4"]]))




#####
#
# luasocket: building statically on an AIX box
# 2006jan11
#
#####

# «luasocket-static-aix»  (to ".luasocket-static-aix")
# (find-fline "/tmp/dba/HOWM4/2005-12-28")
#*
# (eev-alides-bounded)

#----
#
# Lua: unpack, make the ".o"s, the ".a"s, lua, and luac
#
#----

rm -Rf ~/usrc/lua-5.0.2/
cd     ~/usrc/
gunzip <    ~/lua-5.0.2.tar.gz | tar -xvf -
cd     ~/usrc/lua-5.0.2/

cat >> config <<'%%%'
LOADLIB= -DUSE_DLOPEN=1
DLLIB= -ldl
# MYLDFLAGS= -Wl,-E
MYLDFLAGS=
EXTRA_LIBS= -lm -ldl
%%%

make CC=cc \
   CFLAGS="-I$HOME/usrc/lua-5.0.2/include/ \
           -I$HOME/usrc/lua-5.0.2/src/ -DUSE_POPEN=1" \
 2>&1 | tee om

# A test:
bin/lua -e 'for li in io.popen("ls bin/"):lines() do print("! "..li) end' \
 2>&1 | tee ol

#----
#
# Luasocket: unpack, make luasocket.so
# (we won't use the .so, but this produces the ".o"s as a side-effect)
#
#----

rm -Rf ~/usrc/luasocket-2.0/
cd     ~/usrc/
gunzip    < ~/luasocket-2.0.tar.gz | tar -xvf -
cd     ~/usrc/luasocket-2.0/
rm        src/compat-5.1r4/*.o

LUA50DIR=$HOME/usrc/lua-5.0.2
make CC=cc LD=cc \
  CFLAGS="-I$LUA50DIR/include/ -I$LUA50DIR/src/ -I$PWD/src/compat-5.1r4/" \
  LDFLAGS="-qmkshrobj -L$LUA50DIR/lib/ -llua -llualib" \
  SOCKET_SO=socket.so \
  2>&1 | tee om

#----
#
# Luasocket: make libluasocket.a
#
#----

cd ~/usrc/luasocket-2.0/src/
ar rcu ../../lua-5.0.2/lib/libluasocket.a \
  compat-5.1r4/compat-5.1.o \
  luasocket.o timeout.o buffer.o io.o auxiliar.o options.o inet.o \
  tcp.o udp.o except.o select.o usocket.o \
  mime.o
ranlib ../../lua-5.0.2/lib/libluasocket.a

#----
#
# Lua: make preload_socket.c, luasocket.o, luasocket
# (luasocket = lua + libluasocket.a)
#
#----

cd ~/usrc/lua-5.0.2/src/lua/

cat > preload_socket.c <<'%%%'
extern int luaopen_socket_core(lua_State *L);
extern int luaopen_mime_core(lua_State *L);
/*
 * written by prec from #lua@freenode
 */
LUALIB_API int preload_socket (lua_State *L) {
  lua_pushliteral(L, "package");             /* "package" */
  lua_newtable(L);                           /* "package" T1 */
  lua_pushliteral(L, "preload");             /* "package" T1 "preload" */
  lua_newtable(L);                           /* "package" T1 "preload" T2 */
  lua_pushliteral(L, "socket.core");         /* ... T2 name */
  lua_pushcfunction(L, luaopen_socket_core); /* ... T2 name func */
  lua_settable(L, -3);                       /* ... T2 */
  lua_pushliteral(L, "mime.core");           /* ... T2 name */
  lua_pushcfunction(L, luaopen_mime_core);   /* ... T2 name func */
  lua_settable(L, -3);                       /* "package" T1 "preload" T2 */
  lua_settable(L, -3);                       /* "package" T1 */
  lua_settable(L, LUA_GLOBALSINDEX);         /* */
  return 0;
}
%%%

cc -I$HOME/usrc/lua-5.0.2/include/ -I$HOME/usrc/lua-5.0.2/src/ \
  -DLUA_USERCONFIG='"preload_socket.c"'     \
  -DLUA_EXTRALIBS="{NULL, preload_socket}," \
  -c -o luasocket.o lua.c

cd ~/usrc/lua-5.0.2/src/lua/
cc -o ../../bin/luasocket  luasocket.o -L../../lib \
  -llua -llualib -lluasocket -lm -ldl

#----
#
# Luasocket: install ".lua"s in ~/.lua50/
# (We don't use the ".so"s)
#
#----

rm -Rf   ~/.lua50/socket/
rm -Rf   ~/.lua50/mime/
rm -f    ~/.lua50/{compat-5.1,ltn12,socket,mime}.lua

mkdir -p ~/.lua50/
mkdir -p ~/.lua50/socket/
mkdir -p ~/.lua50/mime/
cd  ~/usrc/luasocket-2.0/
cd  ~/usrc/luasocket-2.0/src/
cp  compat-5.1r4/compat-5.1.lua               ~/.lua50/
cp  ltn12.lua socket.lua mime.lua             ~/.lua50/
cp  http.lua tp.lua ftp.lua smtp.lua url.lua  ~/.lua50/socket/

#----
#
# Lua: install the binaries (lua, luac, luasocket) in ~/bin/
#
#----

cd ~/bin/
ln -sf ../usrc/lua-5.0.2/bin/lua .
ln -sf ../usrc/lua-5.0.2/bin/luac .
ln -sf ../usrc/lua-5.0.2/bin/luasocket .

#----
#
# luasocket: a test (just check if, e.g., "try" gets loaded)
#
#----

export LUA_INIT="@$HOME/.lua50/compat-5.1.lua"
export  LUA_PATH="$HOME/.lua50/?.lua;?.lua"
export LUA_CPATH="$HOME/.lua50/?.dll;?.dll"

luasocket -e '
  require "socket"
  pt = function(str, T) for k,v in T do print(str, k, v) end end
  pt("socket", socket)
'

#*



#####
#
# luasocket-2.0 on linux
# 2006mar24
#
#####

# «luasocket-on-linux»  (to ".luasocket-on-linux")
# Note: Sarge's luasocket package is crippled - it doesn't have
# ftp.lua, http.lua, etc - so we have to build a non-crippled version
# by hand.

# http://www.cs.princeton.edu/~diego/professional/luasocket/
# http://luaforge.net/frs/download.php/1097/luasocket-2.0.tar.gz
# http://luaforge.net/frs/download.php/1589/luasocket-2.0.1.tar.gz
# (code-c-d "luasocket" "~/usrc/luasocket-2.0.1/")
# (find-luasocketfile "")
#*
rm -Rf ~/usrc/luasocket-2.0.1/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/1589/luasocket-2.0.1.tar.gz
cd     ~/usrc/luasocket-2.0.1/
mv -iv config config.orig

cat > config <<'---'
# (find-luasocketfile "config.orig")
EXT=so
SOCKET_SO=socket.so
MIME_SO=mime.so
UNIX_SO=unix.so
LUAINC=-I$(HOME)/usrc/lua-5.0.2/include
LUALIB=-L$(HOME)/usrc/lua-5.0.2/lib
COMPAT=compat-5.1r5
INSTALL_TOP=$(HOME)/.lua50
INSTALL_TOP_SHARE=$(INSTALL_TOP)
INSTALL_TOP_LIB=$(INSTALL_TOP)
INSTALL_DATA=cp
INSTALL_EXEC=cp
CC=gcc
DEF=-DLUASOCKET_DEBUG 
CFLAGS= $(LUAINC) -I$(COMPAT) $(DEF) -pedantic -Wall -O2 -fpic
LDFLAGS=-O -shared
LD=gcc 
---

make |& tee om
rm -Rv /tmp/.lua50
make INSTALL_TOP=/tmp/.lua50  install |& tee omi-tmp
make INSTALL_TOP=$HOME/.lua50 install |& tee omi

#*
# Old (2.0):

rm -Rf ~/usrc/luasocket-2.0/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/1097/luasocket-2.0.tar.gz
cd     ~/usrc/luasocket-2.0/
rm -v src/compat-5.1r4/compat-5.1.o
mv -iv config config.orig

cat > config <<'---'
# (find-luasocketfile "config.orig")
EXT=so
SOCKET_SO=socket.so
MIME_SO=mime.so
UNIX_SO=unix.so
LUAINC=-I$(HOME)/usrc/lua-5.0.2/include
LUALIB=-L$(HOME)/usrc/lua-5.0.2/lib
COMPAT=compat-5.1r4
INSTALL_TOP=$(HOME)/.lua50
INSTALL_TOP_SHARE=$(INSTALL_TOP)
INSTALL_TOP_LIB=$(INSTALL_TOP)
INSTALL_DATA=cp
INSTALL_EXEC=cp
CC=gcc
DEF=-DLUASOCKET_DEBUG 
CFLAGS= $(LUAINC) -I$(COMPAT) $(DEF) -pedantic -Wall -O2 -fpic
LDFLAGS=-O -shared
LD=gcc 
---

make |& tee om
rm -Rv /tmp/.lua50
make INSTALL_TOP=/tmp/.lua50  install |& tee omi-tmp
make INSTALL_TOP=$HOME/.lua50 install |& tee omi

#*
# (find-luasocketfile "")
# (find-luasocketfile "omi-tmp")
# (find-sh "cd /tmp/.lua50/; find * -type f | sort")
# (find-sh "cd    ~/.lua50/; find * -type f | sort")
#*





#####
#
# luasocket on lua5.1
# 2007aug07
#
#####

# «luasocket-lua51»  (to ".luasocket-lua51")
# http://www.cs.princeton.edu/~diego/professional/luasocket/
# http://luaforge.net/frs/download.php/1589/luasocket-2.0.1.tar.gz
# (code-c-d "luasocket" "~/usrc/luasocket-2.0.1/" :grep)
# (find-luasocketfile "")
# (find-luasocketgrep "grep -nH -e select $(find *)")
# (find-luasocketw3m "doc/socket.html#select")
#*
rm -Rf ~/usrc/luasocket-2.0.1/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/1589/luasocket-2.0.1.tar.gz
cd     ~/usrc/luasocket-2.0.1/
mv -iv config config.orig

#*
cd     ~/usrc/luasocket-2.0.1/
cat > config <<'---'
# (find-luasocketfile "config.orig")
EXT=so
SOCKET_SO=socket.so
MIME_SO=mime.so
UNIX_SO=unix.so
LUAINC=-I$(HOME)/usrc/lua-5.0.2/include
LUALIB=-L$(HOME)/usrc/lua-5.0.2/lib
COMPAT=compat-5.1r5
INSTALL_TOP=$(HOME)/.lua50
INSTALL_TOP_SHARE=$(INSTALL_TOP)
INSTALL_TOP_LIB=$(INSTALL_TOP)
INSTALL_DATA=cp
INSTALL_EXEC=cp
CC=gcc
DEF=-DLUASOCKET_DEBUG 
CFLAGS= $(LUAINC) -I$(COMPAT) $(DEF) -pedantic -Wall -O2 -fpic
LDFLAGS=-O -shared
LD=gcc 
---

make |& tee om
rm -Rv /tmp/.lua50
make INSTALL_TOP=/tmp/.lua50  install |& tee omi-tmp
make INSTALL_TOP=$HOME/.lua50 install |& tee omi

#*




#####
#
# lua2c on lua-5.0.2
# 2006jul13
#
#####

# «lua2c»  (to ".lua2c")
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/4.0/lua2c.tar.gz
# (code-c-d "lua2c" "~/usrc/lua2c/")
# (find-lua2cfile "")
# (find-lua2cfile "lua2c")
# (find-lua2cfile "lua2c.lua")
# (find-lua2cfile "test/")
#*
rm -Rv ~/usrc/lua2c/
tar -C ~/usrc/ -xvzf \
  $S/http/www.tecgraf.puc-rio.br/~lhf/ftp/lua/4.0/lua2c.tar.gz
cd     ~/usrc/lua2c/
cd     ~/usrc/lua2c/test/

#./lua2c test1.lua
# lua: lua2c.lua:185: attempt to call global `read' (a nil value)
# (find-lua2cfile "lua2c.lua" "s=read()")
# (find-luamanualw3m+ "io.read")

# (find-lua2cfile "lua2c.lua" "this version of lua2c cannot handle")
luac -v -p -l test1.lua | lua -e 'read = function () return io.input():read() end' ../lua2c.lua

#*
# E-mail to the mailing list, Lhf's answer, Hisham's answer:
# http://lua-users.org/lists/lua-l/2006-07/msg00119.html
# http://lua-users.org/lists/lua-l/2006-07/msg00120.html
# http://www.inf.puc-rio.br/~hisham/luatoc.tar.gz

#*
rm -Rv ~/usrc/luatoc/
tar -C ~/usrc/ -xvzf \
  $S/http/www.inf.puc-rio.br/~hisham/luatoc.tar.gz
cd     ~/usrc/luatoc/
cd     ~/usrc/luatoc/

#*
# (code-c-d "luatoc" "~/usrc/luatoc/")
# (find-luatocfile "")
# (find-luatocfile "toc")

# It needs Lua 5.1, see these "require"s...
# (find-luatocfile "luatoc.lua")





#####
#
# calling Lua from C
# 2006jul14
#
#####

# «calling-Lua-from-C»  (to ".calling-Lua-from-C")
# (find-es "swig")
# (find-luamanual-ff  "pushing")
# (find-luamanualw3m+ "pushing")
# (find-luamanual-ff  "3.14")
# (find-luamanualw3m+ "3.14")

The following example shows how the host program may do the equivalent
to this Lua code:

  a = f("how", t.x, 14)

Here it is in C:

  lua_pushstring(L, "t");
  lua_gettable(L, LUA_GLOBALSINDEX);          /* global `t' (for later use) */
  lua_pushstring(L, "a");                                       /* var name */
  lua_pushstring(L, "f");                                  /* function name */
  lua_gettable(L, LUA_GLOBALSINDEX);               /* function to be called */
  lua_pushstring(L, "how");                                 /* 1st argument */
  lua_pushstring(L, "x");                            /* push the string "x" */
  lua_gettable(L, -5);                      /* push result of t.x (2nd arg) */
  lua_pushnumber(L, 14);                                    /* 3rd argument */
  lua_call(L, 3, 1);         /* call function with 3 arguments and 1 result */
  lua_settable(L, LUA_GLOBALSINDEX);             /* set global variable `a' */
  lua_pop(L, 1);                               /* remove `t' from the stack */


# (find-luamanualw3m+ "pushing")
# file:///home/edrx/usrc/lua-5.0.2/doc/manual2.html#pushing
# file:///home/edrx/usrc/lua-5.0.2/doc/manual2.html#3.14

/*
 * Ve se um masked_phone_number consta da tabela de monitorados.
 * Esta funcao e' um wrapper em C para uma funcao em Lua com o mesmo nome.
 * «monitored_p_C»  (to ".monitored_p_C")
 * (find-es "swig" "mla.c")
 */
int monitored_p(char *masked_phone_number) {
  /* pseudocode */
  lua_pushstring(L, "monitored_p");                        /* function name */
  lua_gettable(L, LUA_GLOBALSINDEX);               /* function to be called */
  lua_pushstring(L, masked_phone_number);        /* 1st (and only) argument */
  lua_call(L, 1, 1);          /* call function with 1 argument and 1 result */
  /* now convert the returned value to an int and return it */
}




#####
#
# Calling the interactive interpreter inside a Lua program
# 2006jul18
#
#####

# «debug.debug»  (to ".debug.debug")
# (find-luamanualw3m+ "debug.debug")
# (find-lua50tag "debug")
# (find-lua50file "")
# (find-lua50file "src/lib/ldblib.c")
# (find-lua50file "src/lib/ldblib.c" "\"traceback\"")
# (find-lua50file "src/lib/ldblib.c" "static int errorfb")

* (eepitch-shell)
lua50 -e '
  bar = function () local b=33; debug.debug() end
  foo = function () local a=22; bar() end
  foo()
'
PP(debug.getinfo(1))
PP(debug.getinfo(2))
PP(debug.getinfo(3)) -- bar
PP(debug.getinfo(4)) -- foo
PP(debug.getinfo(print))
PP(debug.getinfo(foo))



This function returns a table with information about a function. You
can give the function directly, or you can give a number as the value
of function, which means the function running at level function of the
call stack: Level 0 is the current function (getinfo itself); level 1
is the function that called getinfo; and so on. If function is a
number larger than the number of active functions, then getinfo
returns nil.

The returned table contains all the fields returned by lua_getinfo,
with the string what describing which fields to fill in. The default
for what is to get all information available. If present, the option
`f∧ adds a field named func with the function itself.

For instance, the expression debug.getinfo(1,"n").name returns the
name of the current function, if a reasonable name can be found, and
debug.getinfo(print) returns a table with all available information
about the print function.

debug.getlocal (level, local)



#####
#
# libmapm (for arbitrary precision math)
#
#####

# http://www.tc.umn.edu/~ringx004/mapm-main.html
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.0/lmapm.tar.gz
# http://mat.ufpb.br/~lenimar/alc/index.html
# http://mat.ufpb.br/~lenimar/alc/metodos.txt




#####
#
# long comment syntax
# 2006jul28
#
#####

# (find-lua51w3m "doc/manual.html")
# (find-lua51w3m "doc/manual.html" "]====]")
#*
LUA51=$HOME/usrc/lua-5.1.1/src/lua
$LUA51 -e '
  print "a"
  --[=[
  print "b"
  --]=]
  print "c"
'
#*




#####
#
# getouput
# 2006jul28
#
#####

# «getoutput»  (to ".getoutput")
# (find-angg "LUA/lua50init.lua" "getoutput")
# The name is taken from python...
--*
-- (eeb-lua0)
-- (find-es "lua5" "io.popen")
-- (find-man "3tcl exec")
-- (find-man "perlfunc" "system PROGRAM LIST")
-- (find-man "perlop" "qx/STRING/")
-- (find-node "(libc)Function Index" "* system:")
-- (find-node "(bashref)Command Substitution")
-- (find-rubymanualw3m "IO.html" "popen(command [, mode])")
-- (find-pylibnode "commands" "`getoutput(cmd)'")

getoutput = function (command)
    local pipe = assert(io.popen(command))
    local output = pipe:read("*a")
    pipe:close()
    return output
  end

print(getoutput "echo > /tmp/foo; stat -c %Y /tmp/foo")

--*




#####
#
# trapping signals
# 2006aug10
#
#####

# «signal»  (to ".signal")
# (find-lposixfile "")
# (find-angg "LUA/lua50init.lua" "loadalarm")
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.0/lalarm.tar.gz
# (code-c-d "lalarm" "~/usrc/alarm/")
# (find-lalarmfile "")
#*
rm -Rv ~/usrc/alarm/
tar -C ~/usrc/ -xvzf \
  $S/http/www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.0/lalarm.tar.gz
cd     ~/usrc/alarm/

gcc -shared -I$LUA51SRC/src/ -o lalarm.so lalarm.c
lua51 -e "loadalarm(); print(alarm)"

#*
# (find-lua51tag "lua_sethook")

# (find-luasocketfile "")
# (find-lposixfile "")
# (find-lposixfile "lposix.c" "Psleep")
# (find-lua51file "")
# (find-lua50grep "grep -nH -e 'error with no message' $(cat .files.ch)")
# (find-lua51grep "grep -nH -e 'signal'                $(cat .files.ch)")
# (find-lua51grep "grep -nH -e 'SIG_DFL'               $(cat .files.ch)")
# (find-lua51grep "grep -nH -e 'SIGINT'                $(cat .files.ch)")
# (find-lua51file "src/lua.c" "signal(i, SIG_DFL);")
# (find-lua51file "src/lua.c" "signal(SIGINT, laction)")
# (find-lua51file "src/lua.c" "static void laction (int i)")

# (find-node "(libc)Signal Handling")
# (find-man "7 signal")

# (find-lua51file "src/lua.c" "signal(SIGINT, laction)")
# (find-lua51file "src/lua.c" "static void laction (int i)")

# (code-c-d "uincl" "/usr/include/" :grep)
# (find-uinclfile "")
# (find-uinclgrep "grep -nH -e SIG_DFL $(find * -type f | sort)")
# (find-uinclfile "asm/signal.h" "#define SIG_DFL")
# (find-uinclfile "bits/signum.h" "#define SIG_DFL")

# (find-lua50file "src/lua/lua.c" "signal(i, SIG_DFL)")
# (find-lua50file "src/lua/lua.c" "signal(SIGINT, SIG_DFL)")
# (find-node "(libc)Basic Signal Handling" "Function: sighandler_t signal")
# (find-uclibcfile "")
# (find-uclibctag "signal")
# (find-uclibcfile "libc/signal/")
# (find-uclibcgrep "grep -nH -e SIG_DFL $(cat .files.chS--)")

# A guess:
#
#   signal(SIGINT, SIG_DFL)
#
# should suffice.
# (As it turns out, it does...)

# (find-anggfile ".lua50/")
# (find-anggfile ".lua50/PP.c")

#*
rm -Rv /tmp/luasignal/
mkdir  /tmp/luasignal/
cd     /tmp/luasignal/
cat > luasignal.c <<'---'
#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>
#include <signal.h>
LUALIB_API int luasignal_init(lua_State *L) {
  signal(SIGINT, SIG_DFL);
  return 0;
}
---
# (find-sh "cd /tmp/luasignal/; gcc -g -Wall -shared -I$LUASRC/include -o luasignal.so luasignal.c;pwd;ls -lAF")

gcc -g -Wall -shared -I$LUASRC/include -o luasignal.so luasignal.c
pwd
ls -lAF

lua50 -e '
  load_posix()
  print("^C me now - you should get the message")
  posix.sleep(2)
  print("^C me now - you should get a clean abort")
  assert(loadlib("/tmp/luasignal/luasignal.so", "luasignal_init"))()
  posix.sleep(2)
'

#*
# ...but then I realized that there was a simpler solution: just wrap
#  the call the to main function in a pcall. See:
# (find-angg "bin/pump.lua")

# (find-luamanualw3m "#lua_pcall")
# (find-luamanualw3m "#pdf-pcall")




#####
#
# question about captured variables
# 2006aug10
#
#####

# «captured-variables»  (to ".captured-variables")
# (find-eevex "lua.e" "quick-presentation")
# (find-eevex "lua.e" "quick-presentation" "Capture of local variables")
# http://angg.twu.net/eev-current/examples/lua.e.html#quick-presentation

# The question:
# http://rafb.net/paste/
# (eekill "where do local variables captured by closures live")

# Capture of local variables
# (find-luamanualw3m+ "func-def" "closure")
lua50 -e '
  foo = function ()
    local storage
    return
      function () return storage end,
      function (x) storage = x; return x end
  end
  get1, set1 = foo()
  get2, set2 = foo()
  print(set1(22), get1())          --> 22 22
  print(set2(33), get1(), get2())  --> 33 22 33
'

<lhf> http://www.tecgraf.puc-rio.br/~lhf/ftp/doc/jucs05.pdf pointed to
      in http://www.lua.org/docs.html
<lhf> the bottom line is that while external local vars are in the
      normal stack everything is fine. as soon as their scope is gone,
      they are moved to a special place in the closure.

# http://www.tecgraf.puc-rio.br/~lhf/ftp/doc/jucs05.pdf
# (find-lua50file "src/lfunc.c" "void luaF_close (lua_State *L, StkId level)")
# (code-xpdf "luaimp" "$S/http/www.tecgraf.puc-rio.br/~lhf/ftp/doc/jucs05.pdf")
# (find-luaimppage 9)

# The eps:
# http://www.tecgraf.puc-rio.br/~lhf/tmp/upval.eps
# http://www.tecgraf.puc-rio.br/~lhf/tmp/upval.fig

#*
# Printing the implementation paper:
cp $S/http/www.tecgraf.puc-rio.br/~lhf/ftp/doc/jucs05.pdf /tmp/luaimp.pdf
cd /tmp/
pdftops luaimp.pdf luaimp.ps
psnup -2 < luaimp.ps > luaimp.2.ps
gv luaimp.2.ps

#*




#####
#
# objL (bloated version - removing the bloat)
# 2006aug15
#
#####

# «objective-lua»  (to ".objective-lua")
# http://en.wikipedia.org/wiki/Objective-C
# http://luaforge.net/frs/download.php/1707/ObjL-0.02alpha.tgz
# (code-c-d "objl" "~/usrc/objective-lua/")
# (find-objlfile "")
#*
rm -Rv ~/usrc/objective-lua/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/1707/ObjL-0.02alpha.tgz
cd   ~/usrc/objective-lua/

rm -Rv LGPL.txt
rm -Rv src/lauxlib.h
rm -Rv src/lua/
rm -Rv src/lua.h
rm -Rv src/lualib.h
rm -Rv src/objl
rm -Rv src/objl.o
cat $(find * -type f) | wc

#*




#####
#
# Token Filters
# 2006sep13
#
#####

# «tokenf»  (to ".tokenf")
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.1/tokenf.tar.gz
# http://lua-users.org/lists/lua-l/2007-05/msg00176.html
# http://lua-users.org/lists/lua-l/2009-06/msg00249.html

# See also:
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/#lstrip

# (find-es "lua5" "install-5.1.1")
#*
rm -Rv ~/usrc/tokenf/
tar -C ~/usrc/ -xvzf \
  $S/http/www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.1/tokenf.tar.gz
tar -C ~/usrc/tokenf/ -xvzf \
  $S/http/www.lua.org/ftp/lua-5.1.1.tar.gz

cd ~/usrc/tokenf/lua-5.1.1/src/
mv -v llex.c llex.c.orig
cp -v ../../llex.c  .
cp -v ../../proxy.c .

cd ~/usrc/tokenf/lua-5.1.1/
find * -name '*.[ch]' | sort > .files.ch
etags $(<.files.ch)

make linux test |& tee oml

# (find-tokenffile "Makefile" "$T -l$(FILTER) $(TEST)")

cd ~/usrc/tokenf/
lua-5.1.1/src/lua -lfdebug test.lua   |& tee oltest

# Oops - test.lua:3: attempt to call a table value

#*
# (find-tkdiff "~/usrc/tokenf/llex.c" "~/usrc/lua-5.1.1/src/llex.c")
# (code-c-d "tokenf"    "~/usrc/tokenf/")
# (code-c-d "tokenflua" "~/usrc/tokenf/lua-5.1.1/")
# (find-tokenfluafile "")
# (find-tokenffile "")
# (find-tokenffile "oltest")


# 2010nov24, from lhf, subj: "Lightweight syntax: a dissident view"
# http://lua-users.org/lists/lua-l/2010-11/msg00808.html








#####
#
# ex
# 2006sep04
#
#####

# «ex»  (to ".ex")
# http://lua-users.org/wiki/ExtensionProposal
# http://lua-users.org/files/wiki_insecure/users/MarkEdgar/exapi/ex-20060608.tar.gz
# (code-c-d "luaex" "~/usrc/luaex/")
# (find-luaexfile "")
# (find-luaexfile "posix/")
#*
rm -Rv ~/usrc/luaex/
mkdir  ~/usrc/luaex/
tar -C ~/usrc/luaex/ -xvzf \
  $S/http/lua-users.org/files/wiki_insecure/users/MarkEdgar/exapi/ex-20060608.tar.gz
cd     ~/usrc/luaex/

# (find-lua51file "")
# (find-lua51file "src/")
# (find-luaexfile "")
# (find-luaexfile "posix/")
cd     ~/usrc/luaex/posix/
gcc -g -Wall -shared -I ~/usrc/lua-5.1.1/src -o ex.so ex.c
gcc -g -Wall -shared -I ~/usrc/lua-5.1.1/src -o spawn.so spawn.c
gcc -g -Wall -shared -I ~/usrc/lua-5.1.1/src -o posix_spawn.so posix_spawn.c


#*
# (find-angg ".zshrc" "lua")





#####
#
# xpcall
# 2006sep16
#
#####

# «xpcall»  (to ".xpcall")
# (to "ldb")
# (find-luamanualw3m "#pdf-pcall")
# (find-luamanualw3m "#pdf-xpcall")
# (find-luamanualw3m "#pdf-debug.traceback")
# (find-luamanualw3m "#pdf-debug.debug")
# (find-luamanualw3m "#pdf-debug.getinfo")
# (find-luamanualw3m "#lua_getinfo")
# (find-luamanualw3m "#lua_getstack")
# (find-pilw3m "8.4.html" "Error Handling and Exceptions")
# (find-pilw3m "8.5.html" "xpcall")
# (find-pilw3m "index.html" "23 - The Debug Library")
# (find-pilw3m "23.1.html" "debug.getinfo(n)")
# (find-pilw3m "23.1.html" "function traceback ()")
# (find-pilw3m "23.1.1.html" "Accessing Local Variables")
# (find-pilw3m "23.1.2.html" "Accessing Upvalues")
* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
err    = function () print("foo"); io.output():flush(); error("bar") end
inner  = function () return 1+err() end
middle = function () return 1+inner() end
outer  = function () return 1+middle() end
outer()            -- "foo", then traceback
pcall(outer)       -- "foo", no traceback
xpcall(outer, PP)  -- "foo", "stdin:1: bar"
xpcall(outer, function() print(debug.traceback()) end)   -- traceback
xpcall(outer, function() PP(debug.getinfo(1, "n")) end)  -- name=nil
xpcall(outer, function() PP(debug.getinfo(2, "n")) end)  -- name="error"
xpcall(outer, function() PP(debug.getinfo(3, "n")) end)  -- name="err"
xpcall(outer, function() PP(debug.getinfo(4, "n")) end)  -- name="inner"
xpcall(outer, function() PP(debug.getinfo(5, "n")) end)  -- name="middle"
xpcall(outer, function() PP(debug.getinfo(6, "n")) end)  -- name=nil
xpcall(outer, function() print(debug.traceback()) end)   -- traceback
xpcall(outer, debug.debug)
  PP(debug.getinfo(3, "n"))  -- name="error"
  PP(debug.getinfo(4, "n"))  -- name="err"
  PP(debug.getinfo(5, "n"))  -- name="inner"
  PP(debug.getinfo(6, "n"))  -- name="middle"
  PP(debug.getinfo(3))       -- name="error"
  PP(debug.getinfo(4))       -- name="err"
  print(debug.traceback())
  -- (find-angg "LUA/lua50init.lua" "errorfb_line")
  print("stack traceback:\n"..errorfb_lines(2, 11))
cont


-- «traceback»  (to ".traceback")
-- (find-angg "LUA/lua50init.lua" "errorfb_line")
-- (find-pil2page (+ 19 70) "8.5    Error Messages and Tracebacks")
-- (find-pil2text (+ 19 70) "8.5    Error Messages and Tracebacks")
-- (find-pil3page (+ 19 79) "8.6      Error Messages and Tracebacks")
-- (find-pil3text (+ 19 79) "8.6      Error Messages and Tracebacks")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
err    = function () print("foo"); io.output():flush(); error("bar") end
inner  = function () return 1+err() end
middle = function () return 1+inner() end
outer  = function () return 1+middle() end
xpcall(outer, function() print(debug.traceback()) end)  -- traceback
xpcall(outer, debug.debug)
  print(debug.traceback())                          -- traceback
  print("stack traceback:\n"..errorfb_lines(2, 11)) -- simulated traceback
cont

-- (find-lua51file "src/ldebug.c")
-- (find-lua51file "src/ldblib.c")
-- (find-lua51file "src/ldblib.c" "{\"traceback\", db_errorfb},")
-- (find-lua51file "src/ldblib.c" "static int db_errorfb")
-- (find-lua51file "src/ldblib.c" "static int db_errorfb" "lua_getinfo")
-- (find-lua51file "src/lua.h" "struct lua_Debug {")
-- (find-lua51tag "db_errorfb")

-- (find-luamanualw3m "#lua_Debug")
-- (find-lua51tag "db_errorfb" "ar.short_src")
-- (find-lua51tag "dblib" "{\"traceback\", db_errorfb},")



--*
-- (eeb-lua)
print "foo"

a = function () bang() end
b = function () return 1+a() end
c = function () return 1+b() end

mytraceback = function (errmsg)
    io.output():flush()
    print(debug.traceback(errmsg))
  end

-- c()
xpcall(c, mytraceback)

--*

# Output with "c()", i.e., without flush/xpcall:
# (Note that the traceback appears before "foo")

lua50: /home/edrx/.eev/ee.lua:5: attempt to call global `bang' (a nil value)
stack traceback:
	/home/edrx/.eev/ee.lua:5: in function `a'
	/home/edrx/.eev/ee.lua:6: in function `b'
	/home/edrx/.eev/ee.lua:7: in function `c'
	/home/edrx/.eev/ee.lua:15: in main chunk
	[C]: ?
foo


# Output with "mytraceback", i.e., with flush and xpcall:
# (Note that the "foo" appears before the traceback, as expected)

foo
/home/edrx/.eev/ee.lua:5: attempt to call global `bang' (a nil value)
stack traceback:
	/home/edrx/.eev/ee.lua:13: in function `bang'
	/home/edrx/.eev/ee.lua:5: in function `a'
	/home/edrx/.eev/ee.lua:6: in function `b'
	/home/edrx/.eev/ee.lua:7: in function `c'
	[C]: in function `xpcall'
	/home/edrx/.eev/ee.lua:17: in main chunk
	[C]: ?



#####
#
# StackTracePlus
# 2013sep23
#
#####

# «stacktraceplus» (to ".stacktraceplus")
# https://github.com/ignacio/StackTracePlus
# https://github.com/ignacio/StackTracePlus.git
#
# (code-c-d "stacktraceplus" "~/usrc/StackTracePlus/")
# (find-stacktraceplusfile "")
# (find-stacktraceplusfile "README.md")
# (find-gitk "~/usrc/StackTracePlus/")

# When it gets published on LuaRocks main repository, installation will
# be just:
luarocks install stacktraceplus

# Until then, you'll have to specify the rockspec url:
luarocks install \
  https://raw.github.com/ignacio/StackTracePlus/master/rockspecs/stacktraceplus-0.1.1-1.rockspec





#####
#
# pseudocode for some metatable behaviours
# 2006oct09
#
#####

# «metamethods-pseudocode»  (to ".metamethods-pseudocode")
# This is obsolete. See: (find-TH "__mt")
-- (find-luamanualw3m "" "\"index\":")
-- (find-pilw3m "13.4.1.html" "The __index Metamethod")
--   t[key]
--   t.mt.__index(t, key)
--   t.mt.__index[key]

-- (find-luamanualw3m "" "\"newindex\":")
-- (find-pilw3m "13.4.2.html" "The __newindex Metamethod")
--   t[key] = value
--   t.mt.__newindex(t, key, value)
--   t.mt.__newindex[key] = value

-- (find-luamanualw3m "" "\"call\":")
--   f(...)
--   t.mt.__call(t, ...)


-- «generators-pseudocode»  (to ".generators-pseudocode")
-- (find-pilw3m "index.html")
-- (find-pilw3m "7.1.html" "Iterators and Closures")
-- (find-luamanualw3m "#2.4.5" "For statement")
-- (find-luamanualw3m "#2.4.5" "local f, s, var = explist")
--   for a,b,c in generator() do block(a, b, c) end
--     f, s, a0 = generator()
--   a1, b1, c1 = f(s, a0);   block(a1, b1, c1)
--   a2, b2, c2 = f(s, a1);   block(a2, b2, c2)
--   a3, b3, c3 = f(s, a2);   block(a3, b3, c3)
--   a4, b4, c4 = f(s, a3);   -- a4 == nil: break

-- for a,b,c,d in explist do
--                block
-- end
--
-- is equivalent to:
--
--               f,s,var = explist
-- while true do
--     a,b,c,d = f(s,var)
--                   var = a
--                if var == nil then break end
--                block
-- end


* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
eval = function (str) return assert(loadstring(str))() end
ask = function (prompt) io.write(prompt) return eval("return "..io.read()) end
pask = function (...) PP(...) return ask("? ") end
= eval "return 22, 33, 44"
= ask "? "
22, 33, 44
= pask(20, 30, 40)
222, 333

for a,b,c in pask,"state","0","1" do PP("a,b,c =", a, b, c) end
1, 2, 3
4, 5, 6
7, 8
9
nil

-- for a,b,c in pask,"state","0","1" do PP("a,b,c =", a, b, c) end
--  "state" "0"
-- ? 1, 2, 3
--  "a,b,c =" 1 2 3
--  "state" 1
-- ? 4, 5, 6
--  "a,b,c =" 4 5 6
--  "state" 4
-- ? 7, 8
--  "a,b,c =" 7 8 <nil>
--  "state" 7
-- ? 9
--  "a,b,c =" 9 <nil> <nil>
--  "state" 9
-- ? nil
-- > 



To do: coroutines pseudocode





#####
#
# pil 24.1: calling Lua from C
# 2006oct21
#
#####

# «pil24.1»  (to ".pil24.1")
# (find-es "icon" "icon-lua")
# (find-lua51file "")
# (find-lua51file "oml" "liblua.a")
# (find-lua51file "src/lua.c")
# (find-lua51file "src/" "liblua.a")

#*
rm -Rv /tmp/pil24_1/
mkdir  /tmp/pil24_1/
cd     /tmp/pil24_1/

cat > pil24_1.c <<'---'
#include <stdio.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <string.h>   // for strlen
int main (void) {
  char buff[256];
  int error;
  lua_State *L = luaL_newstate();   /* opens Lua */
  luaL_openlibs(L);             /* opens the standard libraries */
  while (fgets(buff, sizeof(buff), stdin) != NULL) {
    error = luaL_loadbuffer(L, buff, strlen(buff), "line") ||
            lua_pcall(L, 0, 0, 0);
    if (error) {
      fprintf(stderr, "%s", lua_tostring(L, -1));
      lua_pop(L, 1);  /* pop error message from the stack */
    }
  }
  lua_close(L);
  return 0;
}
---

export LUA51SRC=$HOME/usrc/lua-5.1.2
gcc -O2 -Wall -I$LUA51SRC/src -c -o pil24_1.o pil24_1.c
# (find-lua51file "oml" "liblua.a")
# (find-lua51file "oml" "gcc -o lua ")
# gcc -o lua  lua.o liblua.a -lm -Wl,-E -ldl -lreadline -lhistory -lncurses
# gcc -o pil24_1 pil24_1.o $LUA51SRC/src/liblua.a -lm -Wl,-E -ldl -lreadline -lhistory -lncurses
  gcc -o pil24_1 pil24_1.o $LUA51SRC/src/liblua.a -lm -Wl,-E -ldl

echo 'print(1+2, "hello")' | ./pil24_1

#*
# (find-node "(gcc)Invoking GCC")
# (find-node "(gcc)Link Options")




#####
#
# pixeltoaster (rec. Keffo)
# 2006oct22
#
#####

# «pixeltoaster»  (to ".pixeltoaster")
# Keffo says that he has Lua bindings for
# this but hasn't given them to me yet...
# http://www.pixeltoaster.com/about/
# http://www.pixeltoaster.com/downloads/PixelToaster-1.3.1.zip
# (find-man "1 unzip")
#*
rm -Rv ~/usrc/pixeltoaster/
mkdir  ~/usrc/pixeltoaster/
unzip -d ~/usrc/pixeltoaster/ \
  $S/http/www.pixeltoaster.com/downloads/PixelToaster-1.3.1.zip
cd     ~/usrc/pixeltoaster/
make -f makefile.unix |& tee om
 
cd     ~/usrc/pixeltoaster/
./Flower

#*
# (code-c-d "pixeltoaster" "~/usrc/pixeltoaster/")
# (find-pixeltoasterfile "makefile.unix")
# (find-pixeltoasterfile "")
# (find-pixeltoasterfile "om")
# (find-pixeltoasterfile "demos/")
#*





#####
#
# compressing jpgs to under 100KB
# 2006oct27
#
#####

# «compressing-jpgs»  (to ".compressing-jpgs")

* (eepitch-shell)
# rm -Rv /tmp/tiao/
mkdir  /tmp/tiao/
cd     /tmp/tiao/
A=(068 071 073 078 079 082 331 332)
for i in $A; do cp -v ~/FOTOS/tiao/julho_2006_$i.jpg $i.jpg; done

lua50

-- (find-angg "LUA/lua50init.lua" "readfile")
-- (find-bashnode "Bash Conditional Expressions" "`-e FILE'")
fileexists = function (fname)
    local f, err = (io.open(fname, "r"))
    if f then io.close(f); return true end
    return false
  end
map = function (f, t)
    local t2 = {}
    for _,v in ipairs(t) do tinsert(t2, f(v)) end
    return t2
  end

id    = function (...)       return unpack(arg) end
p     = function (str)       io.write(str); return str end
run   = function (cmd)       return getoutput(cmd) end
e     = function (fname)     return fileexists(fname) end
d2    = function (n)         return format("%02d", n) end
size  = function (fname)     return strlen(readfile(fname)) end
pszn  = function (sz, fn)    p(format("%6d %s\n", sz, fn)); return sz; end
psize = function (fname)     return pszn(size(fname), fname) end
cq0   = function (f1, q, f2) run("convert "..f1.." -quality "..q.." "..f2) end
shr0  = function (f1, s, f2) run("convert "..f1.." -resize "..s.."% "..f2) end
cq1   = function (f1, q, f2) return e(f2) or cq0 (f1, q, f2) end
shr1  = function (f1, s, f2) return e(f2) or shr0(f1, s, f2) end
cq2   = function (f1, q, f2) cq1 (f1, q, f2); return psize(f2) end
shr2  = function (f1, s, f2) shr1(f1, s, f2); return psize(f2) end
qstem = function (stem,   q) return stem.."_q"..d2(q) end
sstem = function (stem,   s) return stem.."_s"..d2(s) end
qname = function (stem,   q) return qstem(stem, q)..".jpg" end
sname = function (stem,   s) return sstem(stem, s)..".jpg" end
cq3   = function (f1, st, q) return cq2 (f1, q, qname(st, q)) end
shr3  = function (f1, st, s) return shr2(f1, s, sname(st, s)) end
cq4   = function (stem,   q) return cq3 (stem..".jpg", stem, q) end
shr4  = function (stem,   s) return shr3(stem..".jpg", stem, s) end
cq5   = function (stem,   q) cq4 (stem, q); return qstem(stem, q) end
shr5  = function (stem,   s) shr4(stem, s); return sstem(stem, s) end
small = function (n)         return n <  100000 end
big   = function (n)         return n >= 100000 end

godown = function (stem, n1, step)
    for q=n1,n1+10*step,step do if small(cq4(stem, q)) then return q end end
  end
goup   = function (stem, n1, step)
    for q=n1,n1+10*step,step do if   big(cq4(stem, q)) then return q end end
  end
foo  = function (stem)
    local q10 = godown(stem,  90, -20)
    local q5  = goup  (stem, q10,   5)
    local q1  = godown(stem,  q5,  -1)
    return qname(stem, q1), q1
  end
T = {
foo("068"),
foo("071"),
foo("073"),
foo("078"),
foo("079"),
foo("082"),
foo("331"),
foo("332"),
foo(shr5("331", 50)),
(foo(shr5("332", 50)))
}
print(concat(T, "\n"))

-- (find-fline "~/FOTOS/tiao/")
-- (find-fline "/tmp/tiao/")






#####
#
# unit tests
# 2006nov27
#
#####

from		Brian McCallister <brianm@skife.org>	 3:10 am (15 minutes ago) 
reply-to	Lua list <lua@bazar2.conectiva.com.br>	 
to		Lua list <lua@bazar2.conectiva.com.br>	 
date		Nov 27, 2006 3:10 AM	 
subject		Re: Are there any guide or best practice article for unit test with lua ?	 
mailed-by	bazar2.conectiva.com.br

http://svn.i-want-a-pony.com/repos/wombat/trunk/test/moonunit.lua
http://svn.i-want-a-pony.com/repos/wombat/trunk/test/test.lua





#####
#
# matrix.lua
# 2006dec31
#
#####

# «matrix.lua»  (to ".matrix.lua")
# http://lua-users.org/wiki/SimpleMatrix
# http://lua-users.org/files/wiki_insecure/users/chill/Matrix.V.0.4.lua
# (find-angg "LUA/matrix.lua")

# (find-sh0 "cp $S/http/lua-users.org/wiki/SimpleMatrix /tmp/SimpleMatrix.html")
# (find-firefox "/tmp/SimpleMatrix.html")

* (eepitch-shell)
cd ~/LUA/
lua50
dofile "matrix.lua"

m1 = Matrix:Create(4, 4)
m1:fillrandom()
m1:draw()
m2 = m1^-1
m2:draw()
m3 = m1 * m2
m3:draw()
print(m2:getDet())
print(1/m1:getDet())
m4 = m1 * 4
m4:draw()
m5 = m4..m3
m5:draw()
m6 = Matrix:Create({{2, 3}, {3, 4}, {4, 5}})
m6:draw()
m7 = m6^"T"
m7:draw()

m7 = m7 * "a"
m7:draw()
m7:replace("a", 4)
m7:draw()

print(m7:getE(1, 3))
print(m7:setE(1, 3 , 8))
m7:draw()
m7:switch("line", 1, 2)
m7:draw()
m7:switch("column", 2, 3)
m7:draw()
m7:remove(1, 1)
m7:draw()

m8 = Matrix:Create(5, 5)
m8:fillrandom()
m8:draw()
m9 = m8:getSubM(2, 2, 3, 5)
m9:draw()

m9:doGJ()
m9:draw()




#####
#
# lpeg
# 2007jan01
#
#####

# «lpeg»  (to ".lpeg")
# (find-angg "LUA/lua50init.lua" "loadlpeg")
# http://www.inf.puc-rio.br/~roberto/lpeg.html
# http://www.inf.puc-rio.br/~roberto/lpeg-0.5.tar.gz
# http://pdos.csail.mit.edu/~baford/packrat/popl04/peg-popl04.pdf
# http://pdos.csail.mit.edu/~baford/packrat/
# http://en.wikipedia.org/wiki/Parsing_expression_grammar
# http://lua-users.org/lists/lua-l/2006-12/msg00532.html
# (code-c-d "lpeg" "~/usrc/lpeg-0.5/")
# (find-lpegw3m "doc.html")
# (find-lpegfile "og")
# (find-lpegfile "re.lua")
# (find-lpegfile "test.lua")
# (find-lpegfile "")
#*
rm -Rfv ~/usrc/lpeg-0.5/
tar -C  ~/usrc/ -xvzf $S/http/www.inf.puc-rio.br/~roberto/lpeg-0.5.tar.gz
cd      ~/usrc/lpeg-0.5/

chmod 644 lpeg.c
# http://lua-users.org/lists/lua-l/2007-03/msg00616.html
# http://lua-users.org/lists/lua-l/2007-03/msg00620.html
patch -p0 lpeg.c <<'%%%'
470c470,471
<           capture[captop - 1].siz = s - capture[captop - 1].s + 1;
---
>           /* capture[captop - 1].siz = s - capture[captop - 1].s + 1; */
>           capture[captop - 1].siz = (s - getoff(p)) - capture[captop - 1].s + 1;
%%%

# export LUA51SRC=~/usrc/lua-5.1.2
# echo $LUA51SRC

gcc -g -Wall -shared -I$LUA51SRC/src \
  -o lpeg.so lpeg.c   |& tee og
lua51 test.lua

#*


# «lpeg-0.6»  (to ".lpeg-0.6")
# (code-c-d "lpeg" "~/usrc/lpeg-0.6/")
# (find-lpegfile "")
# (find-lpegw3m  "doc.html")
# http://www.inf.puc-rio.br/~roberto/lpeg.html
# http://www.inf.puc-rio.br/~roberto/lpeg-0.6.tar.gz
# (find-lpegw3m "doc.html")
#*
rm -Rfv ~/usrc/lpeg-0.6/
tar -C  ~/usrc/ -xvzf $S/http/www.inf.puc-rio.br/~roberto/lpeg-0.6.tar.gz
cd      ~/usrc/lpeg-0.6/
chmod 644 *
etags lpeg.c

# «lpeg-precaptures»  (to ".lpeg-precaptures")
# (find-lpegfile "lpeg.c")
patch -p0 lpeg.c <<'%%%'
1866a1867,1870
> #ifdef SAVE_PRECAPTURES /* edrx */
>   lua_pushlstring(L, (void *)cap, captop * sizeof(Capture));
>   lua_setglobal(L, "lpeg_precaptures");
> #endif SAVE_PRECAPTURES
%%%

gcc -g -Wall -shared -I$LUA51SRC/src \
  -o lpeg.so    lpeg.c   |& tee og
# gcc -g -Wall -shared -I$LUA51SRC/src -DSAVE_PRECAPTURES \
#  -o lpegspc.so lpeg.c   |& tee ogspc
lua51 test.lua

#*
# Links related to a discussion with Roberto:
# (find-lpegtag "matchl")
# (find-lpegtag "match")
# (find-lpegtag "Capture")
# (find-lpegtag "doublecap")
# (find-lpegtag "getcaptures")






#*
(code-ps "pegford"
  "$S/http/pdos.csail.mit.edu/~baford/packrat/popl04/peg-popl04.pdf")
(find-pegfordpage 3)
(find-pegfordpage 5)

# http://www.inf.puc-rio.br/~roberto/lpeg.html
# (find-sh0 "cd /tmp/; cat mozilla.ps | pstops '1:@.9(1cm,1cm)' | psnup -2 > mozilla.2.ps")
# (find-pspage "/tmp/mozilla.2.ps")

# (find-lpegfile "test.lua")


* (eepitch-shell)
cd ~/usrc/lpeg-0.4/
lua51
require "lpeg"
PP(lpeg)

* (eepitch-at-dir-comint ee-lpegdir "lpeg-lua" "lua51")
require "lpeg"
PP(lpeg)

* (eepitch-lua51)
loadlpeg()
PP(lpeg)

-- (find-lpegw3m "doc.html" "function split (s, sep)")
-- (find-lpegfile "lpeg.c" "** Printing patterns")
sep1  = lpeg.P(" ")
sep   = sep1^1
elem  = lpeg.C((1 - sep)^0)
elems = elem * (sep * elem)^0
= sep
sep1:print()
sep:print()
elem:print()
elems:print()
PP(elems:match(" foo  bar "))




#####
#
# lpeg-0.7
# 2007dec27
#
#####

# «lpeg-0.7»  (to ".lpeg-0.7")
# (find-angg "LUA/lua50init.lua" "loadlpeg")
# (find-blogme3 "Makefile")
# (find-angg ".zshrc" "lua" "LUA51SRC=")
# http://www.inf.puc-rio.br/~roberto/lpeg-0.7.tar.gz
#*
rm -Rv ~/usrc/lpeg-0.7/
tar -C ~/usrc/ -xvzf \
  $S/http/www.inf.puc-rio.br/~roberto/lpeg-0.7.tar.gz
cd     ~/usrc/lpeg-0.7/

chmod 644 *
gcc -g -Wall -shared -I$LUA51SRC/src -o lpeg.so lpeg.c
lua51 test.lua

#*
# (code-c-d "lpeg" "~/usrc/lpeg-0.7/")
# (find-lpegfile "")
# (find-lpegfile "makefile")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
loadlpeg()




#####
#
# lpeg-0.8.1
# 2008jul17
#
#####

# «lpeg-0.8.1»  (to ".lpeg-0.8.1")
# (find-angg "LUA/lua50init.lua" "loadlpeg")
# (find-dn4 "Makefile" "lpeg")
# http://www.inf.puc-rio.br/~roberto/lpeg.html
# http://www.inf.puc-rio.br/~roberto/lpeg/lpeg-0.8.1.tar.gz
#*
rm -Rfv ~/usrc/lpeg-0.8.1/
tar -C ~/usrc/ -xvzf \
  $S/http/www.inf.puc-rio.br/~roberto/lpeg/lpeg-0.8.1.tar.gz
cd     ~/usrc/lpeg-0.8.1/

make LUADIR=$LUA51SRC/src  |& tee om
lua51 test.lua

#*
# (code-c-d "lpeg" "~/usrc/lpeg-0.8.1/")
# (find-lpegfile "")
# (find-lpegfile "makefile")
# (find-lpegfile "om")
# (find-lpegw3m "lpeg.html")
# (find-lpegw3m "re.html")
# (find-lpegw3m "lpeg.html" "utf8 sequence to a Latin 1 char")




#####
#
# lpeg-0.9
# 2008oct12
#
#####

# «lpeg-0.9»  (to ".lpeg-0.9")
# (find-dn4 "Makefile" "lpeg")
# http://www.inf.puc-rio.br/~roberto/lpeg/lpeg-0.9.tar.gz
#*
rm -Rv ~/usrc/lpeg-0.9/
tar -C ~/usrc/ -xvzf \
  $S/http/www.inf.puc-rio.br/~roberto/lpeg/lpeg-0.9.tar.gz
cd     ~/usrc/lpeg-0.9/ \
  && chmod 644 *

# make LUADIR=$LUA51SRC/src   |& tee om
  make LUADIR=$LUA51SRC/src CC="gcc -g"  |& tee om
# make LUADIR=$LUA51SRC/src CC="gcc -g" COPT=""  |& tee om
lua51 test.lua

etags lpeg.c

#*
# (code-c-d "lpeg" "~/usrc/lpeg-0.9/")
# (find-lpegfile "")
# (find-lpegfile "makefile")
# (find-lpegfile "om")
# (find-lpegw3m "lpeg.html")
# (find-lpegw3m "lpeg.html#captures")
# (find-lpegw3m "lpeg.html#cap-b")
# (find-lpegw3m "lpeg.html#matchtime")
# (find-lpegw3m "re.html")
# (find-lpegw3m "lpeg.html" "UTF-8 encoding to Latin 1")
# (find-lpegfile "lpeg.c" "{\"print\", printpat_l},")





#####
#
# lpeg-0.10.2
# 2012may13
#
#####

# «lpeg-0.10.2»  (to ".lpeg-0.10.2")
# (find-dn4 "Makefile" "lpeg")
# http://www.inf.puc-rio.br/~roberto/lpeg/lpeg-0.10.2.tar.gz
#*
rm -Rv ~/usrc/lpeg-0.10.2/
tar -C ~/usrc/ -xvzf \
  $S/http/www.inf.puc-rio.br/~roberto/lpeg/lpeg-0.10.2.tar.gz
cd     ~/usrc/lpeg-0.10.2/ \
  && chmod 644 *

# make LUADIR=$LUA51SRC/src   |& tee om
# make LUADIR=$LUA51SRC/src CC="gcc -g" COPT=""  |& tee om

make LUADIR=$LUA51SRC/src CC="gcc -g"  |& tee om

cp -v $LUA51SRC/etc/strict.lua .
lua51 test.lua

etags lpeg.c

#*
# (code-c-d "lpeg" "~/usrc/lpeg-0.10.2/")
# (find-lpegfile "")
# (find-lpegfile "makefile")
# (find-lpegfile "om")
# (find-lpegw3m "lpeg.html")
# (find-lpegw3m "lpeg.html#captures")
# (find-lpegw3m "lpeg.html#cap-g")
# (find-lpegw3m "lpeg.html#cap-b")
# (find-lpegw3m "lpeg.html#matchtime")
# (find-lpegw3m "re.html")
# (find-lpegw3m "lpeg.html" "UTF-8 encoding to Latin 1")
# (find-lpegfile "lpeg.c" "{\"print\", printpat_l},")

# (find-lpegfile "test.lua")
# (find-lpegfile "test.lua" "-- tests for back references")

# «lpeg-metatable»  (to ".lpeg-metatable")
* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
require "lpeg"
= lpeg.Cp()
getmetatable(lpeg.Cp()).__tostring = function () return "pattern" end
= lpeg.Cp()

= lpeg
=         getmetatable(lpeg.Cp()).__index
= lpeg == getmetatable(lpeg.Cp()).__index
PP(lpeg)
PP(getmetatable(lpeg.Cp()))


# «lpeg-Cg-and-Cb»  (to ".lpeg-Cg-and-Cb")
* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
require "lpeg"
P  = lpeg.P
Cc = lpeg.Cc
Ct = lpeg.Ct
Cb = lpeg.Cb
lpeg.prmatch = function (patt, ...) PP(patt:match(...)) end

 (Cc"a" * Cc"b")                    :prmatch"foo"    --> "a" "b"	       
 (Cc"a" * Cc"b"):Cg()               :prmatch"foo"    --> "a" "b"
 (Cc"a" * Cc"b"):Cg""               :prmatch"foo"    --> 1                  
((Cc"a" * Cc"b"):Cg"" * Cb"" * Cb""):prmatch"foo"    --> "a" "b" "a" "b"    
((Cc()  * Cc"b"):Cg"" * Cb"" * Cb""):prmatch"foo"    --> "b" "b"	       
((Cc(nil)*Cc"b"):Cg"" * Cb"" * Cb""):prmatch"foo"    --> <nil> "b" <nil> "b"
((Cc"a"*Cc(nil)):Cg"" * Cb"" * Cb""):prmatch"foo"    --> "a" <nil> "a" <nil>

               Cc"b":Cg""              :prmatch"foo"  --> 1  
              (Cc"b":Cg""):Cg()        :prmatch"foo"  --> ""  
(Cc"a":Cg"" * (Cc"b":Cg""):Cg()       ):prmatch"foo"  --> ""
(Cc"a":Cg"" * (Cc"b":Cg""):Cg() * Cb""):prmatch"foo"  --> "" "a"




#####
#
# lepg-0.12
# 2014feb08
#
#####

# «lpeg-0.12» (to ".lpeg-0.12")
# http://www.inf.puc-rio.br/~roberto/lpeg/lpeg-0.12.tar.gz
# http://www.inf.puc-rio.br/~roberto/lpeg/lpeg-1.0.1.tar.gz <- use this
#*
rm -Rv ~/usrc/lpeg-0.12/
tar -C ~/usrc/ -xvzf \
  /home/edrx/snarf/http/www.inf.puc-rio.br/~roberto/lpeg/lpeg-0.12.tar.gz
cd     ~/usrc/lpeg-0.12/

#*
# «lpeg-re» (to ".lpeg-re")
# (code-c-d "lpeg" "~/usrc/lpeg-0.12/")
# (find-lpegfile "")
# (find-lpegfile "re.lua")
# (find-lpegw3m  "re.html")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
userocks()
require "re"
b      = re.compile[[  balanced <- "(" ([^()] / balanced)* ")"  ]]
rev    = re.compile[[ R <- (!.) -> '' / ({.} R) -> '%2%1']]
record = re.compile[[
  record <- {| field (',' field)* |} (%nl / !.)
  field <- escaped / nonescaped
  nonescaped <- { [^,"%nl]* }
  escaped <- '"' {~ ([^"] / '""' -> '"')* ~} '"'
]]

print(b:match"(ab(cd)ef(gh)ij(kl))")     --> 21
print(b:match"(ab(cd)ef(gh)ij(kl))mn")   --> 21
print(rev:match"0123456789")   --> 9876543210


# «lpeg-re-find» (to ".lpeg-re-find")
# (code-c-d "lpeg" "~/usrc/lpeg-0.12/")
# (find-lpegfile "re.lua" "local function find (s, p, i)")







#####
#
# lpeg quickref
# 2007mar05
#
#####

# «lpeg-quickref»  (to ".lpeg-quickref")
# (find-es "lua-intro" "lpeg-quickref")
# http://www.inf.puc-rio.br/~roberto/lpeg.html
# (find-lpegfile "lpeg.c")
# (find-lpegfile "lpeg.c" "{\"match\", matchl},")
# (find-lpegw3m "lpeg.html")
# (find-lpegw3m "lpeg.html#f-match")
# (find-lpegw3m "lpeg.html#captures")
# (find-lpegw3m "lpeg.html#op-p")
# (find-lpegw3m "lpeg.html#op-p" "match-time")
# (find-lpegw3m "lpeg.html#matchtime")

# (find-lpegw3m "lpeg.html#grammar")
# (find-lpegw3m "lpeg.html#cap-g")
# (find-lpegw3m "lpeg.html#cap-b")
# (find-lpegw3m "lpeg.html#ex" "Name-value lists")
# (find-lpegw3m "lpeg.html#ex" "Lua's long strings" "Cb")

lpeg.P(str)    matches str
lpeg.P(0)      matches always
lpeg.P(1)      matches one char (".")
lpeg.P(2)      matches two chars ("..")
lpeg.P(-1)     matches is there isn't another char (end of string)
lpeg.P(-2)     matches if there aren't two more chars
lpeg.P(p)      return the pattern p unmodified
lpeg.P(f)      if f(subj, pos) returns a valid newpos then matches until it
lpeg.P(gra)    matches the first entry (gra[1]) in the grammar gra (a table)
lpeg.V(2)      matches the second entry (gra[2]) in the grammar above this
lpeg.R("az", "AZ") matches any char in ranges ("[A-Za-z]")
lpeg.S("abc")  matches any char in set ("[abc]")
#patt          like patt, but without consuming input
-patt          like #patt, but negating the result
p1 * p2        concatenation: "p1p2"
p1 + p2        bounded prioritized choice - roughly like "p1|p2"
p1 - p2        equivalent to -p2 * p1
1 - cset       a char not in cset
patt ^ 0       at least 0 occurrences of patt; i.e., "patt*"
patt ^ 1       at least 1 occurrence  of patt; i.e., "patt+"
patt ^ 2       at least 2 occurrences of patt
patt ^ -1      at most  1 occurrence  of patt; i.e., "patt?"
patt ^ -2      at most  2 occurrences of patt

lpeg.Carg(n)     the value of the n^th extra argument to lpeg.match
lpeg.Cc(a,b,c)   constant: captures a, b, c
lpeg.Cp()        the current position

patt:C()      the match for patt, then patt's other captures
patt:Cf(f)    folding: if patt returns a,b,c,d then f(f(f(a,b),c),d)
patt:Ct()     a table with all captures from patt
patt / "_%2_" if patt captured "foo" and "bar" then "_bar_"
patt / T      T[c], where c is the (first) capture of patt
patt / f      if patt returns a,b,c,d then this returns f(a,b,c,d)
patt:Cmt(f)   if patt returns a,b,c,d then run (at match-time):
                f(subj, pos, a, b, c, d) => newpos, x, y, z
              which succeeds with values x, y, z if newpos is a number or true,
              fails if newpos is nil or false

lpeg.Cb(name) the values produced by the previous group capture named name
patt:Cg()     the values produced by patt
patt:Cg(name) the values produced by patt, tagged with name                                      
patt:Cs()     the match for patt with the values from nested captures replacing their matches               

-- (find-lpegw3m "lpeg.html#captures")
-- (find-lpegw3m "lpeg.html#captures" "match-time")
-- (find-lpegw3m "lpeg.html#matchtime")
-- (find-lpegw3m "lpeg.html#cap-arg")
-- (find-lpegw3m "lpeg.html#cap-b")
-- (find-lpegw3m "lpeg.html#cap-t")


lpeg.C(patt)   the substring matched by patt (then patt's other captures)
lpeg.Cc(a,b,c) matches the empty string, captures a,b,c
lpeg.Cs(patt)  the substring matched by patt, after substitutions
lpeg.Ct(patt)  all captures made by patt as a table
patt / f       if patt captured a,b,c then f(a, b, c)
patt / "_%2_"  if patt captured "foo" and "bar" then "_bar_"
patt / tbl     if patt captured a and b then tbl[a]




#####
#
# A Trace debugger for Lpeg
# 2012may29
#
#####

# «lpeg-trace»  (to ".lpeg-trace")
-- Trace debugger for Lpeg:
-- http://lua-users.org/lists/lua-l/2009-10/msg00774.html
-- http://article.gmane.org/gmane.comp.lang.lua.general/91553
-- http://article.gmane.org/gmane.comp.lang.lua.general/91557
for k, p in pairs(grammar) do
  local enter = lpeg.Cmt(lpeg.P(true), function(s, p, ...)
      print("ENTER", k) return p end);
  local leave = lpeg.Cmt(lpeg.P(true), function(s, p, ...)
      print("LEAVE", k) return p end) * (lpeg.P("k") - lpeg.P "k");
  grammar[k] = lpeg.Cmt(enter * p + leave, function(s, p, ...)
      print("---", k, "---") print(p, s:sub(1, p-1)) return p end)
end





#####
#
# lpeg.Cmt
# 2012may03
#
#####

# «lpeg.Cmt»  (to ".lpeg.Cmt")
# (find-angg "LUA/lua50init.lua" "loadlpeg")
# (find-lpegw3m "lpeg.html#f-match")
# (find-lpegw3m "lpeg.html#captures")
# (find-lpegw3m "lpeg.html#op-p")
# (find-lpegw3m "lpeg.html#op-p" "match-time")
# (find-lpegw3m "lpeg.html#matchtime")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
userocks()
loadlpeg()

Digit = lpeg.R "09"
Num = Digit^1
Space  = lpeg.P " "
Spaces = Space ^ 0
S      = Spaces

Numn = Num / tonumber
Digit:test "123 456"
Num  :test "123 456"
Numn :test "123 456"

(Numn * S):test "123 456"
(Numn * S * Numn):test "123 456 789"

lpeg.P(function(...) PP(...) end):test  "123 456"
lpeg.P(function(...) PP(...) end):match("123 456")
lpeg.P(function(...) PP(...) end):match("123 456", 1)
lpeg.P(function(...) PP(...) end):match("123 456", 2)

K = function (val) return function (...) PP(...); return val end end
Num = Digit^0
Numn = Num / function (s) return s+0 end





#####
#
# lpeg example: arithmetic expressions, take 1
# 2007mar05
#
#####

# «lpeg-ex-arith-1»  (to ".lpeg-ex-arith-1")
# (find-lpegfile "")
# (find-lpegw3m "doc.html")
# (find-lpegw3m "doc.html#ex")
# http://www.inf.puc-rio.br/~roberto/lpeg.html#ex

* (eepitch-lua51)
loadlpeg()

-- Lexical Elements
-- local Space Number, FactorOp, TermOp, Open, Close
Space = lpeg.S(" \n\t")^0
Number = lpeg.C(lpeg.P"-"^-1 * lpeg.R("09")^1) * Space
FactorOp = lpeg.C(lpeg.S("+-")) * Space
TermOp = lpeg.C(lpeg.S("*/")) * Space
Open = "(" * Space
Close = ")" * Space

-- Grammar
-- local V
-- local Exp, Term, Factor
V = lpeg.V
Exp, Term, Factor = 1, 2, 3
G = lpeg.P{
  [Exp]    = lpeg.Ct(V(Factor) * (FactorOp * V(Factor))^0);
  [Factor] = lpeg.Ct(V(Term) * (TermOp * V(Term))^0);
  [Term]   = Number + Open * V(Exp) * Close;
}

G = Space * G * -1

-- Evaluator
function eval (x)
  if type(x) == "string" then
    return tonumber(x)
  else
    local op1 = eval(x[1])
    for i = 2, #x, 2 do
      local op = x[i]
      local op2 = eval(x[i + 1])
      if (op == "+") then op1 = op1 + op2
      elseif (op == "-") then op1 = op1 - op2
      elseif (op == "*") then op1 = op1 * op2
      elseif (op == "/") then op1 = op1 / op2
      end
    end
    return op1
  end
end

-- Parser/Evaluator
function evalExp (s)
  local t = lpeg.match(G, s)
  if not t then error("syntax error", 2) end
  return eval(t)
end

-- small example
print(evalExp"3 + 5*9 / (1+1) - 12")

G:print()




#####
#
# lpeg example: arithmetic expressions, take 2
# 2007mar05
#
#####

# «lpeg-ex-arith-2»  (to ".lpeg-ex-arith-2")
# (find-lpegfile "")
# (find-lpegw3m "doc.html")
# (find-lpegw3m "doc.html#ex")
# http://www.inf.puc-rio.br/~roberto/lpeg.html#ex

* (eepitch-lua51)
loadlpeg()

-- Lexical Elements
-- local Space Number, FactorOp, TermOp, Open, Close
Space = lpeg.S(" \n\t")^0
Number = lpeg.C(lpeg.P"-"^-1 * lpeg.R("09")^1) * Space
FactorOp = lpeg.C(lpeg.S("+-")) * Space
TermOp = lpeg.C(lpeg.S("*/")) * Space
Open = "(" * Space
Close = ")" * Space

-- Auxiliary function
function eval (v1, op, v2)
  if (op == "+") then return v1 + v2
  elseif (op == "-") then return v1 - v2
  elseif (op == "*") then return v1 * v2
  elseif (op == "/") then return v1 / v2
  end
end

-- Grammar
-- local V
-- local Exp, Term, Factor
V = lpeg.V
Exp, Term, Factor = 1, 2, 3
G = lpeg.P {
  [Exp] = lpeg.Ca(V(Factor) * (FactorOp * V(Factor) / eval)^0);
  [Factor] = lpeg.Ca(V(Term) * (TermOp * V(Term) / eval)^0);
  [Term] = Number / tonumber + Open * V(Exp) * Close;
}

-- small example
print(lpeg.match(G, "3 + 5*9 / (1+1) - 12"))

G:print()






#####
#
# lpeg patterns as several layers
# 2007mar02
#
#####

# «lpeg-layers» (to ".lpeg-layers")
# (find-fline "~/LOGS/2007mar01.lua" "pattern-with-captures")
# (find-fline "~/LOGS/2007mar01.lua")
# (find-iconbookpage (+ 22 87))
# (find-iconbookpage (+ 22 305))

<edrx> as I understand it there's the PEG layer, where we have just
       patterns that can succeed or fail, but we don't have a way to
       specify and return captures
<edrx> on top of that the full thing with the captures is built - and
       I imagine that there should be a way to "project" a
       pattern-with-captures into the world of
       patterns-that-just-succeed-or-fail
<edrx> supposing that this guess is right
<edrx> I think that there are also some basic functions to lift a
       pattern-that-can-just-succeed-or-fail
<edrx> to a pattern-with-captures
<edrx> like: in case of success return the match as a string (a
       substring of the subject), or return the starting point of the
       match, or the end of the match
<edrx> and there are also ways to build bigger pattern-with-captures
       from smaller patterns-that-just-succeed-or-fail and
       patterns-with-captures
<edrx> hmmm, actually it seems that there's a natural embedding of the
       world of patterns-that-just-succeed-or-fail into the world of
       patterns-with-captures
<edrx> a pattern-that-just-succeed-or-fail returns the position of the
       end of the match when it succeeds and nil when it fails
<edrx> hmmm again
<edrx> it seems that there is also the world of
       patterns-that-might-be-resumed versus
       patterns-that-on-success-have-no-backtracking-information




#####
#
# parsing elisp hyperlinks with lpeg
# 2007mar14
#
#####

# «lpeg-elisp-hyperlinks»  (to ".lpeg-elisp-hyperlinks")

* (eepitch-lua51)
loadlpeg()

SStringChar = 1 - lpeg.S "\"\n"
SStringBsl  = "\\" * (1 - lpeg.S "\n")
SString     = "\"" * SStringChar^0 * "\""

SNumber = lpeg.P"-"^-1 * lpeg.R"09"^1

SNonSymbolChar = lpeg.S "\"#'(),.[\\]`"
SSymbolChar    = lpeg.R "!~" - SNonSymbolChar - lpeg.S "{}"
SSymbol        = SSymbolChar^1

SAtom = SString + SNumber + SSymbol

SSpace  = lpeg.S " \t"
SSpaces = SSpace^1

subj  = [[find-angg ".emacs" "foo"]]
subj2 = [[find-ongg ".emacs" "foo"]]
M  = function (pat) io.write("lpeg.match: "); PP(lpeg.match(pat, subj)) end
M2 = function (pat) io.write("lpeg.match: "); PP(lpeg.match(pat, subj2)) end

M(SSymbol)
M(lpeg.C(SSymbol) * (SSpaces * lpeg.C(SAtom))^0)
M (SSymbol / hyperlinksymbols * (SSpaces * lpeg.C(SAtom))^0)
M2(SSymbol / hyperlinksymbols * (SSpaces * lpeg.C(SAtom))^0)

M (SSymbol / PPP("SSymbol:") * (SSpaces * lpeg.C(SAtom))^0)
M (SSymbol * lpeg.P(PPP("Pf:")) * (SSpaces * lpeg.C(SAtom))^0)
M (SSymbol * lpeg.P(function (subj, pos) return pos end) * (SSpaces * lpeg.C(SAtom))^0)
M (lpeg.C(SSymbol) * lpeg.P(function (subj, pos) return pos end) * (SSpaces * lpeg.C(SAtom))^0)
M (lpeg.C(SSymbol) * lpeg.P(function (subj, pos) return nil end) * (SSpaces * lpeg.C(SAtom))^0)

flag = true
M (lpeg.C(SSymbol) * lpeg.P(function (subj, pos) return flag and pos end) * (SSpaces * lpeg.C(SAtom))^0)
flag = false
M (lpeg.C(SSymbol) * lpeg.P(function (subj, pos) return flag and pos end) * (SSpaces * lpeg.C(SAtom))^0)

Flag = lpeg.P(function (subj, pos) return flag and pos end)
flag = true
M (lpeg.C(SSymbol) * Flag * (SSpaces * lpeg.C(SAtom))^0)
flag = false
M (lpeg.C(SSymbol) * Flag * (SSpaces * lpeg.C(SAtom))^0)

flag = true
M (SSymbol / PPP("/f:") * Flag * (SSpaces * lpeg.C(SAtom))^0)
flag = false
M (SSymbol / PPP("/f:") * Flag * (SSpaces * lpeg.C(SAtom))^0)
-- Oh, no!...
-- The "f" in "patt / f" is only executed after the full pattern succeds...

SetMark = lpeg.P(function (subj, pos) mark = pos; return pos end)
SymbolIsGood = lpeg.P(function (subj, pos)
    local str = string.sub(subj, mark, pos - 1)
    PPP("SIG:")(str)
    return (str ~= "find-ongg") and pos
  end)

M (SetMark * lpeg.C(SSymbol) * SymbolIsGood * (SSpaces * lpeg.C(SAtom))^0)
M2(SetMark * lpeg.C(SSymbol) * SymbolIsGood * (SSpaces * lpeg.C(SAtom))^0)

-- f = function (subj, mark, pos) ... return boolean end
lpeg_filter = function (patt, f)
    local mark
    return lpeg.P(function (subj, pos) mark = pos; return pos end) * patt *
           lpeg.P(function (subj, pos) return f(subj, mark, pos) and pos end)
  end
-- f = function (str) ... return boolean end
lpeg_strfilter = function (patt, f)
    local mark
    return lpeg.P(function (subj, pos) mark = pos; return pos end) * patt *
           lpeg.P(function (subj, pos) return f(string.sub(subj, mark, pos - 1)) and pos end)
  end

-- f = function (str) ... return boolean end
lpeg_strfilter = function (patt, f)
    return lpeg_filter(patt, function (subj, mark, pos)
        return f(string.sub(subj, mark, pos - 1))
      end)
  end

M (lpeg_strfilter(lpeg.C(SSymbol), function (str) return str ~= "find-ongg" end) * (SSpaces * lpeg.C(SAtom))^0)
M2(lpeg_strfilter(lpeg.C(SSymbol), function (str) return str ~= "find-ongg" end) * (SSpaces * lpeg.C(SAtom))^0)

-- The (good) "head symbols" are the ones that we know how to htmlize.
headsymbols = {}
for _,s in ipairs(split("to find-fline find-angg")) do
  headsymbols[s] = s
end

lpeg_intable = function (patt, tbl)
    local mark
    return lpeg.P(function (subj, pos) mark = pos; return pos end) * patt *
           lpeg.P(function (subj, pos) return tbl[string.sub(subj, mark, pos - 1)] and pos end)
  end

M (lpeg_strfilter(lpeg.C(SSymbol), function (str) return headsymbols[str] end) * (SSpaces * lpeg.C(SAtom))^0)
M2(lpeg_strfilter(lpeg.C(SSymbol), function (str) return headsymbols[str] end) * (SSpaces * lpeg.C(SAtom))^0)

M (lpeg.C(lpeg_intable(SSymbol, headsymbols)) * (SSpaces * lpeg.C(SAtom))^0)
M2(lpeg.C(lpeg_intable(SSymbol, headsymbols)) * (SSpaces * lpeg.C(SAtom))^0)

SHeadSymbol = lpeg_intable(SSymbol, headsymbols)



-- (find-lpegw3m "doc.html" "lpeg.P (value)" "If the argument is a function")
-- (find-lpegw3m "doc.html#captures")
-- (find-lpegw3m "doc.html#captures" "patt / function")

Hypothesis: patterns with captures are really a separate layer on top
of simple patterns; in order to make a pattern fail depending on
captured values I need to "move down" some values using, say, a global
variable "foo" and

  pattwithcapturesthanchangesfoo *
  lpeg.P(function (subj, pos) return foo and pos end)

No, that doesn't work - I have to use lpeg.P(function ... end) twice.

What is the exact moment in which a pattern is considered to have been
matched, and its captures are converted from "instructions for
captures" into "the values of the captures"?

-- (find-lpegfile "lpeg.c")
-- (find-lpegfile "lpeg.c" "#if defined(DEBUG)")
-- (find-lpegfile "lpeg.c" "static const char *match ")
-- (find-lpegfile "lpeg.c" "static int matchl ")



#####
#
# lpeg-debug
# 2015oct11
#
#####

# «lpeg-debug» (to ".lpeg-debug")
# https://github.com/pkulchenko/PegDebug
# https://github.com/pkulchenko/PegDebug/blob/master/src/pegdebug.lua
# https://nmap.org/nsedoc/lib/lpeg-utility.html
# http://lua-users.org/lists/lua-l/2014-09/msg00489.html



#####
#
# LpegLabel
# 2016sep03
#
#####

# «lpeglabel» (to ".lpeglabel")
# https://github.com/sqmedeiros/lpeglabel
# https://mail.google.com/mail/ca/u/0/#inbox/15638e09aa7127d6
# (find-git-links "https://github.com/sqmedeiros/lpeglabel" "lpeglabel")
# (code-c-d "lpeglabel" "~/usrc/lpeglabel/")
# (find-lpeglabelfile "")
# (find-gitk "~/usrc/lpeglabel/")




#####
#
# Roberto Ierusalimschy's solution to the SHeadSymbol problem
# 2007mar15
#
#####

# «sheadsymbol-roberto»  (to ".sheadsymbol-roberto")
# http://lua-users.org/lists/lua-l/2007-03/msg00355.html
# http://lua-users.org/lists/lua-l/2007-03/msg00358.html
# (find-blogmefile "text2html.lua")

* (eepitch-lua51)
loadlpeg()

--------[ Anchor ]--------

-- (find-anggfile "TH/Generate")
-- (find-anggfile "TH/Generate" "txt2html")

AnchorChar = lpeg.R ...
Anchor = "«" * AnchorChar^1 * "»"

--------[ Url ]--------

UrlProtocol = lpeg.P("http") + lpeg.P("ftp") + lpeg.P("shttp")

UrlDomainChar = lpeg.R("az", "09") + lpeg.S("-")
UrlDomain     = UrlDomainChar^1 * ("." * UrlDomainChar^1)^1

UrlPathChar = ...


--------[ SSexpLink ]--------

SStringChar = 1 - lpeg.S "\"\n"
SStringBsl  = "\\" * (1 - lpeg.S "\n")
SString     = "\"" * SStringChar^0 * "\""

SNumber = lpeg.P"-"^-1 * lpeg.R"09"^1

SNonSymbolChar = lpeg.S "\"#'(),.[\\]`"
SSymbolChar    = lpeg.R "!~" - SNonSymbolChar - lpeg.S "{}"
SSymbol        = SSymbolChar^1

headsymbols = { ["info"]=true, ["man"]=true }

SHeadSymbol = lpeg.P(function (subj, pos)
    local e = lpeg.match(SSymbol, subj, pos)
    if not e then return nil end
    local symbol = string.sub(subj, pos, e - 1)
    return headsymbols[symbol] and pos
  end)

SAtom = SString + SNumber + SSymbol

SSpace  = lpeg.S " \t"
SSpaces = SSpace^1

Eos = lpeg.P(-1)
Eol = -(lpeg.S "\n" + Eos)

SSexpLink = "(" * lpeg.C(SHeadSymbol) * (Spaces * lpeg.C(SAtom))^0 * ")" * Eol




#####
#
# a bug in lpeg-0.5
# 2007mar22
#
#####

# «lpeg-0.5-bug»  (to ".lpeg-0.5-bug")
# http://lua-users.org/lists/lua-l/2007-03/msg00616.html
# (find-angg "LUA/lua50init.lua" "loadlpeg")

* (eepitch-lua51)
package.cpath = "/home/edrx/usrc/lpeg-0.4/?.so"
require "lpeg"
print(lpeg.match("<" * lpeg.C(lpeg.R("az")^1) * ">", "<foo> bar"))

* (eepitch-lua51)
package.cpath = "/home/edrx/usrc/lpeg-0.5/?.so"
require "lpeg"
print(lpeg.match("<" * lpeg.C(lpeg.R("az")^1) * ">", "<foo> bar"))

# (eekill "A bug in lpeg-0.5")
#
Here's a bug that I found in lpeg-0.5... compare the two transcripts
below, the output "foo>" is wrong.

Lua 5.1.1  Copyright (C) 1994-2006 Lua.org, PUC-Rio
> package.cpath = "/home/edrx/usrc/lpeg-0.4/?.so"
> require "lpeg"
> print(lpeg.match("<" * lpeg.C(lpeg.R("az")^1) * ">", "<foo> bar"))
foo
>

Lua 5.1.1  Copyright (C) 1994-2006 Lua.org, PUC-Rio
> package.cpath = "/home/edrx/usrc/lpeg-0.5/?.so"
> require "lpeg"
> print(lpeg.match("<" * lpeg.C(lpeg.R("az")^1) * ">", "<foo> bar"))
foo>
>

Does that happen on other people's machines too? I'm using Debian
stable (gcc 3.3.5) on an i386...

  Cheers,
    Eduardo Ochs
    eduardoochs@gmail.com
    http://angg.twu.net/







#####
#
# loadstring and eof
# 2007jan17
#
#####

# «loadstring_and_eof»  (to ".loadstring_and_eof")
# (find-es "tcl" "info_complete")

<edrx> hi all - sorry if this is an obvious questions (pointers
       welcome) but: suppose that I have my own function for reading a
       line, "getline", say - how do I implement something like lua's
       interactive mode - in lua - using it and the debug library? I
       need to concatenate the lines that I've read and see if the
       result either (1) is a complete command, (2) is an incomplete
       command, (3) is "wrong" - how do I distinguish betwe
<edrx> en these three cases?
<lhf> btw, the HOPL paper is done. managed to mention you wrt
      metamethods.
<rici> lhf: thanks
<rici> edrx: do it the way lua.c does
<rici> try to compile the line, and see what error you get, if any
<lhf> try loadstring. if it does not fail, run the chunk. if it fails,
      check the message for eof.
<rici> right

# (find-fline "~/LOGS/2007jan17.lua" "check the message for eof")
# (find-lua51file "src/")
# (find-lua51file "src/lparser.c")
# (find-lua51file "src/lparser.c" "unexpected symbol")
# (find-lua51file "src/lua.c" "<eof>")

* (eepitch-lua51)
* (eepitch-lua50)
* (eechannel-xterm "A")

-- «incompletep»  (to ".incompletep")
--
incompletepat = ": unexpected symbol near '<eof>'$"
incompletep   = function (errmsg)
    if errmsg and string.find(errmsg, incompletepat) then return true end
  end
myloadstring = function (T)
    T.code, T.err = loadstring(table.concat(T, "\n"))
    T.incomplete  = incompletep(T.err)
    return T
  end
myreadmore = function (T)
    io.write(prompt or (table.getn(T) == 0 and "-> " or "->> "))
    local line = io.read()
    if line then table.insert(T, line); return true end
  end
myreadlines = function (T)
    if myreadmore(T) then
      while myloadstring(T).incomplete and myreadmore(T) do end
    end
    return T
  end

T = {}; PP(myreadlines(T))
  print(
  22+33)
PP(T)



#####
#
# ldb (from .tgz)
# 2007apr29
#
#####

# «ldb-from-tgz»  (to ".ldb-from-tgz")
# http://primero.ricilake.net:8008/ldb/
# http://primero.ricilake.net/lua/ldb-20070420.tar.gz
#*
rm -Rv ~/usrc/ldb/
tar -C ~/usrc/ -xvzf \
  $S/http/primero.ricilake.net/lua/ldb-20070420.tar.gz
cd     ~/usrc/ldb/

#*
# (find-es "davinci")
# (find-angg ".emacs" "davinci")
# (find-angg "LUA/lua50init.lua" "loadldb")

# (code-c-d "ldb" "~/usrc/ldb/" :grep)
# (find-ldbfile "")
# (find-ldbfile "ldb")
# (find-ldbfile "ldb.lua")


* (eepitch-kill)
* (eepitch-at-dir-comint "~/usrc/ldb/" "ldb" "lua51")
ldb = require "ldb"
ldb()
help
help topics

help copyright
help intro
help version
help clocal
help context
help getinfo
help here
help magic
help tailcall

, PP(1+2)
help exec
help print
,, PP(1+2)
,, PP(alias)
,, PP(keys(splain))
,, PP(keys(command))
,, PP(command)
,, error("sja")

,, PP(keys(getfenv()))
,, PP(keys(getfenv(1)))
bt

= getfenv()
= getmetatable(getfenv())
= PP(keys(getmetatable(getfenv())))
= _G
, PP(keys(getfenv()))

-- =  expr
-- == expr   print expr using the ldb environment
-- ,, expr    exec expr using the ldb environment
-- .= expr   same as "== expr"
-- ., expr   same as ",, expr"


-- (find-pilfile "")
-- (find-pilw3m "23.html")
-- (find-pilw3m "23.1.html")
-- (find-pilw3m "23.1.1.html")
-- (find-pilw3m "23.1.2.html")
-- (find-pilw3m "23.2.html")
-- (find-pilw3m "23.3.html")

-- (find-ldbfile "ldb.lua")



= env

PP(keys(package))
PP(keys(package.preload))
PP(keys(package.loaded))


= ldb
PP(keys(ldb))


PP(keys(package))


= splain
= ldb









#####
#
# ldb - rici lake's replacement for debug.debug
# 2007apr05
#
#####

# «ldb»  (to ".ldb")
# (to "xpcall")
# (find-angg "LUA/lua50init.lua" "loadldb")
# (find-fline "~/LOGS/2007apr04.lua")
# (find-fline "~/LOGS/2007apr04.lua" "<rici> debug.traceback = ldb")
# Rici keeps an old version of ldb at this url:
# http://primero.ricilake.net/lua/ldb.lua
# The new version has to be fetched by CVStrac from:
# http://primero.ricilake.net:8008/ldb/getfile?f=ldb/ldb.lua

# Download from cvstrac (2007apr12):
* (eepitch-shell)
cd ~/LUA/
{ URL='http://primero.ricilake.net:8008/ldb/getfile?f=ldb/ldb.lua'
  echo "-- From: $URL"
  echo "-- See: (find-es \"lua5\" \"ldb\")"
  echo "--"
  wget -O - $URL
} > ldb.lua

# (find-fline "~/LUA/" "ldb.lua")
# (find-fline "~/LUA/ldb.lua")

* (eepitch-shell)
cd $S/http/primero.ricilake.net/lua/
lua51
ldb = require "ldb"
debug.traceback = ldb
err    = function () print("foo"); io.output():flush(); error("bar") end
inner  = function () return 1+err() end
middle = function () return 1+inner() end
outer  = function () return 1+middle() end
outer()        -- "foo", then traceback
help
backtrace

* (eepitch-shell)
cd $S/http/primero.ricilake.net/lua/
lua51
loadldb()
debug.traceback = ldb
err    = function () print("foo"); io.output():flush(); error("bar") end
inner  = function () return 1+err() end
middle = function () return 1+inner() end
outer  = function () return 1+middle() end
outer()        -- "foo", then traceback
help
backtrace








#####
#
# lua-mode.el
# 2007feb05 / 2017fev01
#
#####

https://github.com/immerrr/lua-mode/

# «lua-mode.el»  (to ".lua-mode.el")


# (find-angg ".emacs" "lua-mode")
# (find-angg "elisp/lua-mode.el")
#
# (code-c-d "luamode" "~/usrc/lua-mode/")
# (find-luamodefile "")
# (find-luamodefile "Makefile")
#
# http://luaforge.net/projects/lua-mode/
# http://luaforge.net/frs/download.php/2074/lua-mode-20061208.tar.gz
# http://luaforge.net/frs/download.php/2471/lua-mode-20070608.tar.gz
#*
tar -C ~/elisp/ -xvzf \
  $S/http/luaforge.net/frs/download.php/2074/lua-mode-20061208.tar.gz
#*
tar -C ~/elisp/ -xvzf \
  $S/http/luaforge.net/frs/download.php/2471/lua-mode-20070608.tar.gz
#*

# (find-available "lua-mode")
# (find-status   "lua-mode")
# (find-vldifile "lua-mode.list")
# (find-udfile   "lua-mode/")

# (find-fline    "~/elisp/lua-mode.el")
# (find-sh "rm -v ~/elisp/lua-mode.el")

# 2011apr22 / 2013sep05:
# Needs: (find-es "emacs" "cask")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# https://github.com/immerrr/lua-mode/
# https://github.com/immerrr/lua-mode.git
rm -Rfv ~/usrc/lua-mode/
cd      ~/usrc/ && \
  git clone https://github.com/immerrr/lua-mode.git
cd      ~/usrc/lua-mode/

# EMACS=emacs-default make compile check
  EMACS=emacs-default make compile
# (find-fline "~/usrc/lua-mode/")
cp -v lua-mode..elc lua-mode.elc 

rm -Rfv ~/usrc/lua-mode/

tar -cvzf ~/tmp/lua-mode-git.tgz lua-mode/

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# (find-fline "~/usrc/lua-mode/")
cp -v ~/usrc/lua-mode/lua-mode.el  ~/elisp/
cp -v ~/usrc/lua-mode/lua-mode.elc ~/elisp/




#####
#
# risclua (for the "\x => x*x end" patch)
# 2006dec04 / 2007feb05
#
#####

# «risclua»  (to ".risclua")
# (to "minimal_GCW_SUGAR")
# http://www.wra1th.plus.com/lua/
# http://www.wra1th.plus.com/lua/risclua.html
# http://www.wra1th.plus.com/lua/book/rb04.html

# (find-fline "/tmp/rlua400.zip")
# (find-fline "/tmp/risclua/")
# (find-man "1 unzip")
# http://www.wra1th.plus.com/lua/zip/Luasrc.zip
# http://www.wra1th.plus.com/lua/zip/rlua401.zip
#*
rm -Rv /tmp/risclua/
mkdir  /tmp/risclua/
cd     /tmp/risclua/
unzip -d /tmp/risclua/ $S/http/www.wra1th.plus.com/lua/zip/rlua401.zip
unzip -d /tmp/risclua/ $S/http/www.wra1th.plus.com/lua/zip/Luasrc.zip
cd     /tmp/risclua/

#*
# (code-c-d "risclua" "/tmp/risclua/")
# (find-riscluafile "")
# (find-riscluafile "c/llex")
# (find-riscluafile "c/llex" "#ifdef GCW_SUGAR")
# (find-lua51file "src/llex.c")
# (find-tkdiff "/tmp/risclua/c/lparser" (ee-lua51file "src/lparser.c"))

rm -Rfv /tmp/lua-5.1.1/
mkdir   /tmp/lua-5.1.1/
tar  -C /tmp/ -xvzf $S/http/www.lua.org/ftp/lua-5.1.1.tar.gz
cd      /tmp/lua-5.1.1/
unzip -j -d src/ $S/http/www.wra1th.plus.com/lua/zip/Luasrc.zip c/lparser

#*
# Some messages about this:
# Mine:     http://lua-users.org/lists/lua-l/2007-02/msg00100.html
#   Fabien: http://lua-users.org/lists/lua-l/2006-12/msg00050.html
#   Wraith: http://lua-users.org/lists/lua-l/2006-12/msg00046.html
# The body of my message was just:

Speaking of syntax for lambdas: in RiscLua a backslash is a synonym
for "function" and "=>" is a synonym for "return". See:

  http://www.wra1th.plus.com/lua/book/rb04.html

The patch that implements that is just what's contained in the two
"#ifdef GCW_SUGAR" blocks in the file "c/llex" of RiscLua's sources
(<http://www.wra1th.plus.com/lua/zip/Luasrc.zip>); this "c/llex"
corresponds to the file "src/llex.c" in the standard Lua sources.

  Cheers,
    Eduardo Ochs
    eduardoochs@gmail.com
    http://angg.twu.net/




#####
#
# functionnames
# 2007feb26
#
#####

# «functionnames»  (to ".functionnames")
# (find-angg "LUA/lua50init.lua" "preparef2n")
# (find-luamanualw3m "#pdf-debug")
# (find-luamanualw3m "#pdf-debug.getinfo")
# (find-es "lua5" "debug.debug")


* (eepitch-lua51)

addfunctionnames = function (fun2name, dictname, dictnamedot, dict)
    fun2name = fun2name or {}
    if dictname then
      return addfunctionnames_(fun2name or {}


makef2n = function (otherdicts)
    local f2n = {}
    local mainsubdicts = "coroutine debug io math os package string table"
    for _,dn = ipairs(split(mainsubdicts)) do
      addfunctionnames(f2n, dn, dn..".", _G[dn])
    end
    for _,dn = ipairs(split(mainsubdicts)) do
      addfunctionnames(f2n, dn, dn..".", _G[dn])
    end
    addfunctionnames(f2n, "_G", "", _G)
    return f2n
  end

_G["---"] = function () print("---") end
f2n = addfunctionnames()
PP(f2n)

functionnames = function ()
    local name2fun = {}
    local fun2name = {}
    local tablenames = split("coroutine debug io math os package string table")
    local addfuns = function (prefix, tbl)
        for name,val in pairs(tbl) do
          if type(val) == "function" then
            fun2name[val] = prefix .. name
            name2fun[prefix .. name] = val
          end
        end
      end
    for _,tablename in ipairs(tablenames) do
      addfuns(tablename .. ".", _G[tablename])
    end
    addfuns("", _G)
    return fun2name, name2fun
  end

f2n, n2f = functionnames()
PP(n2f)

function outer  () middle() end
function middle () inner() end
function inner  ()
    for i=1,5 do
      PP(i, f2n[debug.getinfo(i).func])
    end
    debug.debug()
  end

f2n, n2f = functionnames()

outer()
PP(debug.getinfo(1))
PP(debug.getinfo(1).func)
PP(f2n[debug.getinfo(1).func])
PP(f2n[debug.getinfo(2).func])
PP(f2n[debug.getinfo(3).func])
PP(f2n[debug.getinfo(4).func])
PP(f2n[debug.getinfo(5).func])
PP(debug.getinfo(2))


= functionnames()[require]


PP(debug.getinfo(print))
PP(debug.getinfo(inner))

PP(debug.getinfo(1,"n").name)
function inner  () error("foo") end
PP(debug.getinfo(1,"n").name)





#####
#
# cinvoke
# 2007mar02
#
#####

# «cinvoke»  (to ".cinvoke")
# (find-angg "LUA/lua50init.lua" "loadcinvoke")
# http://cinvoke.teegra.net/     <- 2011jan07
# http://www.nongnu.org/cinvoke/lua.html
# http://download.savannah.nongnu.org/releases/cinvoke/cinvoke-1.0.tgz
#*
rm -Rv ~/usrc/cinvoke-1.0/
tar -C ~/usrc/ -xvzf \
  $S/http/download.savannah.nongnu.org/releases/cinvoke/cinvoke-1.0.tgz
cd     ~/usrc/cinvoke-1.0/

perl configure.pl       |& tee opc
make                    |& tee om
(cd test && ./runtests) |& tee ort

#*
# (code-c-d "cinvoke" "~/usrc/cinvoke-1.0/")
# (find-cinvokefile "")
# (find-cinvokefile "README.txt")
# (find-cinvokefile "bindings/lua/")
# (find-cinvokefile "bindings/lua/socket.lua")
# (find-cinvokefile "bindings/lua/test.lua")

# (find-cinvokefile "bindings/lua/")
# (find-cinvokesh "cd bindings/lua/; make")
# (find-cinvokefile "bindings/lua/Makefile")
# (find-cinvokefile "bindings/lua/Makefile" ".c.o:")
# (find-cinvokefile "bindings/lua/Makefile.templ")

* (eepitch-shell)
cd ~/usrc/cinvoke-1.0/
cd ~/usrc/cinvoke-1.0/bindings/lua/
# make
gcc -g -Wall -DCINVOKE_BUILD -DARCH_GCC_X86_UNIX -fpic \
  -I../../lib -I$LUA51SRC/src \
  -c cinvoke_lua.c -o cinvoke_lua.o
make cinvoke_lua.so
lua51 test.lua
  foo

* (eepitch-shell)
cd ~/usrc/cinvoke-1.0/bindings/lua/
lua51
-- (find-cinvokefile "bindings/lua/test.lua")
require("cinvoke_lua")

* (eepitch-lua51)
oldcpath = package.cpath
package.cpath = "/home/edrx/usrc/cinvoke-1.0/bindings/lua/?.so"
require "cinvoke_lua"
package.cpath = oldcpath

* (eepitch-lua51)
loadcinvoke()
for k,v in pairs(package) do print(k) end
PP(package.preload)
PP(package.loadlib)
for k,v in pairs(package.loaded) do print(k) end
= package.loaded.cinvoke_lua
PP(package.loaders)
= package.cpath
= package.config
= package.path
= package.seeall




#####
#
# calling Tcl from Lua using cinvoke
# 2007mar05
#
#####

# «cinvoke-libtcl»  (to ".cinvoke-libtcl")
# (find-anggfile "LUA/lua50init.lua" "loadcinvoke")
# (find-es "tcl" "tcl_from_c")
# http://www.nongnu.org/cinvoke/lua.html

# (find-tclbook3page 1)
# (find-tclbook3page (+ -250 263))
# (find-tclbook3text)

* (eepitch-lua51)
loadcinvoke()
libtcl = clibrary.new("libtcl8.4.so.0")
TclInterpPtr = Cptr
  PP(libtcl, Cptr, Cstring)
Tcl_CreateInterp    = libtcl:get_function(TclInterpPtr, "Tcl_CreateInterp")
Tcl_Eval            = libtcl:get_function(Cint,         "Tcl_Eval", TclInterpPtr, Cstring)
Tcl_GetStringResult = libtcl:get_function(Cstring,      "Tcl_GetStringResult", TclInterpPtr)
interp = Tcl_CreateInterp()
= Tcl_Eval(interp, "puts Hello")
= Tcl_Eval(interp, "expr 22+33")
= Tcl_GetStringResult(interp)


How do I call Tcl using cinvoke?
To use Tk I will have to have a Tcl word "lua" that blah





#####
#
# tlbridge.c - a Tcl/Tk<->Lua bridge
# 2007mar06
#
#####

# «tlbridge.c»  (to ".tlbridge.c")
# (find-angg "LUA/tlbridge.c")
# (find-angg "LUA/lua50init.lua" "loadtcl")
#*
cd /tmp/
cp -v ~/LUA/tlbridge.c .
gcc --shared -ltcl8.4 \
  -Wall \
  -I$LUA51SRC/src/ -I/usr/include/tcl8.4/ \
  -o tlbridge.so tlbridge.c

# ldd tlbridge.so
lua51 -e 'tcl = require "tlbridge"; print(tcl("expr 22+33"))'
lua51 -e 'tcl = require "tlbridge"; tcl("lua0 foo")'
lua51 -e 'tcl = require "tlbridge"; tcl("lua0 foo bar")'
lua51 -e 'tcl = require "tlbridge"; tcl("lua0 foo {bar bletch}")'
lua51 -e 'tcl = require "tlbridge"; tcl("lua print abc def")'

#*
* (eepitch-shell)
cd /tmp/
lua51

tcl = require "tlbridge"
= tcl("expr 22+33")
= tcl("lua0 foo")
= tcl("lua0 foo bar")
= tcl("lua0 foo {bar bletch}")
= tcl("lua print abc")

#*
# Build in a permanent place: ~/LUA/
# (find-angg "LUA/lua50init.lua" "loadtcl")

cd ~/LUA/
gcc --shared -ltcl8.4 \
  -Wall \
  -I$LUA51SRC/src/ -I/usr/include/tcl8.4/ \
  -o tlbridge.so tlbridge.c

#*
# Danger Will Robinson!
# tlbridge.c: In function `TLBridge_call_lua':
# tlbridge.c:39: warning: passing arg 2 of `Tcl_SetResult' discards qualifiers from pointer target type




#####
#
# luatclbridge.c - a Tcl/Tk<->Lua bridge
# 2007mar06 / 2007may20
#
#####

# «luatclbridge»  (to ".luatclbridge")
# (find-angg "LUA/luatclbridge.c")
# (find-angg "LUA/lua50init.lua" "loadtcl")
# (find-es "tcl" "luatclbridge")
#*
cd /tmp/
cp -v ~/LUA/luatclbridge.c .
gcc --shared -ltcl8.4 \
  -Wall \
  -I$LUA51SRC/src/ -I/usr/include/tcl8.4/ \
  -o ~/.lua51/luatclbridge.so ~/LUA/luatclbridge.c

# ldd luatclbridge.so
lua51 -e 'print(tcl("expr 22+33"))'
lua51 -e 'tcl "lua print args to Lua functions are strings"'
lua51 -e 'tcl "source /usr/lib/tcl8.4/init.tcl"'

#*
* (eepitch-shell)
cd /tmp/
lua51
= tcl("expr 22+33")
= tcl("lua print args to Lua functions are strings")

#*
# Build in a permanent place: ~/LUA/
# (find-angg "LUA/lua50init.lua" "loadtcl")

cd ~/LUA/
gcc --shared -ltcl8.4 \
  -Wall \
  -I$LUA51SRC/src/ -I/usr/include/tcl8.4/ \
  -o luatclbridge.so luatclbridge.c

#*
# Danger Will Robinson!
# luatclbridge.c: In function `LuaTclBridge_call_lua':
# luatclbridge.c:39: warning: passing arg 2 of `Tcl_SetResult' discards qualifiers from pointer target type




# (find-man "3tcl Tcl_SetResult" "TCL_STATIC")
# (find-man "3tcl Tcl_SetResult" "TCL_DYNAMIC")
# (find-man "3tcl Tcl_SetResult" "THE TCL_FREEPROC ARGUMENT")


# (find-tclbookfile "examples.gz" "Chapter 30:")
# (find-tclbook3text)
# (find-fline "/usr/include/tcl8.4/")
# (find-fline "/usr/include/tcl8.4/tclDecls.h" "Tcl_CreateCommand")
# (find-fline "/usr/include/tcl8.4/tcl.h" "typedef int (Tcl_CmdProc)")
# (find-lua51tag "str_format")
# (find-lua51file "src/")
# (find-lua51file "src/lua.h")
# (find-debpkg-links "tcl8.4-doc")
# (find-debpkg-links "tcl8.4-dev")
# (find-debpkg-links "tcl8.4")
# (find-man "3tcl Tcl_Interp")
# (find-man "3tcl Tcl_Eval" "TCL_OK")

# (find-tclbookfile "examples.gz" "Chapter 30:")
# (find-tclbook3text)
# (find-fline "/usr/include/tcl8.4/")
# (find-fline "/usr/include/tcl8.4/tclDecls.h" "Tcl_CreateCommand")
# (find-fline "/usr/include/tcl8.4/tcl.h" "typedef int (Tcl_CmdProc)")





#####
#
# lunatic python
# 2007mar07
#
#####

# «lunatic-python»  (to ".lunatic-python")
# http://lua-users.org/wiki/LunaticPython
# http://labix.org/download/lunatic-python/lunatic-python-1.0.tar.bz2
#*
rm -Rv ~/usrc/lunatic-python-1.0/
tar -C ~/usrc/ -xvjf \
  $S/http/labix.org/download/lunatic-python/lunatic-python-1.0.tar.bz2
cd     ~/usrc/lunatic-python-1.0/

patch -p0 setup.py <<'%%%'
12c12,13
< LUALIBS = ["lua", "lualib"]
---
> # LUALIBS = ["lua", "lualib"]
> LUALIBS = ["lua"]
%%%

patch -p0 src/luainpython.c <<'%%%'
491,496c491,497
< 		luaopen_base(L);
< 		luaopen_table(L);
< 		luaopen_io(L);
< 		luaopen_string(L);
< 		luaopen_debug(L);
< 		luaopen_loadlib(L);
---
> 		luaL_openlibs(L);
> /* 		luaopen_base(L); */
> /* 		luaopen_table(L); */
> /* 		luaopen_io(L); */
> /* 		luaopen_string(L); */
> /* 		luaopen_debug(L); */
> /* 		luaopen_loadlib(L); */
%%%

python setup.py build_ext -I$LUA51SRC/src -L$LUA51SRC/src     |& tee opsbe

#*
# (code-c-d "lpython" "~/usrc/lunatic-python-1.0/")
# (find-lpythonfile "")
# (find-lpythonfile "setup.py")
# (find-lpythonfile "opsbe")

# Now I need to create an example of usage...
# (find-lpythonfile "python.lua")





#*
# (find-w3m "/usr/share/doc/python2.3/html/dist/setup-config.html")
# (find-w3m "/usr/share/doc/python2.3/html/dist/setup-script.html")

* (eepitch-shell)
cd ~/usrc/lunatic-python-1.0/
make                               |& tee om
python setup.py --help             |& tee opsh
python setup.py --help build       |& tee opshb
python setup.py --help build_ext   |& tee opshbe
python setup.py --help-commands    |& tee opshc
python setup.py build              |& tee opsb
python setup.py build_ext          |& tee opsbe

# (find-lpythonfile "")
# (find-lpythonfile "src/luainpython.c" "luaopen_loadlib")
# (find-lpythonfile "Makefile")
# (find-lpythonfile "setup.py")
# (find-lpythonfile "opsh")
# (find-lpythonfile "opshb")
# (find-lpythonfile "opshbe")
# (find-lpythonfile "opshc")

# (find-pylibnode "Process Parameters" "`getenv(varname[, value])'")





#####
#
# kepler
# 2007mar11
#
#####

# «kepler»  (to ".kepler")
# http://luaforge.net/frs/download.php/2050/kepler-1.0.tar.gz
# http://www.keplerproject.org/kepler/install.unix.html
#*
rm -Rv ~/usrc/kepler-1.0/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/2050/kepler-1.0.tar.gz
cd     ~/usrc/kepler-1.0/

#*
# (code-c-d "kepler" "~/usrc/kepler-1.0/")
# (find-keplerfile "")
# (find-keplerfile "configure")

* (eepitch-shell)
cd ~/usrc/kepler-1.0/
./configure --with-lua=$LUA50SRC |& tee oc
./configure --disable-lua |& tee oc

# Seems that I need to copy some ".h"s and ".so"s and executables to
# dirs inside the kepler tree...

# Kepler on thttpd:
# http://lists.luaforge.net/pipermail/kepler-project/2007-January/000419.html




#####
#
# Helper threads
# 2007mar21
#
#####

# «helper-threads»  (to ".helper-threads")
# http://luaforge.net/projects/helper-threads/
# http://luaforge.net/frs/download.php/1513/helper-threads-r4.ZIP





#####
#
# loona
# 2007apr02
#
#####

# «loona»  (to ".loona")
# http://loona.neoscientists.org/download/loona-snapshot.tar.gz
#*
rm -Rv ~/usrc/loona/
tar -C ~/usrc/ -xvzf \
  $S/http/loona.neoscientists.org/download/loona-snapshot.tar.gz
cd     ~/usrc/loona/

#*
# (code-c-d "loona" "~/usrc/loona/")
# (find-loonafile "")
# (find-loonafile "README" "mod_unique")
# (find-loonafile "htdocs/upload.lua")
# (find-loonafile "cgi-bin/")
# (find-loonafile "cgi-bin/cgilua/")
# (find-loonafile "cgi-bin/cgilua/post.lua")




#####
#
# pseudo-spreadsheet
# 2007apr22
#
#####

# «pseudo-spreadsheet»  (to ".pseudo-spreadsheet")
--*
-- (eelua51-bounded)
-- (ee-once (eelua51-bounded))

valor = {}

exp = math.exp
sgn = function (x)
    if x < 0 then return -1 end
    if x > 0 then return  1 end
    return 0
  end

f = function (t)
    return t * (exp(3 / (2 * t)) - exp(-3 / (2 * t))) - 3.2
  end

calcula_CDEFGHIn = function (n)
    local An = valor["A"..n]
    local Bn = valor["B"..n]
    local Cn, Dn, En, Fn, Gn, Hh, In
    Cn = Bn - An
    Dn = f(An)
    En = f(Bn)
    Fn = sgn(Dn * En)
    Gn = (An + Bn) / 2
    Hn = f(Gn)
    In = sgn(Dn * Hn)
    valor["C"..n] = Cn
    valor["D"..n] = Dn
    valor["E"..n] = En
    valor["F"..n] = Fn
    valor["G"..n] = Gn
    valor["H"..n] = Hn
    valor["I"..n] = In
  end

calcula_ABn = function (n)
    local Aanterior = valor["A"..(n-1)]
    local Banterior = valor["B"..(n-1)]
    local Ganterior = valor["G"..(n-1)]
    local Ianterior = valor["I"..(n-1)]
    local An, Bn
    if Ianterior < 0 then
      An = Aanterior
      Bn = Ganterior
    else
      An = Ganterior
      Bn = Banterior
    end
    valor["A"..n] = An
    valor["B"..n] = Bn
  end

valor["A0"] = 2
valor["B0"] = 3
calcula_CDEFGHIn(0)
for i=1,14 do 
  calcula_ABn(i)
  calcula_CDEFGHIn(i)
end

printline = function (n)
    printf("%2d %8.5f %8.5f %8.5f %8.5f %8.5f %2d %8.5f %8.5f %2d\n", n,
       valor["A"..n], valor["B"..n], valor["C"..n], 
       valor["D"..n], valor["E"..n], valor["F"..n], 
       valor["G"..n], valor["H"..n], valor["I"..n])
  end

print("        A        B        C        D        E    F      G        H    I")
print("       a_n      b_n   b_n-a_n   f(a_n)   f(b_n) sgn    m_n   f(m_n) sgnL")
for i=0,14 do printline(i) end

print()
print("Obs: 'sgn'  = sgn(f(a_n) * f(b_n)),")
print("     'sgnL' = sgn(f(a_n) * f(m_n)),")

--[[
Output:
        A        B        C        D        E    F      G        H    I
       a_n      b_n   b_n-a_n   f(a_n)   f(b_n) sgn    m_n   f(m_n) sgnL
 0  2.00000  3.00000  1.00000  0.08927 -0.07343 -1  2.50000 -0.01673 -1
 1  2.00000  2.50000  0.50000  0.08927 -0.01673 -1  2.25000  0.02721  1
 2  2.25000  2.50000  0.25000  0.02721 -0.01673 -1  2.37500  0.00346  1
 3  2.37500  2.50000  0.12500  0.00346 -0.01673 -1  2.43750 -0.00703 -1
 4  2.37500  2.43750  0.06250  0.00346 -0.00703 -1  2.40625 -0.00189 -1
 5  2.37500  2.40625  0.03125  0.00346 -0.00189 -1  2.39062  0.00076  1
 6  2.39062  2.40625  0.01562  0.00076 -0.00189 -1  2.39844 -0.00057 -1
 7  2.39062  2.39844  0.00781  0.00076 -0.00057 -1  2.39453  0.00009  1
 8  2.39453  2.39844  0.00391  0.00009 -0.00057 -1  2.39648 -0.00024 -1
 9  2.39453  2.39648  0.00195  0.00009 -0.00024 -1  2.39551 -0.00007 -1
10  2.39453  2.39551  0.00098  0.00009 -0.00007 -1  2.39502  0.00001  1
11  2.39502  2.39551  0.00049  0.00001 -0.00007 -1  2.39526 -0.00003 -1
12  2.39502  2.39526  0.00024  0.00001 -0.00003 -1  2.39514 -0.00001 -1
13  2.39502  2.39514  0.00012  0.00001 -0.00001 -1  2.39508 -0.00000 -1
14  2.39502  2.39508  0.00006  0.00001 -0.00000 -1  2.39505  0.00000  1

Obs: 'sgn'  = sgn(f(a_n) * f(b_n)),
     'sgnL' = sgn(f(a_n) * f(m_n)),
--]]

--*

--  A    B      C       D       E            F                   G           H             I
-- a_0  b_0  b_0-a_0  f(a_0)  f(b_0)  sgn(f(a_0)*f(b_0))  m_0=(b_0-a_0)/2  f(m_0)  sgn(f(a_0)*f(m_0))



--*
-- (eelua51-bounded)
-- (ee-once (eelua51-bounded))

valor = {}

exp = math.exp
ln  = math.log

phi = function (t)
    local expr = ln(66.5 - 25 * exp(-0.075 * t))
    return (-(expr + ln(70))) / 1.5
  end

calcula_ABn = function (n)
    local Aanterior = valor["A"..(n-1)]
    local An = phi(Aanterior)
    local Bn = An - Aanterior
    valor["A"..n] = An
    valor["B"..n] = Bn
  end

valor["A0"] = 0.2

printline0 = function (n)
    printf("%2d  %8.5f\n",        n, valor["A"..n])
  end
printline = function (n)
    printf("%2d  %8.5f  %8.5f\n", n, valor["A"..n], valor["B"..n])
  end

for i=1,5 do calcula_ABn(i) end

print("        A         B     ")
print("       x_i    x_i-x_(i-1)")
printline0(0)
for i=1,5 do printline(i) end

--[[
Output:
        A         B     
       x_i    x_i-x_(i-1)
 0   0.20000
 1  -5.32208  -5.52208
 2  -5.08259   0.23948
 3  -5.09755  -0.01496
 4  -5.09663   0.00092
 5  -5.09669  -0.00006
--]]

--*

--*
-- (eelua51-bounded)
-- (ee-once (eelua51-bounded))

valor = {}

exp = math.exp
ln  = math.log

f = function (t)
    return 6 * exp(0.075 * t) - 75 * exp(-0.05 * t) - 100
  end
fderiv = function (t)
    return 0.45 * exp(0.075 * t) + 3.75 * exp(-0.05 * t)
  end

calcula_BCn = function (n)
    local An = valor["A"..n]
    local Bn = f(An)
    local Cn = fderiv(An)
    valor["B"..n] = Bn
    valor["C"..n] = Cn
  end

calcula_An = function (n)
    local Aanterior = valor["A"..(n-1)]
    local Banterior = valor["B"..(n-1)]
    local Canterior = valor["C"..(n-1)]
    local An = Aanterior - Banterior / Canterior
    valor["A"..n] = An
  end

valor["A0"] = 50
printline = function (n)
    printf("%2d  %9.5f  %9.5f  %9.5f\n", n,
           valor["A"..n], valor["B"..n], valor["C"..n])
  end

calcula_BCn(0)
for i=1,5 do
  calcula_An (i)
  calcula_BCn(i)
end

print("        A            B         C")
print("       x_i        f(x_i)    f'(x_i)")
for i=0,5 do printline(i) end

--[[
Output:
        A            B         C
       x_i        f(x_i)    f'(x_i)
 0   50.00000  148.97012   19.44231
 1   42.33784   34.57902   11.22223
 2   39.25654    3.44281    9.07503
 3   38.87717    0.04379    8.84532
 4   38.87222    0.00001    8.84237
 5   38.87222    0.00000    8.84237
--]]

--*

--*
-- (eelua51-bounded)
-- (ee-once (eelua51-bounded))

valor = {}

exp  = math.exp
log  = math.log10
sqrt = math.sqrt

f = function (t)
    return log(sqrt(t)) + 2.9 + log(2) - 1 / (4 * sqrt(t))
  end

calcula_Bn = function (n)
    local An = valor["A"..n]
    local Bn = f(An)
    valor["B"..n] = Bn
  end

calcula_An = function (n)
    local Anmenos2 = valor["A"..(n-2)]
    local Anmenos1 = valor["A"..(n-1)]
    local Bnmenos2 = valor["B"..(n-2)]
    local Bnmenos1 = valor["B"..(n-1)]
    local An = (Anmenos2 * Bnmenos1 - Anmenos1 * Bnmenos2) /
               (Bnmenos1 - Bnmenos2)
    valor["A"..n] = An
  end

printline = function (n)
    printf("%2d  %9.5f  %10.6f\n", n, valor["A"..n], valor["B"..n])
  end

valor["A0"] = 0.01;  calcula_Bn(0)
valor["A1"] = 0.02;  calcula_Bn(1)

for i=2,6 do
  calcula_An (i)
  calcula_Bn(i)
end

print("        A            B    ")
print("       x_i        f(x_i)  ")
for i=0,5 do printline(i) end

--[[
Output:
        A            B    
       x_i        f(x_i)  
 0    0.01000   -0.298970
 1    0.02000    0.583778
 2    0.01339    0.103634
 3    0.01196   -0.046160
 4    0.01240    0.002597
 5    0.01238    0.000062
--]]

--*





#####
#
# CGI.lua
# 2007may12
#
#####

# «CGI.lua»  (to ".CGI.lua")
# http://alt.textdrive.com/svn/altdev/LW/CGI.lua
# http://dev.alt.textdrive.com/browser/LW/CGI.lua
# http://www.keplerproject.org/cgilua/manual.html
# (find-es "http" "thttpd")
#*
touch     /var/www/tmp/test.cgi
chmod 755 /var/www/tmp/test.cgi
cat     > /var/www/tmp/test.cgi <<'---'
#!/bin/sh
echo -e "Content-type: text/plain\n"
echo -e "<html>\n<head><title>T</title></head>\n<body>$(date)</body>\n</html>"
---
wget -q -O - http://localhost/tmp/test.cgi

#*
* (eepitch-lua51)
dofile "/home/edrx/LUA/lua50init.lua"
CGI =
dofile "/home/edrx/snarf/http/alt.textdrive.com/svn/altdev/LW/CGI.lua"
-- http://alt.textdrive.com/svn/altdev/LW/CGI.lua
PP(CGI)

#*
touch     /var/www/tmp/test.cgi
chmod 755 /var/www/tmp/test.cgi
cat     > /var/www/tmp/test.cgi <<'---'
#!/home/edrx/bin/lua51
      dofile "/home/edrx/LUA/lua50init.lua"
CGI = dofile "/home/edrx/snarf/http/alt.textdrive.com/svn/altdev/LW/CGI.lua"
print "Content-type: text/plain\n"
print "Hello."
-- PP(CGI)
   PP(CGI:request())
   PP(CGI:request():method())
   PP(CGI:request():parameters())
---
wget -q -O - http://localhost/tmp/test.cgi
wget -q -O - http://localhost/tmp/test.cgi'?FOO=BAR'
date > /tmp/date.txt
curl -F file=@/tmp/date.txt http://localhost/tmp/test.cgi
# oops, it doesn't support file uploads...

#*
# (find-udfile "curl/MANUAL.gz" "curl -F \"file=@cooltext.txt\"")

# (find-status   "curl")
# (find-vldifile "curl.list")
# (find-udfile   "curl/")
# (find-man "1 curl")
# (find-man "1 curl" "-F, --form <name=content>")




#####
#
# cgilua-5.0.1
# 2007may13
#
#####

# http://luaforge.net/frs/download.php/1770/cgilua-5.0.1.tar.gz
#*
rm -Rv ~/usrc/cgilua-5.0.1/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/1770/cgilua-5.0.1.tar.gz
cd     ~/usrc/cgilua-5.0.1/

#*
# (code-c-d "cgilua" "~/usrc/cgilua-5.0.1/" :grep)
# (find-cgiluafile "")
# (find-cgiluafile "src/cgilua/")
# (find-cgiluafile "src/cgilua/post.lua")
# (find-cgiluafile "tests/")
# (find-cgiluaw3m "doc/us/manual.html")
# (find-cgiluaw3m "doc/us/manual.html#parameters")
# (find-cgiluaw3m "doc/us/reference.html")
# (find-cgiluaw3m "doc/us/reference.html#variables")
# (find-cgiluaw3m "doc/us/sapi.html")
# (find-cgiluaw3m "doc/us/sapi.html" "and CGI, FastCGI")
# http://hoohoo.ncsa.uiuc.edu/cgi/env.html
# (find-cgiluagrep "grep -niH -e sapi doc/us/*")
# (find-cgiluagrep "grep -niH -e sapi src/cgilua/*")
# (find-cgiluagrep "grep -niH -e Response src/cgilua/*")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
package.path  = "/home/edrx/usrc/cgilua-5.0.1/src/?.lua;"  ..package.path
package.cpath = "/home/edrx/usrc/luafilesystem-1.2.1/src/?.so;"..package.cpath
-- SAPI = {}
require "cgilua.cgilua"



#####
#
# luafilesystem-1.2.1
# 2007may13
#
#####

# http://luaforge.net/frs/download.php/2381/luafilesystem-1.2.1.tar.gz
#*
rm -Rv ~/usrc/luafilesystem-1.2.1/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/2381/luafilesystem-1.2.1.tar.gz
cd     ~/usrc/luafilesystem-1.2.1/

cat >> config <<'---'
LUA_LIBDIR = $(HOME)/usrc/lua-5.1.2/src
LUA_INC    = $(HOME)/usrc/lua-5.1.2/src
---

make |& tee om
ln -s lfs.so.1.2.1 src/lfs.so

#*
# (code-c-d "luafs" "~/usrc/luafilesystem-1.2.1/")
# (find-luafsfile "")
# (find-luafsfile "config")
# (find-luafsfile "src/")




#####
#
# lua-filesystem
# 2015jan22
#
#####

# «lua-filesystem» (to ".lua-filesystem")
# (find-status   "lua-filesystem")
# (find-vldifile "lua-filesystem:i386.list")
# (find-udfile   "lua-filesystem/")




#####
#
# kepler-1.1
# 2007may13
#
#####

# «kepler-1.1»  (to ".kepler-1.1")
# http://kepler-tmp.dreamhosters.com/en/UNIX_Installation
# http://www.keplerproject.org/wiki/US/HomePage
# http://www.keplerproject.org/kepler-1.1-snapshot-20070511-1628.tar.gz
# On thttpd:
# http://lists.luaforge.net/pipermail/kepler-project/2007-January/000419.html
# http://lists.luaforge.net/pipermail/kepler-project/2006-November/000301.html
#*
rm -Rv ~/usrc/kepler-1.1/
tar -C ~/usrc/ -xvzf \
  $S/http/www.keplerproject.org/kepler-1.1-snapshot-20070511-1628.tar.gz
cd     ~/usrc/kepler-1.1/

./configure --prefix=$HOME/usrc/kepler --launcher=cgi --without-readline  |& tee oc
make         |& tee om
make install |& tee omi

#*
# (code-c-d "keplersrc" "~/usrc/kepler-1.1/")
# (code-c-d "kepler"    "~/usrc/kepler/")
# (find-keplersrcfile "")
# (find-keplersrcfile "launcher/cgi/cgi.c")
# (find-keplerfile "")
# (find-keplersrcsh "find * | sort")
# (find-keplersh    "find * | sort")
# (find-keplersrcfile "xavante/src/t_xavante_start.lua")

* (eepitch-shell)
rm -Rv /var/www/tmp/k/
ln -s ~/usrc/kepler/ /var/www/tmp/k
cd     /var/www/tmp/k/
echo "Foo $(date)" > foo.txt

# http://localhost/tmp/k/foo.txt
# (find-keplerfile "")
# (find-keplerfile "bin/")
# http://localhost/tmp/k/bin/cgi
# http://localhost/tmp/k/kepler.cgi
# http://localhost/tmp/k/kepler.cgi/index.lp
# http://localhost/tmp/k/kepler.cgi?index.lp

cd ~/usrc/kepler/
cp -v bin/cgi kepler.cgi
# (find-keplerfile "htdocs/")
cd ~/usrc/kepler/
cp -v htdocs/index.lp .

cd ~/usrc/kepler/
cat > t.cgi <<'---'
#!/bin/sh
echo -e "Content-type: text/plain\n"
# echo -e "<html>\n<head><title>T</title></head>\n<body>B</body>\n</html>"
set
---
chmod 755 t.cgi
# http://localhost/tmp/k/t.cgi
wget -q -O - http://localhost/tmp/k/t.cgi
wget -q -O - http://localhost/tmp/k/t.cgi\?foo
wget -q -O - http://localhost/tmp/k/t.cgi/foo

cd ~/usrc/kepler/hashbang.cgi
cat > t.cgi <<'---'
#!/home/edrx/usrc/kepler/bin/cgi

# (find-keplersrcfile "")
# (find-keplersrcfile "om" "> launcher/cgi/cgi.lua")
# (find-keplersrcfile "launcher/cgi/t_cgi.lua")
# (find-keplersrcfile "launcher/cgi/cgi.lua")
# (find-keplersrcfile "cgilua/src/cgilua/")

sed -e "s|\[\[KEPLER_INIT\]\]|\[\[/home/edrx/usrc/kepler/etc/kepler/1.1/kepler_init.lua\]\]|" < launcher/cgi/t_cgi.lua > launcher/cgi/cgi.lua
lua-5.1.2/src/luac5.1 -o launcher/cgi/cgi.lc launcher/cgi/cgi.lua
src/bin2c5.1 launcher/cgi/cgi.lc | sed -e "s|lua_pcall|status=lua_pcall|" > launcher/cgi/cgi.lch
gcc -Wl,-E -lm -ldl -I/home/edrx/usrc/kepler-1.1/lua-5.1.2/src -DINCLUDE_LUA  -Ilauncher/cgi -o launcher/cgi/cgi launcher/cgi/cgi.c lua-5.1.2/src/liblua5.1.a

# (find-keplerfile "")



# (find-keplersrcfile "om" "-o launcher/cgi/cgi")
# (find-keplersrcfile "omi")
# (find-keplersrcfile "omi" "cp launcher/cgi/cgi /home/edrx/usrc/kepler/bin")
# (find-keplerfile "")
# (find-keplersrcfile "launcher/cgi/cgi.lua")
# (find-keplerfile "etc/kepler/1.1/kepler_init.lua")

ln -s ~/usrc/kepler/ /var/www/tmp/k

# http://lists.luaforge.net/pipermail/kepler-project/2007-January/000419.html
# http://lists.luaforge.net/pipermail/kepler-project/2006-November/000301.html

# (find-fline "/etc/thttpd/thttpd.conf")
# (find-fline "$ASROOT/etc/thttpd/thttpd.conf")
# (find-sh0 "sudo /etc/init.d/thttpd restart")




#####
#
# kepler-1.1-hashbang
# 2007may13
#
#####

# «kepler-1.1-hasbang»  (to ".kepler-1.1-hasbang")
#*
rm -Rv ~/usrc/kepler-1.1/
tar -C ~/usrc/ -xvzf \
  $S/http/www.keplerproject.org/kepler-1.1-snapshot-20070511-1628.tar.gz
cd     ~/usrc/kepler-1.1/

./configure --prefix=$HOME/usrc/kepler --launcher=cgi --without-readline \
        2>&1 | tee oc
make    2>&1 | tee om
make install \
        2>&1 | tee omi

find | sort > .files

#*
# (code-c-d "keplersrc" "~/usrc/kepler-1.1/" :grep)
# (code-c-d "kepler"    "~/usrc/kepler/"     :grep)
# (find-keplersrcfile "")
# (find-keplersrcfile "om")
# (find-keplersrcfile "om" "> launcher/cgi/cgi.lch")
# (find-keplersrcfile "launcher/cgi/cgi.lua")
# (find-keplersrcfile "launcher/cgi/cgi.lc")
# (find-keplersrcfile "launcher/cgi/cgi.lch")
# (find-keplerfile "etc/kepler/1.1/kepler_init.lua")
# (find-keplersrcfile "omi")
# (find-keplersrcfile "omi" "cp kepler_init.lua")
# (find-keplersrcfile "src/kepler_init.lua")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
bootstrap, err = loadfile([[/home/edrx/usrc/kepler/etc/kepler/1.1/kepler_init.lua]])
bootstrap()
info = require"sapi.cgi.info"
req = require"sapi.cgi.request"
res = require"sapi.cgi.response"
SAPI = {
	Info = info.open (),
	Request = req.open (),
	Response = res.open (),
}
myenv = {}

SAPI.Request = {
  servervariable = function (vname)
      print("(sv: "..vname..")")
      return myenv[vname] or os.getenv(vname)
    end,
  getpostdata = function (n)
     return io.stdin:read (n)
    end,
}
require"cgilua"
myenv.SCRIPT_NAME = "/tmp/foo.lua"
myenv.REMOTE_ADDR = "127.0.0.1"
PP( cgilua.main() )
PP( cgi )

-- ****** <-- I'm here (2007may20)

PP(SAPI)
PP(SAPI.Request)
PP(SAPI.Request)
-- (find-keplersrcfile "launcher/cgi/sapi/request.lua")

-- (find-keplersrcfile "")
-- (find-keplersrcfile "cgilua/src/cgilua/cgilua.lua")
-- (find-keplersrcfile "cgilua/src/cgilua/cgilua.lua" "function () handle (script_file) end")

-- (find-keplersrcfile "cgilua/doc/us/")
-- (find-keplersrcw3m  "cgilua/doc/us/manual.html")

-- (find-keplersrcfile "launcher/cgi/cgi.lua")
-- (find-keplersrcgrep "grep -nH -e servervariable cgilua/src/cgilua/*")

-- (find-keplersrcfile "launcher/cgi/cgi.c")
-- (find-keplerfile "")
-- (find-keplersrcfile "launcher/cgi/t_cgi.lua")




#####
#
# kepler-1.1-xavante
# 2007may13
#
#####

# «kepler-1.1»  (to ".kepler-1.1")
# http://kepler-tmp.dreamhosters.com/en/UNIX_Installation
# http://www.keplerproject.org/wiki/US/HomePage
# http://www.keplerproject.org/kepler-1.1-snapshot-20070511-1628.tar.gz
# On thttpd:
# http://lists.luaforge.net/pipermail/kepler-project/2007-January/000419.html
# http://lists.luaforge.net/pipermail/kepler-project/2006-November/000301.html
#*
rm -Rv ~/usrc/kepler-1.1/
tar -C ~/usrc/ -xvzf \
  $S/http/www.keplerproject.org/kepler-1.1-snapshot-20070511-1628.tar.gz
cd     ~/usrc/kepler-1.1/
find > .files

./configure --prefix=$HOME/usrc/keplerx --launcher=xavante --without-readline  |& tee oc
make         |& tee om

#*
cd     ~/usrc/kepler-1.1/
rm -Rv ~/usrc/kepler-x/
mkdir  ~/usrc/kepler-x/
make install |& tee omi
cd     ~/usrc/kepler-x/

#*




#####
#
# markdown.lua
# 2007may19 / 2014nov10
#
#####

# «markdown.lua»  (to ".markdown.lua")
# 2014nov10:
# (find-status   "lua-markdown")
# (find-vldifile "lua-markdown.list")
# (find-udfile   "lua-markdown/")

# 2011aug29, lua-l: Peter Odding says that lua-discount is much faster:
#   (find-luarocks-links "lua-discount" "1.2.10.1" "-1")
# http://en.wikipedia.org/wiki/Markdown
# http://www.frykholm.se/files/markdown.lua
# http://www.frykholm.se/files/markdown-tests.lua
# http://sophos.berkeley.edu/macfarlane/pandoc/README
# The pandoc page says that Noam Chomsky's blog at zmag is
# written with markdown...
# http://blogs.zmag.org/ttt
#*
rm -Rv ~/usrc/markdown/
mkdir  ~/usrc/markdown/
cd     ~/usrc/markdown/
cp -v $S/http/www.frykholm.se/files/markdown.lua .
cp -v $S/http/www.frykholm.se/files/markdown-tests.lua .
cp -v $S/http/sophos.berkeley.edu/macfarlane/pandoc/README README.md
lua51 markdown.lua -h
lua51 markdown.lua -t
lua51 markdown.lua README.md

#*
# (code-c-d "markdown" "~/usrc/markdown/")
# (find-markdownfile "")
# (find-markdownfile "markdown.lua")
# (find-markdownsh "lua51 markdown.lua -h")
# (find-markdownw3m "README.html")

# See also: textile and basecamp
# http://hobix.com/textile/quick.html





#####
#
# lua-discount
# 2011aug29 / 2014nov10
#
#####

# «lua-discount»  (to ".lua-discount")
# (find-es "markdown")
# (find-luarocks-links "lua-discount" "1.2.10.1" "-1")
# (find-luarocksfile "bin/")
# (find-luarocksfile "bin/olb-lua-discount")

# (code-c-d "lua-discount" "~/usrc/lua-discount-1.2.10.1/")
# (find-lua-discountfile "")
# (find-lua-discountfile "README.mkd")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
userocks()  -- (find-angg "LUA/lua50init.lua" "userocks")
require "discount"

# 2014nov10:
# http://asbradbury.org/projects/lua-discount/
# http://daringfireball.net/projects/markdown/syntax
# http://www.frykholm.se/files/markdown.lua
# (find-zsh "availabledebs | sort | grep discount")
# (find-zsh "availabledebs | sort | grep markdown")
# (find-status   "discount")
# (find-vldifile "discount.list")
# (find-udfile   "discount/")




#####
#
# ctrace
# 2007may23
#
#####

# «ctrace»  (to ".ctrace")
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/#ctrace
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.0/ctrace.tar.gz
# (find-node "(zsh)Array Parameters")
# (find-man "8 ld.so")
# (find-man "8 ld.so" "LD_LIBRARY_PATH\n")
# (find-man "8 ldconfig")
#*
rm -Rv ~/usrc/ctrace/
tar -C ~/usrc/ -xvzf \
  $S/http/www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.0/ctrace.tar.gz
cd     ~/usrc/ctrace/

L=$LUA51SRC/src
MAKEVARS=(LUAINC=$L LUALIB=$L LUABIN=$L LUA_C=$L/lua.c
          LIBS="-L$L -llua -lm -ldl")

make $MAKEVARS          |& tee om
make $MAKEVARS ctrace.o |& tee omco
make $MAKEVARS a.out    |& tee omao
ldd a.out               |& tee olao     ;# this doesn't find $L/liblua.so...
LD_LIBRARY_PATH=$L \
  ldd a.out             |& tee olao2    ;# so use LD_LIBRARY_PATH to force
LD_LIBRARY_PATH=$L \
  make $MAKEVARS test   |& tee omt

#*
# (code-c-d "luactrace" "~/usrc/ctrace/")
# (find-luactracefile "")
# (find-luactracefile "README")
# (find-luactracefile "Makefile")
# (find-luactracefile "om")
# (find-luactracefile "omco")
# (find-luactracefile "omao")
# (find-luactracefile "olao")
# (find-luactracefile "omt")
# (find-lua51file "src/")





#####
#
# coroutines
# 2007may23
#
#####

# «coroutines»  (to ".coroutines")
# (find-pilfile "")
# (find-pilw3m "index.html")
# (find-pilw3m "9.html"   "Coroutines)
# (find-pilw3m "9.1.html" "Coroutine Basics")
# (find-pilw3m "9.2.html" "Pipes and Filters")
# (find-pilw3m "9.3.html" "Coroutines as Iterators")
# (find-pilw3m "9.4.html" "Non-Preemptive Multithreading")

-- (find-pilw3m "9.1.html" "Coroutine Basics")
-- (find-luamanualw3m "#2.11")
-- (find-luamanualw3m "#pdf-coroutine.resume")
-- (find-lua51file "")
-- (find-lua51file "src/lbaselib.c" "** Coroutine library")
-- (find-lua51file "src/lbaselib.c" "static const luaL_Reg co_funcs[] =")

* (eepitch-lua51)
co = coroutine.create(function () print("hi") end)
print(co)                     --> thread: 0x8071d98
print(coroutine.status(co))   --> suspended
coroutine.resume(co)          --> hi
print(coroutine.status(co))   --> dead

* (eepitch-lua51)
co = coroutine.create(function ()
    for i=1,4 do
      print("co", i)
      coroutine.yield()
    end
  end)
coroutine.resume(co)        --> co   1
print(coroutine.status(co)) --> suspended
coroutine.resume(co)        --> co   2
coroutine.resume(co)        --> co   3
coroutine.resume(co)        --> co   4
print(coroutine.status(co)) --> suspended
coroutine.resume(co)        --> (nothing)
print(coroutine.status(co)) --> dead
coroutine.resume(co)        --> (nothing)

* (eepitch-lua51)
co = coroutine.create(function (a, b)
    print(a, b)
    print(coroutine.yield("foo", "bar"))
    print(coroutine.yield("bletch"))
    return "plic", "ploc"
  end)
print(coroutine.resume(co, 22, 33)) --> 22 33 / true foo bar
print(coroutine.resume(co, 44, 55)) --> 44 55 / true bletch
print(coroutine.resume(co, 66, 77)) --> 66 77 / true plic ploc
print(coroutine.status(co))         --> dead
print(coroutine.resume(co, 88, 99)) --> false   cannot resume dead coroutine




#####
#
# LuaCoco-1.1.4
# 2008oct22
#
#####

# «luacoco»  (to ".luacoco")
# http://luajit.org/coco.html
# http://luajit.org/download/LuaCoco-1.1.4.tar.gz
#*
rm -Rv ~/usrc/LuaCoco-1.1.4/
tar -C ~/usrc/ -xvzf \
  $S/http/luajit.org/download/LuaCoco-1.1.4.tar.gz
cd     ~/usrc/LuaCoco-1.1.4/

#*
# (code-c-d "luacoco" "~/usrc/LuaCoco-1.1.4/")
# (find-luacocofile "")




#####
#
# chunkspy
# 2007jul07
#
#####

# «chunkspy»  (to ".chunkspy")
# (find-angg ".emacs.papers" "lua")
# http://luaforge.net/projects/chunkspy/
# http://www.geocities.com/keinhong/chunkspy.html
# http://luaforge.net/frs/download.php/1481/ChunkSpy-0.9.8.zip
# http://luaforge.net/docman/view.php/83/98/ANoFrillsIntroToLua51VMInstructions.pdf
# http://luaforge.net/docman/index.php?group_id=83&selected_doc_group_id=102&language_id=1
# (find-luanofrillspage 1)
# (find-luanofrillstext)
#*
rm -Rv   ~/usrc/ChunkSpy-0.9.8/
unzip -d ~/usrc/ $S/http/luaforge.net/frs/download.php/1481/ChunkSpy-0.9.8.zip
cd       ~/usrc/ChunkSpy-0.9.8/

cd       ~/usrc/ChunkSpy-0.9.8/5.1/
cat > clo.lua <<'%%%'
foo = function ()
  local storage
  return
    function () return storage end,
    function (x) storage = x; return x end
end
get1, set1 = foo()
get2, set2 = foo()
print(set1(22), get1())          --> 22 22
print(set2(33), get1(), get2())  --> 33 22 33
%%%

luac51 -o clo.out clo.lua
lua51 ChunkSpy.lua --brief clo.out clo.lua > clo.bl.lst
lua51 ChunkSpy.lua --brief clo.out         > clo.b_.lst
lua51 ChunkSpy.lua         clo.out clo.lua > clo._l.lst
lua51 ChunkSpy.lua         clo.out         > clo.__.lst

#*
# (code-c-d "chunkspy" "~/usrc/ChunkSpy-0.9.8/" :grep)
# (find-chunkspyfile "")
# (find-chunkspyfile "README")
# (find-chunkspyfile "README" "CHUNKSPY OPTIONS")
# (find-chunkspyfile "README" "USING CHUNKSPY")
# (find-chunkspyfile "README" "MERGING IN THE SOURCE LISTING")
# (find-chunkspyfile "5.1/ChunkSpy.lua" "iABC format")
# (find-chunkspyfile "5.1/ChunkSpy.lua" "iABx | iAsBx format")
# (find-chunkspyfile "5.1/ChunkSpy.lua")
# (find-chunkspyfile "5.1/sample.lua")
# (find-chunkspyfile "5.1/sample_chunkspy3.lst")
# (find-chunkspyfile "5.1/clo.bl.lst")
# (find-chunkspyfile "5.1/clo.b_.lst")
# (find-chunkspyfile "5.1/clo._l.lst")
# (find-chunkspyfile "5.1/clo.__.lst")
# (find-chunkspyfile "5.1/")
# (find-tkdiff (ee-chunkspyfile "5.1/clo.__.lst") (ee-chunkspyfile "5.1/clo._l.lst"))
# (find-tkdiff (ee-chunkspyfile "5.1/clo.b_.lst") (ee-chunkspyfile "5.1/clo.bl.lst"))

# (find-chunkspyfile "5.1/ChunkSpy.lua" "grab_byte")
# Lhf on lua-l, 2011aug03:
#   string.char(
#           math.floor(x/256^0)%256,
#           math.floor(x/256^1)%256,
#           math.floor(x/256^2)%256,
#           math.floor(x/256^3)%256
#           )
# or this, depending on the order you want the bytes:
#   string.char(
#           math.floor(x/256^3)%256
#           math.floor(x/256^2)%256,
#           math.floor(x/256^1)%256,
#           math.floor(x/256^0)%256,
#           )

# Related:
# http://luaforge.net/projects/chunkbake/






#####
#
# mav
# 2007jul12
#
#####

# «mav»  (to ".mav")
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.1/mav.tar.gz
# ftp://ftp.cs.arizona.edu/reports/1989/TR89-30.pdf
#*
rm -Rv ~/usrc/mav/
tar -C ~/usrc/ -xvzf \
  $S/http/www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.1/mav.tar.gz
tar -C ~/usrc/mav -xvzf \
  $S/http/www.lua.org/ftp/lua-5.1.2.tar.gz

cd ~/usrc/mav/lua-5.1.2/

cp -v src/lauxlib.c src/lauxlib.c.orig
patch -p0 src/lauxlib.c <<'%%%'
627a628,629
> static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize);
> /*
637a640
> */
%%%
cat ../alloc.c >> src/lauxlib.c

unset LUA_INIT
make linux test   |& tee omlt
cp -v alloc.txt ..

cd ~/usrc/mav/
# make D=alloc.txt     |& tee om
# make D=alloc.txt mav |& tee om
make mav |& tee omm

#*
# (find-mavfile "mav.c" "static int M=")
cd ~/usrc/mav/
make mav |& tee omm2
./mav < alloc.txt > /dev/null

#*
# (code-c-d "mav"    "~/usrc/mav/")
# (code-c-d "mavlua" "~/usrc/mav/lua-5.1.2/")
# (find-mavfile "")
# (find-mavfile "README")
# (find-mavfile "alloc.c")
# (find-mavluafile "src/lauxlib.c")
# (find-tkdiff (ee-mavluafile "src/lauxlib.c") (ee-mavluafile "src/lauxlib.c.orig"))
# (find-mavfile "")
# (find-mavfile "alloc.txt")
# (find-mavfile "Makefile")
# (find-mavfile "om")
# (find-mavfile "dv.c" "GP")
# (find-mavfile "mav.c" "static int M=")
# (find-man "XParseGeometry")

# This uses a pixel-based UI too, and I would like to port it to Lua
# someday...
# http://angg.twu.net/ICON/tron.icn.html
# http://angg.twu.net/ICON/tron.icn.png
# http://angg.twu.net/elisp/tron.el.html
# http://angg.twu.net/elisp/tron.el.png





#####
#
# using lpeg to add links to ascii diagrams
# 2007jul24
#
#####

# «lpeg-links-ascii-diags»  (to ".lpeg-links-ascii-diags")
# http://angg.twu.net/davinci.html
# (find-angg "TH/davinci.blogme")

* (eepitch-lua51)
str = [[
.________________
|                |
|     emacs      |
|       ::       |
|       ::       |
|   ____\/_______|__                               ___________________
|  |                |                             |                   |
|  |    shell ::::::::::::::::::::::::::::::::::> |                   |
|  |     ::         |                             |     tcmd.tcl      |
|__|_____::_________|                             |  (Tcl/Tk/Expect)  |
         ::     ^                                 |                   |
         ::     : stdout                          |                   |
 ________\/_____:__                               |                   |
|               :  |                              |                   |
|   SciTe 1.74  :  |                              |                   |
|         ::    :  |                              |                   |
|   ______\/____:__|                              |                   |
|  |               |  <--- /tmp/ee.tcmd.pid <---  |                   |
|  |   Lua 5.1     |  ---> /tmp/ee.tcmd.tcl       |                   |
|  |               |  ------- kill -USR2 ------>  |                   |
|__|_______________|       /tmp/ee.tcmd.tcl --->  |___________________|
  ^          ^
  :          :
 intro.lua   :
             :
     lua50init.lua
]]

asats = function (str) return string.rep("@", strlen(str)) end
loadlpeg()

translateword = function (str) return string.rep("@", strlen(str)) end

Pos       = lpeg.Cp()
AnyChar   = lpeg.P(1)
WordChar  = lpeg.R("AZ", "az", "09") + lpeg.S("/")
Word      = WordChar^1
OtherWord = lpeg.S(" .") * lpeg.S("-")^-1 * Word
Words     = Word * OtherWord^0
WordsT    = Words / translateword
SbeChars  = Pos * AnyChar^0 * Pos
SbeCharsThen = function (patT)
    return Pos * lpeg.P { Pos * patT + AnyChar * lpeg.V(1) }
  end
SbeWordsT = SbeCharsThen(WordsT)^0 * SbeChars

sbematch = function (SbePat, str, f)
    return sbeconcat(str, f)(SbePat:Ct():match(str))
  end
lpeg.sbematch = sbematch

= SbeWordsT:sbematch(str)
= SbeWordsT:match(str)



-- big mess:

twordtable = {
  ["emacs"]    = "emacs.html",
  ["tcmd.tcl"] = "DAVINCI/tcmd.tcl.html",
}
translateword = function (word)
    if twordtable[word] then
      return HREF(twordtable[word], word)
    else
      return word
    end
  end

= Words:match("Foo bar")
= (Pos * Words):match("Foo bar")
PP((Pos * Words * Pos):Ct():match("Foo bar"))
PP(((Pos * Words * Pos):Ct() / PP):match("Foo bar"))
PP((Pos * Words * Pos):sbematch("Foo bar"))
PP((Pos * Words * Pos):Ct():match("Foo bar"))
PP(sbeconcat("Foo Bar")((Pos * Words * Pos):Ct():match("Foo bar")))

= sbeconcat("Foo Bar Blep"){1, 8, "@", 9, 13}
= SbeWordsT:sbematch(str)
= sbematch(str, SbeWordsT, identity) 

sbechars

EtcWordsT = Pos * lpeg.P {
            Pos * WordsT
          + lpeg.P(1) * lpeg.V(1)
          }
EtcSpecials    = EtcSpecial^0
EtcSpecialsEtc = EtcSpecials * Pos * EtcChar^0 * Pos


-- (find-blogme3file "escripts.lua" "EtcSpecial     =")
-- (find-es "lua5" "lpeg-quickref")
-- (find-anggfile "LUA/lua50init.lua" "sbeconcat =")
-- (find-fline "~/TH/davinci.blogme")
-- (find-blogme3file "escripts.lua")





#####
#
# lua-ex
# 2007jul27
#
#####

# «lua-ex»  (to ".lua-ex")
# http://lua-users.org/wiki/ExtensionProposal
# http://lua-ex.luaforge.net/
# I need select() for lcmd.
# This thing doesn't have a select(), I'll have to use lhf's lposix...
# Oops, lposix doesn't have a select() either...
# (find-lposixfile "")
# (find-lposixfile "omxx")
# (find-man "2 signal")
# (find-man "2 select")
# (find-man "2 select_tut")
# (find-man "2 poll")
# (find-node "(libc)Function Index" "* select:")
# What about luafilesystem?
#*
rm -Rv ~/usrc/lua-ex/
mkdir  ~/usrc/lua-ex/
cd     ~/usrc/
tar -xvzf ~/tmp/lua-ex-cvs.tar.gz
# cvs -d :pserver:anonymous@cvs.luaforge.net:/cvsroot/lua-ex login
  cvs -d :pserver:anonymous@cvs.luaforge.net:/cvsroot/lua-ex checkout lua-ex
tar -cvzf ~/tmp/lua-ex-cvs.tar.gz lua-ex/
cd     ~/usrc/lua-ex/

#*
rm -Rv ~/usrc/lua-ex/
tar -C ~/usrc/ -xvzf ~/tmp/lua-ex-cvs.tar.gz
cd     ~/usrc/lua-ex/

cp conf.in conf
cat >> conf <<'%%%'
# ---
# Edrx:
LUA= $(HOME)/usrc/lua-5.1.2
LUAINC= -I$(LUA)/src
LUALIB= -L$(LUA)/src -llua
%%%

make linux  |& tee oml

#*
# (code-c-d "luaex" "~/usrc/lua-ex/")
# (find-luaexfile "")
# (find-luaexfile "INSTALL")
# (find-luaexfile "conf.in")
# (find-luaexfile "conf")
# (find-luaexfile "Makefile")
# (find-luaexfile "oml")
# (find-luaexfile "posix/")
# (find-luaexfile "posix/Makefile")
# (find-luaexfile "posix/posix_spawn.c")
# (find-luaexfile "tests/")





#####
#
# Running the Lua API interactively from GDB
# 2007oct27
#
#####

# «lua-api-from-gdb»  (to ".lua-api-from-gdb")
# (to "compile-5.1.4-lua_O0")
# (find-angg ".emacs" "eepitch-gdb-lua")
# (find-angg ".lua51/")
# (find-angg ".lua51/PP.gdb")
# (find-TH "luaforth" "lua-api-from-gdb")

# Preparation for the first block:
# (find-sh0 "echo 'math.sin(0)' > /tmp/foo.lua")

* (eepitch-gdb-lua-kill)
* (eepitch-gdb-lua)
set args /tmp/foo.lua
br math_sin
run
call lua_pushstring(L, "print")
call lua_gettable(L, -10002)
call lua_pushstring(L, "Foo!")
call lua_pushstring(L, "Bar!")
p lua_gettop(L)
call lua_call(L, 2, 0)
p lua_gettop(L)


# (find-angg ".lua51/PP.gdb")

* (eepitch-gdb-lua)
* (eepitch-gdb-lua-kill)
* (eepitch-gdb-lua)
source ~/.lua51/PP.gdb
quickstart
depth
PPeval "a = 32"
PPeval "=   a, a+2"
PPeval "=  {a, a+2}, 40"
PPeval "== {a, a+2}, 40"
depth
lua_pusheval "20 + 42"
depth
PP -1
depth


* (eepitch-gdb-lua-kill)
* (eepitch-gdb-lua)
source ~/.lua51/PP.gdb
quickstart
call lua_pushstring(L, "foo")
call lua_pushstring(L, "bar")
call lua_concat(L, 2)
PP -1

depth
call lua_getfield(L, -10002, "math")
call lua_getfield(L, -10002, "string")
depth
PP(-1)   # the "string" table
PP(-2)   # the "math" table
depth


* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cat > /tmp/fg.lua <<'%%%'
F = function (a, b) local c, d = "c", "d"; G("e", "f"); return "F" end
G = function (a, b) local c, d = "c", "d"; math.sin(0); return "G" end
%%%

* (eepitch-gdb-lua-kill)
* (eepitch-gdb-lua)
source ~/.lua51/PP.gdb
quickstart
PPeval "dofile '/tmp/fg.lua'"
PP -1
PP -2
PP -6
PP -7
PP -8
# How do I access the locals, the arguments and the temporary stack
# of the function that called the current one???
# How do I access the first argument - rather than the last argument -
# of the current function?




#####
#
# Inspecting Lua datatypes in GDB
# 2009jan19
#
#####

# «lua-datatypes-gdb»  (to ".lua-datatypes-gdb")
# (find-angg ".lua51/PP.gdb")
# (find-angg ".lua51/PP.gdb" "lua_pusheval")

# «lua-numbers-gdb»  (to ".lua-numbers-gdb")
# Inspecting a number at the top of the stack:
#   (find-lua51tag "lua_pushnumber")
#   (find-lua51tag "setnvalue")
#   (find-lua51tag "LUA_TNUMBER" "3")

* (eepitch-gdb-lua)
* (eepitch-gdb-lua-kill)
* (eepitch-gdb-lua)
source ~/.lua51/PP.gdb
quickstart
lua_pusheval "20"
p L->top[-1].tt
p L->top[-1].value.n


# «lua-strings-gdb»  (to ".lua-strings-gdb")
# (find-lua51tag "lua_pushstring")
# (find-lua51tag "lua_pushlstring")
# (find-lua51tag "luaS_newlstr")
# (find-lua51tag "setsvalue")
# (find-lua51tag "setsvalue2s")
# (find-lua51tag "LUA_TSTRING" "4")
# (find-lua51tag "GCObject")
# (find-lua51file "src/lstate.h"  "union GCObject {" "ts;")
# (find-lua51file "src/lobject.h" "union TString {"  "tsv;")
# (find-lua51file "src/lobject.h" "#define getstr(ts)")
# (find-lua51tag "getstr")
# (find-lua51tag "#define getstr(ts)")
# (find-lua51grep "grep -nH -e 'union TString' src/*.[ch]")

* (eepitch-gdb-lua)
* (eepitch-gdb-lua-kill)
* (eepitch-gdb-lua)
source ~/.lua51/PP.gdb
quickstart
lua_pusheval "'foobar'"
p  L->top[-1].tt
p  L->top[-1].value
p  L->top[-1].value.gc
pt L->top[-1].value
pt L->top[-1].value.gc
pt L->top[-1].value.gc.ts
pt L->top[-1].value.gc.ts.tsv
p            L->top[-1].value.gc.ts.tsv
p          &(L->top[-1].value.gc.ts.tsv)
p (char *)(&(L->top[-1].value.gc.ts.tsv) + 1)

# (find-lua51tag "luaS_newlstr")
# (find-lua51tag "luaS_newlstr" "/* compute hash */")
p  L->top[-1].value.gc.ts.tsv.hash


# «lua-closures-gdb»  (to ".lua-closures-gdb")
# (find-lua51tag "LUA_TFUNCTION" "6")
# (find-lua51grep "grep -nH -e LUA_TFUNCTION src/*.[ch]")
# (find-lua51grep "grep -nH -e 'union Closure' src/*.[ch]")
# (find-lua51tag "setclvalue")
# (find-lua51file "src/lobject.h" "union Closure {")
# (find-lua51file "src/lobject.h" "struct LClosure {")

# (find-lua51tag "lua_pushstring")
# (find-lua51tag "lua_pushlstring")
# (find-lua51tag "luaS_newlstr")
# (find-lua51tag "setsvalue")
# (find-lua51tag "setsvalue2s")
# (find-lua51tag "GCObject")
# (find-lua51file "src/lobject.h" "#define getstr(ts)")
# (find-lua51tag "getstr")
# (find-lua51tag "#define getstr(ts)")
# (find-lua51grep "grep -nH -e 'union TString' src/*.[ch]")

* (eepitch-gdb-lua)
* (eepitch-gdb-lua-kill)
* (eepitch-gdb-lua)
source ~/.lua51/PP.gdb
quickstart
PPeval "f = function (a, b) return function (c) return a + b + c end end"
PPeval "add5 = f(2, 3)"
PPeval "add9 = f(4, 5)"
PPeval "=  add5(20)"
PPeval "=  add9(40)"
lua_pusheval "add5"
lua_pusheval "add9"
p L->top[-1].tt
p L->top[-1].value
p L->top[-1].value.gc[0]
p L->top[-1].value.gc.cl
p L->top[-1].value.gc.cl.l
p L->top[-1].value.gc.cl.l.nupvalues
p L->top[-1].value.gc.cl.l.upvals
p L->top[-1].value.gc.cl.l.upvals[0]
p L->top[-1].value.gc.cl.l.upvals[0][0]
p L->top[-1].value.gc.cl.l.upvals[0]->u
p  L->top[-1].value.gc.cl.l.upvals[0]->u.value
pt L->top[-1].value.gc.cl.l.upvals[0]->u.value
p L->top[-1].value.gc.cl.l.upvals[0]->u.value.value.n
p L->top[-1].value.gc.cl.l.upvals[1]->u.value.value.n
p L->top[-2].value.gc.cl.l.upvals[0]->u.value.value.n
p L->top[-2].value.gc.cl.l.upvals[1]->u.value.value.n









p L
p *L
p L->stack
p L->stack[0]
p L->stack[1]
p L->stack[2]



# (find-angg ".lua51/PP.gdb")
# (find-node "(gdb)Define")
help user-defined
show user
show user PP
# (find-lua51file "src/lua.h" "#define LUA_GLOBALSINDEX" "(-10002)")
# (find-lua51file "src/lua.h" "#define lua_getglobal")




* (eepitch-gdb-lua)
* (eepitch-gdb-lua-kill)
* (eepitch-gdb-lua)
source ~/.lua51/PP.gdb
quickstart
PPeval "a = 32"
PPeval "=   a, a+2"
PPeval "=  {a, a+2}, 40"
PPeval "== {a, a+2}, 40"
depth
lua_pusheval "20 + 42"
depth
PP -1
depth





#####
#
# lbci
# 2007oct31
#
#####

# «lbci»  (to ".lbci")
# http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.1/lbci.tar.gz
#*
rm -Rv ~/usrc/lbci/
tar -C ~/usrc/ -xvzf \
  $S/http/www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.1/lbci.tar.gz
cd     ~/usrc/lbci/
cp -v Makefile Makefile.orig

patch -p0 Makefile <<'%%%'
4c4,5
< LUA= /tmp/lhf/lua-5.1
---
> #LUA= /tmp/lhf/lua-5.1
> LUA= $(HOME)/usrc/lua-5.1.2
%%%

make |& tee om

cc -v -o a.out /home/edrx/usrc/lua-5.1.2/src/lua.o lbci.o linit.o -L/home/edrx/usrc/lua-5.1.2/src -llua -lm -ldl -lreadline -lhistory -lncurses |& tee oc


#*
# (code-c-d "lbci" "~/usrc/lbci/")
# (find-lbcifile "")
# (find-lbcifile "om")
# (find-lbcifile "Makefile")
# (find-lua51tag "luaP_opnames")





#####
#
# numlua
# 2007nov07
#
#####

# «numlua»  (to ".numlua")
# http://numlua.luaforge.net/
# http://luaforge.net/frs/download.php/2566/numlua-0.2.1.tar.gz
#*
rm -Rv ~/usrc/numlua/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/2566/numlua-0.2.1.tar.gz
cd     ~/usrc/numlua/

#*
cd     ~/usrc/numlua/lib/
make |& tee om

#*
# (code-c-d "numlua" "~/usrc/numlua/" :grep)
# (find-numluafile "INSTALL")
# (find-numluafile "Makefile")
# (find-numluafile "src/Makefile")
# (find-numluafile "lib/Makefile")
# (find-numluafile "om")
# (find-numluafile "lib/om")
# (find-numluafile "lib/om" "-I/usr/include/lua5.1")
# (find-numluafile "lib/")
# (find-numluafile "")
# (find-numluagrep "grep -nH -e LUADIR $(find *)")
# (find-numluafile "src/Makefile" "LUADIR = /usr")
# (find-numluafile "src/Makefile" "LIBS += -L$(LUADIR)/lib -llua")
# (find-numluafile "src/Makefile" "OBJFLAGS = -I$(LUADIR)/include/lua5.1")




#####
#
# clue
# 2007nov07
#
#####

# «clue»  (to ".clue")
# http://ufpr.dl.sourceforge.net/sourceforge/zee/zee-0.6.tar.gz
# http://www.lua.org/notes/ltn004.html
# http://luaforge.net/frs/download.php/2703/clue.h
# http://luaforge.net/projects/clue/
# http://luaforge.net/frs/download.php/4797/clue-5.zip

# https://github.com/downloads/rrthomas/zee/zee-0.7.tar.gz
# https://github.com/rrthomas/zee
#*
rm -Rv ~/usrc/zee-0.7/
tar -C ~/usrc/ -xvzf \
  $S/https/github.com/downloads/rrthomas/zee/zee-0.7.tar.gz
cd     ~/usrc/zee-0.7/

# (find-lua52file "install/bin/")
export PATH=/home/edrx/usrc/lua-5.2.0/install/bin:$PATH

./configure   |& tee oc
make          |& tee om

#*
# (code-c-d "zee" "~/usrc/zee-0.7/")
# (find-zeefile "")
# (find-zeesh "./configure --help")
# (find-zeesh "./configure --help" "lua")
# (find-zeefile "configure.ac" "[LUA_VERSION], [5.2]")




#####
#
# reader
# 2007nov16
#
#####

# «reader»  (to ".reader")
# «interactor»  (to ".interactor")
# (find-angg "LUA/lua50init.lua" "interactor")
# (find-angg "LUA/reader.lua")
# (find-luamanualw3m "#pdf-loadstring")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)

reader_metatable = {
  concat = function (self) return table.concat(self, "\n") end,
  code = function (self) return self:concat() end,    -- overridden
  prompt = function (self) return ">> " end,          -- overridden
  abort = function (self) end,                        -- overridden; message
  load = function (self)
      if self.line then
        self.compiled, self.errmsg = loadstring(self:code())
        self.incomplete = self.errmsg and
          string.find(self.errmsg, ": unexpected symbol near '<eof>'$")
      else
        self.compiled, self.errmsg, self.incomplete = nil, nil, nil
      end
      return self
    end,
  read = function (self, prompt)
      io.write(prompt or self:prompt())
      self.line = io.read()
      if self.line == "." then self:abort(); self.line = nil end
      if self.line then table.insert(self, self.line) end
      return self
    end,
  complete = function (self)
      while self.line and self.incomplete do self:read(); self:load() end
      return self
    end,
}

over = function (bottomtable, toptable)
    return setmetatable(toptable or {}, {__index = bottomtable})
  end

reader = over(reader_metatable, {})
reader:read("R> ")
  print(22,
reader:load()
PP(reader)
reader:complete()
  33,
  44)
PP(reader)
reader.compiled()

reader:read("R> "):load():complete()
  print(22,
  33,
  44)
assert(reader.compiled, reader.errmsg)()

readerwithprefix_metatable = over(reader_metatable, {
  prefix  = "=",
  prepend = "return ",
  code = function (self)
      return self.prepend .. self:concat():sub(#self.prefix+1)
    end,
})

reader = over(readerwithprefix_metatable, {})
reader:read("R> "):load():complete()
= 22,
  33,
  44
print(assert(reader.compiled, reader.errmsg)())

# «interactor-prefixes»  (to ".interactor-prefixes")

* (eepitch-lua51)
m = function (str)
    local pos, rest = ("["..str.."]"):match("^%b[]()(.*)$")
    if rest == ""  then return "complete" end
    if rest == nil then return "incomplete" end
    return pos-2   -- Extra closing bracket at this position
  end
= m("foo bar")   --> "complete"
= m("foo b[a")   --> "incomplete"
= m("foo b]a")   --> 6

* (eepitch-lua51)
-- (find-luamanualw3m "#pdf-string.find")
hasprefix = function (str, prefix)
    return str:find(prefix, 1, "plain") == 1
  end

= hasprefix("=foo", "=")        --> true
= hasprefix("=foo", "=foobar")  --> false
= hasprefix("=foo", "plic")     --> false

prefixes = {"==[", "==", "=[", "=", "["}
metatables = {
    ["==["] = interactor_blogme_PP_metatable,
    ["=["]  = interactor_blogme_print_metatable,
    ["["]   = interactor_blogme_metatable,
    ["=="]  = interactor_PP_metatable,
    ["="]   = interactor_print_metatable,
    [""]    = interactor_metatable,
  }


interactor_print_metatable = over(interactor_metatable, {
    prefix = "="
    body = function (self) return "return "..self:concat():sub(2) end
    eval = function (self)




#####
#
# debug.getinfo
# 2007nov28
#
#####

# «debug.getinfo»  (to ".debug.getinfo")
# (find-angg "LUA/lua50init.lua" "errorfb_line")
# (find-lua51manualw3m "#pdf-debug.getinfo")
# (find-lua51manualw3m "#pdf-debug.getlocal")
# (find-lua51manualw3m "#pdf-debug.setlocal")
# (find-lua51manualw3m "#lua_getinfo")
# (find-lua51manualw3m "#lua_getstack")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
do
local u = "33"
f = function (a, g)
    local b = u
    g(a..b)
  end
end
f(22, function () PP(debug.getinfo(0, "nSlu")) end)
f(22, function () PP(debug.getinfo(1, "nSlu")) end)
f(22, function () PP(debug.getinfo(2, "nSlu")) end)
f(22, function () PP(debug.getinfo(2, "nu")) end)
                     --> {"name"="f", "namewhat"="global", "nups"=1}
f(22, function () PP(debug.getinfo(0, "n").name) end)  --> "getinfo"
f(22, function () PP(debug.getinfo(1, "n").name) end)  --> "g"
f(22, function () PP(debug.getinfo(2, "n").name) end)  --> "f"
f(22, function () P(debug.getlocal(2, 1)) end)   --> "a" 22
f(22, function () P(debug.getlocal(2, 2)) end)   --> "g" <function>
f(22, function () P(debug.getlocal(2, 3)) end)   --> "b" "33"
f(22, function () P(debug.getlocal(2, 4)) end)   --> nil
PP(debug.getinfo(f, "f").func)
PP(debug.getinfo(f, "u"))    --> {"nups"=1}
PP(debug.getupvalue(f, 1))   --> "u" "33"
f(22, function () PP(debug.getinfo(2, "f").func, f) end) --> (same func twice)
f(22, function () PP(debug.getupvalue(debug.getinfo(2, "f").func, 1)) end)
                             --> "u" "33"

L_meta = {}
L = {2, {a=1, g=2, b=3}, function ()
    L[2] = {}
    for i=1,10000 do
      local name = debug.getlocal(L[1], i)
      if name then print(name); L[2][name] = i else break end
    end
  end}
setmetatable(L, L_meta)

L_meta.__index    = function (L, k)
    local name, v = debug.getlocal(L[1], L[2][k])
    print(name)
    return v
  end
L_meta.__newindex = function (L, k, v)
    debug.setlocal(L[1], L[2][k], v)
  end

L[1]=0; f(22, function () PP(L.b) end)
L[1]=1; f(22, function () PP(L.b) end)
L[1]=2; f(22, function () PP(L.b) end)
L[1]=3; f(22, function () PP(L.b); L.b=44; PP(L.b) end)
L[1]=3; f(22, function () L[3]() end)


-- (find-luamanualw3m "#pdf-debug.getupvalue")
-- (find-lua51file "")
-- (find-lua51grep "grep -nH -e '\"getinfo\"' $(cat .files.ch)")
-- (find-lua51file "src/ldblib.c" "static int db_getinfo ")




#####
#
# getlocal and setlocal
# 2016feb14
#
#####

# «getlocal-and-setlocal» (to ".getlocal-and-setlocal")
# (to "debug.getinfo")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
getlocals = function (level)
    local tbl = {}
    for i=1,2000 do
      local name = debug.getlocal(level, i)
      if not name then break end
      tbl[i] = name
      tbl[name] = i
    end
    return tbl
  end
getlocaln = function (tbl, name)
    if not tbl[name] then
      error(format("No local \"%s\" in: [%s]", tostring(name), table.concat(tbl, " ")))
    end
    return tbl[name]
  end
getlocal = function (level, name)
    local nm, val = debug.getlocal(level, getlocaln(getlocals(level+1), name))
    return val
  end
setlocal = function (level, name, value)
    debug.setlocal(level, getlocaln(getlocals(level+1), name), value)
  end

f = function (n, a, b)
    local c, d, e = "cc", "dd", "ee"
    print(table.concat(getlocals(2), " "))
    print(getlocaln(getlocals(2), "c"))
    print(getlocal(2, "c"))
    setlocal(2, "c", "cccc")
    print(getlocal(2, "c"))
  end
f()




#####
#
# luafilesystem-1.2.1
# 2007aug13
#
#####

# http://luaforge.net/frs/download.php/2381/luafilesystem-1.2.1.tar.gz
#*
rm -Rv ~/usrc/luafilesystem-1.2.1/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/2381/luafilesystem-1.2.1.tar.gz
cd     ~/usrc/luafilesystem-1.2.1/

#*
# (code-c-d "lfs" "~/usrc/luafilesystem-1.2.1/")
# (find-lfsfile "")
# (find-lfsw3m "doc/us/manual.html")

#####
#
# lualogging-1.1.3
# 2007aug13
#
#####

# http://luaforge.net/frs/download.php/2552/lualogging-1.1.3.tar.gz
#*
rm -Rv ~/usrc/lualogging-1.1.3/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/2552/lualogging-1.1.3.tar.gz
cd     ~/usrc/lualogging-1.1.3/

#*
# (code-c-d "lualogging" "~/usrc/lualogging-1.1.3/")
# (find-lualoggingfile "")
# (find-lualoggingw3m "doc/us/manual.html")

#####
#
# luadoc-3.0
# 2007aug13
#
#####

# http://luaforge.net/frs/download.php/2557/luadoc-3.0.tar.gz
#*
rm -Rv ~/usrc/luadoc-3.0/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/2557/luadoc-3.0.tar.gz
cd     ~/usrc/luadoc-3.0/

#*
# (code-c-d "luadoc" "~/usrc/luadoc-3.0/")
# (find-luadocfile "")
# (find-luadocfile "doc/us/")
# (find-luadocw3m  "doc/us/manual.html")





#####
#
# metalua
# 2008feb06 / 2011oct18
#
#####

# «metalua»  (to ".metalua")
# (find-angg ".emacs" "metalua")
# (find-angg "bin/setenved-metalua")
# http://groups.google.com/group/metalua?pli=1
# http://metalua.luaforge.net/
# http://metalua.blogspot.com/
# http://metalua.luaforge.net/download.html
# http://metalua.luaforge.net/metalua-0.4.1-rc1.tgz
# http://metalua.luaforge.net/metalua-0.4.tgz

# http://metalua.luaforge.net/metalua-0.4.1-rc1.tgz
#*
rm -Rv ~/usrc/metalua/
tar -C ~/usrc/ -xvzf \
  $S/http/metalua.luaforge.net/metalua-0.4.1-rc1.tgz
cd     ~/usrc/metalua/

cd     ~/usrc/metalua/src/

# make PLATFORM=linux   |& tee om
# make PLATFORM=linux TARGET_LUA_PATH=$PWD/tmp/metalua           |& tee om
  make PLATFORM=linux TARGET_LUA_PATH=$HOME/usrc/metalua/target  |& tee om

cd     ~/usrc/metalua/
cat   src/setenv.sh                       > target/bin/setenved-metalua
echo  "exec $PWD/target/bin/metalua \$*" >> target/bin/setenved-metalua
chmod 755                                   target/bin/setenved-metalua

#*
# (code-c-d "metalua" "~/usrc/metalua/")
# (find-metaluafile "")
# (find-metaluafile "src/om")
# (find-metaluafile "INSTALL.TXT")
# (find-metaluafile "INSTALL.TXT" "Un*x")
# (find-metaluafile "src/config")
# (find-metaluafile "src/config" "TARGET_LUA_PATH  =")
# (find-metaluagrep "grep -nrH -e TARGET_BIN *")
# (find-metaluagrep "grep -nrH -e TARGET_LUA *")
# (find-metaluagrep "grep -nrH -e yueliang *")
# (find-metaluafile "src/Makefile")
# (find-metaluafile "src/setenv.sh")
# (find-metaluafile "target/bin/")
# (find-metaluafile "target/bin/setenved-metalua")
# (find-metaluash0 "cp -v target/bin/setenved-metalua ~/bin/")
# (find-fline "~/usrc/metalua/src/setenv.sh")
# (find-fline "/tmp/metalua/")
# (find-metaluash "find * | sort")
# (find-metaluafile "src/lib/metalua/runtime.lua")
# (find-metaluafile "junk/notes.txt" "Yueliang")
# (find-metaluafile "src/samples/")

# (find-metaluafile "src/compiler/gg.lua")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/metalua/target/
# bin/metalua
. ~/usrc/metalua/src/setenv.sh
bin/metalua

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/metalua/src/samples/
setenved-metalua
-- (find-metaluafile "src/samples/")
dofile "h_test.mlua"


* (eepitch-metalua)
* (eepitch-kill)
* (eepitch-metalua)


# (find-metaluafile "README.TXT")
# (find-metaluafile "doc/ast.txt")
# (find-metaluafile "doc/manual/")
# (code-xpdf      "metalua" (ee-metaluafile "doc/manual/metalua-manual.pdf"))
# (code-pdftotext "metalua" (ee-metaluafile "doc/manual/metalua-manual.pdf"))
# (find-metaluapage 1)
# (find-metaluapage 5 "Contents")
# (find-metaluatext 1)

# http://www.ccs.neu.edu/home/dherman/research/papers/esop08-hygiene.pdf
# http://www.cs.utah.edu/plt/publications/macromod.pdf

# (find-metaluafile "src/lib/package2.lua" "function package.findfile")



# «gradual-typing» (to ".gradual-typing")
https://github.com/fab13n/metalua/tree/tilo/src/tilo
https://github.com/fab13n/metalua/raw/tilo/doc/tilo/paper/tilo.pdf
http://ecee.colorado.edu/~siek/gradualtyping.html





#####
#
# setvbuf
# 2008feb09
#
#####

# «setvbuf»  (to ".setvbuf")
# (find-node "(libc)Controlling Buffering" "Function: int setvbuf")
# (find-luamanualw3m "#pdf-file:setvbuf")
# (find-blogme3 "anggdefs.lua" "setvbuf")
# (find-blogme3 "anggdefs.lua" "setvbuf" "Without a setvbuf errors are")

io.stdout:setvbuf("no")




#####
#
# luarocks-2.0.12
# 2008may13 / 2012mar19
#
#####

# «luarocks»  (to ".luarocks")
# (find-angg ".emacs" "luarocks")
# (find-angg ".emacs.templates" "find-luarocks-links")
# http://luarocks.org/
# http://luarocks.org/repositories/rocks/
# http://luarocks.org/repositories/rocks/index.html#lposix
# http://luarocks.org/repositories/rocks/#lposix
# http://luarocks.luaforge.net/luadoc/
# http://www.luarocks.org/en/Documentation
# http://www.luarocks.org/en/Installation_instructions_for_Unix
# http://www.luarocks.org/en/Using_LuaRocks
# http://www.luarocks.org/en/Download
# http://lists.luaforge.net/pipermail/luarocks-developers/
# http://lists.luaforge.net/pipermail/luarocks-developers/2010-December/002188.html
# http://luarocks.org/releases/
# http://luarocks.org/releases/luarocks-2.0.12.tar.gz
# http://luarocks.org/releases/luarocks-2.0.13.tar.gz
# http://luarocks.org/releases/luarocks-2.1.1.tar.gz
# http://luarocks.luaforge.net/rocks/
# http://luarocks.luaforge.net/rocks/index.html
* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
#*
# (find-fline "~/usrc/luarocks/")

rm -Rv ~/usrc/luarocks/
rm -Rv ~/usrc/luarocks-2.0.13/

tar -C ~/usrc/ -xvzf \
  $S/http/luarocks.org/releases/luarocks-2.0.13.tar.gz
cd     ~/usrc/luarocks-2.0.13/
./configure
./configure --help
./configure \
  --with-lua=$LUA51SRC \
  --prefix=$HOME/usrc/luarocks
make         |& tee om
make install |& tee omi

#*

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
#*
# (find-fline "~/usrc/luarocks/")

rm -Rv ~/usrc/luarocks/
rm -Rv ~/usrc/luarocks-2.1.1/

tar -C ~/usrc/ -xvzf \
  $S/http/luarocks.org/releases/luarocks-2.1.1.tar.gz
cd     ~/usrc/luarocks-2.1.1/
./configure
./configure --help
./configure \
  --with-lua=$LUA51SRC \
  --prefix=$HOME/usrc/luarocks
make         |& tee om
make build   |& tee om
make install |& tee omi

#*
# (code-c-d "luarockssrc" "~/usrc/luarocks-2.1.1/")
# (code-c-d "luarockssrc" "~/usrc/luarocks-2.0.13/")
# (code-c-d "luarocks"    "~/usrc/luarocks/")
# (code-c-d "luarocksbin" "~/usrc/luarocks/bin/")
# (code-c-d "luarocks51"  "~/usrc/luarocks/share/lua/5.1/luarocks/")

# (find-luarockssrcfile "")
# (find-luarockssrcfile "Makefile")
# (find-luarockssrcfile "configure")
# (find-luarockssrcsh "./configure --help")
# (find-luarockssrcfile "om")
# (find-luarockssrcfile "omi")
# (find-luarockssrcfile "omi" "into /home/edrx/usrc/luarocks")

# (find-luarocks51file "")
# (find-luarocksfile "")
# (find-luarocksfile "etc/luarocks/")
# (find-luarocksfile "etc/luarocks/config.lua")
# (find-luarocksfile "bin/")
# (find-luarocksfile "bin/luarocks")
# (find-luarocksfile "bin/luarocks-admin")
# (find-luarocksfile "lib/")
# (find-luarocksfile "lib/luarocks/rocks/alien/0.5.0-1/")
# (find-luarocksfile "lib/luarocks/rocks/lpeg/0.10-1/")
# (find-luarocksfile "lib/luarocks/rocks/")
# (find-luarocksfile "share/")
# (find-luarocks51file "build.lua")
# (find-luarocks51file "build.lua" "--- Build and install")
# (find-luarockssh    "pwd; find * | sort")
# (find-luarockssrcsh "pwd; find * | sort")
# (find-luarocks51sh  "pwd; find * | sort")
# (find-luarocksfile "bin/")

# (find-sh "find ~/usrc/luarocks* | sort")

# 2014jul03:

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -v ~/bin/luarocks
ln -s ../usrc/luarocks/bin/luarocks ~/bin/luarocks

# (find-sh "luarocks help search")
# (find-sh "luarocks help download")
# (find-sh "luarocks help unpack")
# (find-sh "luarocks help make")
# (find-sh "luarocks help build")
# (find-sh "luarocks help install")

luarocks search lpeg

rm -Rfv /tmp/lr/
mkdir   /tmp/lr/
cd      /tmp/lr/
luarocks download lpeg 0.12-1
rm -Rfv   /tmp/lr/lpeg-0.12-1/
luarocks unpack   lpeg 0.12-1
cd        /tmp/lr/lpeg-0.12-1/
cd        /tmp/lr/lpeg-0.12-1/lpeg-0.12/
luarocks make --pack-binary-rock lpeg-0.12-1.rockspec   |& tee ob
luarocks install  lpeg-0.12-1.linux-x86.rock

luarocks make  |& tee om


luarocks build    lpeg-0.12-1.rockspec |& tee ob



# (find-fline "/tmp/lr/lpeg-0.12-1/")
# (find-fline "/tmp/lr/lpeg-0.12-1/lpeg-0.12/")

# (find-luarocks51file "")
# (find-luarocks51file "build.lua")
# (find-luarocks51file "build/")
# (find-luarocks51file "build.lua" "is now built and installed in")


rm -Rv /tmp/lr/; mkdir /tmp/lr/; cd /tmp/lr/ luarocks download lpeg 0.12-1; luarocks unpack lpeg 0.12-1; luarocks make

# (find-fline "/tmp/lr/lpeg-0.12-1/")
# (find-fline "/tmp/lr/lpeg-0.12-1/lpeg-0.12/")
# (find-fline "/tmp/lr/lpeg-0.12-1/lpeg-0.12/lpeg-0.12-1.linux-x86.rock")
cd /tmp/lr/lpeg-0.12-1/
cd /tmp/lr/lpeg-0.12-1/lpeg-0.12/




laf
# luarocks download --all lpeg 0.12-1
laf

# (find-fline "/tmp/lr/")
# (find-fline "~/bin/" "luarocks")
# (find-fline "~/bin/luarocks")
# (find-luarocks51file "")


cd /tmp/
luarocks search lpeg
luarocks download --all lpeg 0.12-1
unzip -o lpeg-0.12-1.src.rock
# (find-fline "/tmp/lpeg-0.12.tar.gz")
# (find-fline "/tmp/")
# (find-man "unzip")

# (find-sh "luarocks search repl")
# (find-sh "luarocks help")
# (find-sh "luarocks help install")
# (find-sh "luarocks help unpack")

luarocks download --all asklua
luarocks download inspect
luarocks unpack inspect
cd /tmp/

# (find-sh "luarocks help")
# (find-sh "luarocks help search")
# (find-sh "luarocks search --all")
# (find-sh "luarocks help download")



* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/luarocks/
laf
cd ~/usrc/luarocks/bin/
laf
./luarocks
./luarocks list
./luarocks download lpeg
./luarocks build    lpeg    |& tee olb-lpeg
./luarocks download lposix
./luarocks build    lposix  |& tee olb-lposix
./luarocks download luarepl
./luarocks build    luarepl |& tee olb-luarepl

# https://rocks.moonscript.org/modules/leafo/loadkit

./luarocks download alien
./luarocks build    alien   |& tee olb-alien
./luarocks download luagl
./luarocks build    luagl   |& tee olb-luagl
./luarocks download xavante
./luarocks build    xavante |& tee olb-xavante

./luarocks download lexpect
./luarocks build    lexpect |& tee olb-lexpect

./luarocks download lbc
./luarocks build    lbc |& tee olb-lbc
./luarocks download lmapm
./luarocks build    lmapm |& tee olb-lmapm



<edrx> hello - I'm trying luarocks again, after a long time... two
       quick questions: 1) is there a way to make it run in verbose
       mode? 2) where does it put the build dirs for the rocks? for
       example, ~/usrc/luarocks/bin/lpeg-0.10-1.src.rock ->
       lpeg-0.10.tar.gz -> lpeg-0.10/lpeg.html should be available
       somewhere...

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/luarocks/bin/
laf
strace-to /tmp/s ./luarocks build    lpeg  |& tee olb-lpeg
# (find-fline "/tmp/s")



# http://lists.luaforge.net/pipermail/luarocks-developers/2008-February/date.html
# http://lists.luaforge.net/pipermail/luarocks-developers/
# http://cosmo.luaforge.net/

luarocks
luarocks help
luarocks list
luarocks search --all
luarocks install bitlib

# (find-fline "/tmp/luarocks/")
# (find-fline "/tmp/luarocks/bin/luarocks")
# (find-luarocksfile "configure" "LUA_BINDIR")

<edrx> hi (& happy new year =)) -
<edrx> I'm looking for hints on how to use luarocks more
       verbosely...
<edrx> my current way of using it is through the sequences of
       commands stored in these messy notes (which come with an
       implicit "you are not expected to understand this" - summary
       soon):
<edrx> http://angg.twu.net/e/lua5.e.html#luarocks
<edrx> so, for installing, for example, luarepl, I'd do this:
<edrx> ./luarocks download luarepl
<edrx> ./luarocks build    luarepl 2>&1 | tee olb-luarepl
<edrx> which leaves a copy of the ___.rock and a build log in a
       known place
<edrx> but I have the impression that there must a way to make the
       "./luarocks build" run more verbose - in particular, to make
       it show which dirs are being used, and what is the current
       pwd before running a sequence of commands.
<edrx> if anyone has any hints I'd love to hear... luarocks still
       feels quite opaque to me =\




#####
#
# luarocks mailing list
# 2015oct10
#
#####

# «luarocks-mailing-list» (to ".luarocks-mailing-list")
# https://github.com/keplerproject/luarocks/wiki/Mailing-list
# https://lists.sourceforge.net/lists/listinfo/luarocks-developers
# http://lists.luaforge.net/pipermail/luarocks-developers/       <- old archive
# http://sourceforge.net/p/luarocks/mailman/luarocks-developers/ <- current archive




#####
#
# running luarocks interactively
# 2014mar06
#
#####

# «luarocks-interactively» (to ".luarocks-interactively")
# (find-luarocksfile "bin/luarocks-5.1" "command_line.run_command(...)")
# (find-angg "LUA/lua50init.lua" "loadluarocks")

# (find-status   "luarocks")
# (find-vldifile "luarocks.list")
# (find-udfile   "luarocks/")
# (find-fline "/etc/luarocks/config.lua")
# (find-fline "/usr/bin/luarocks-admin")
# (find-fline "/usr/bin/luarocks")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
loadluarocks()
command_line.run_command("help")
command_line.run_command("list")
command_line.run_command("path")
command_line.run_command("help show")
command_line.run_command("help show")

-- (find-luarocks-links "lpeg")



#####
#
# luarocks interactively: my email asking for help
# 2015oct10
#
#####

# «luarocks-my-email-1» (to ".luarocks-my-email-1")
# https://mail.google.com/mail/ca/u/0/#sent/15053d74e98e7f6d (did not go)
# https://mail.google.com/mail/ca/u/0/#sent/1512767307f2d09d (sent on 2015nov21)
# http://sourceforge.net/p/luarocks/mailman/luarocks-developers/?viewmonth=201511
# http://sourceforge.net/p/luarocks/mailman/message/34636407/

Hi all,

I am trying to understand more about luarocks by running it from the
lua5.1 interpreter... I added this to my $LUA_INIT file,

  loadluarocks = function ()
      package.path = "/usr/share/lua/5.1//?.lua;/usr/share/lua/5.1//?/init.lua;"..package.path
      command_line = require("luarocks.command_line")
      program_name = "luarocks"
      program_description = "LuaRocks main command-line interface"
      commands          = {}
      commands.help     = require("luarocks.help")
      commands.pack     = require("luarocks.pack")
      commands.unpack   = require("luarocks.unpack")
      commands.build    = require("luarocks.build")
      commands.install  = require("luarocks.install")
      commands.search   = require("luarocks.search")
      commands.list     = require("luarocks.list")
      commands.remove   = require("luarocks.remove")
      commands.make     = require("luarocks.make")
      commands.download = require("luarocks.download")
      commands.path     = require("luarocks.path")
      commands.show     = require("luarocks.show")
      commands.new_version = require("luarocks.new_version")
    end

so that I can do things like this:

  Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
  > loadluarocks()
  > command_line.run_command("help")

and replace functions dynamically, adding print-like statements to
them.

One thing that I find very frustrating about luarocks is that I've
never managed to learn how to run it more verbosely... for example, if
I run this from from a shell,

  sudo luarocks remove lpeg
  sudo luarocks install lpeg

then the output shows how to build lpeg without luarocks - something
like:

  Installing http://luarocks.org/repositories/rocks/lpeg-1.0.0-1.src.rock...
  Using http://luarocks.org/repositories/rocks/lpeg-1.0.0-1.src.rock... switching to 'build' mode
  Archive:  /tmp/luarocks_luarocks-rock-lpeg-1.0.0-1-1133/lpeg-1.0.0-1.src.rock
    inflating: lpeg-1.0.0-1.rockspec   
    inflating: lpeg-1.0.0.tar.gz       
  gcc -O2 -fPIC -I/usr/include/lua5.1 -c lpcap.c -o lpcap.o
  gcc -O2 -fPIC -I/usr/include/lua5.1 -c lpcode.c -o lpcode.o
  gcc -O2 -fPIC -I/usr/include/lua5.1 -c lpprint.c -o lpprint.o
  gcc -O2 -fPIC -I/usr/include/lua5.1 -c lptree.c -o lptree.o
  gcc -O2 -fPIC -I/usr/include/lua5.1 -c lpvm.c -o lpvm.o
  gcc -shared -o lpeg.so -L/usr/local/lib lpcap.o lpcode.o lpprint.o lptree.o lpvm.o
  Updating manifest for /usr/local/lib/luarocks/rocks
  
  lpeg 1.0.0-1 is now built and installed in /usr/local/ (license: MIT/X11)

but I would like to make that output even more verbose, showing the
"chdir"s, the calls to tar and unzip, and the "cp"s - and, ideally,
but that may be much harder, to have a way to make luarocks run like
"make -n", showing the commands that it would run, but without running
them...

Any help or hints would be VERY appreciated. I understand very little
of the sources right now...

  Cheers =),
    Eduardo Ochs
    eduardoochs@gmail.com
    http://angg.twu.net/




#####
#
# LuaRocks presentation at FOSDEM 2015
# 2015feb06
#
#####

# «luarocks-fosdem2015» (to ".luarocks-fosdem2015")
# https://github.com/keplerproject/luarocks/wiki/Documentation
# http://hisham.hm/papers/talks/hisham_luarocks_fosdem2015.pdf
;; (find-fline "$S/http/hisham.hm/papers/talks/")
(code-xpdf     "luarocks2015" "$S/http/hisham.hm/papers/talks/hisham_luarocks_fosdem2015.pdf")
(code-pdf-text "luarocks2015" "$S/http/hisham.hm/papers/talks/hisham_luarocks_fosdem2015.pdf")
;; (find-luarocks2015page)
;; (find-luarocks2015text)
# (find-luarocks2015page 15 "Up and running in one slide!")
# (find-luarocks2015text 15 "Up and running in one slide!")




#####
#
# luarocks chat
# 2016sep11
#
#####

# «luarocks-chat» (to ".luarocks-chat")
https://gitter.im/keplerproject/luarocks



#####
#
# alien-0.5.0
# 2010nov10
#
#####

# «alien»  (to ".alien")
# http://alien.luaforge.net/alien-0.5.0.tar.gz
#*
rm -Rv ~/usrc/alien-0.5.0/
tar -C ~/usrc/ -xvzf \
  $S/http/alien.luaforge.net/alien-0.5.0.tar.gz
cd     ~/usrc/alien-0.5.0/

#*
# (code-c-d "alien" "~/usrc/alien-0.5.0/")
# (find-alienfile "")
# (find-alienfile "libffi/")
# (find-aliensh "find * | sort")





#####
#
# lua-gdb and lexpect
# 2008apr01 / 2009sep26
#
#####

# «lexpect»  (to ".lexpect")
# http://mysite.mweb.co.za/residents/sdonovan/lua/lua-gdb.zip
# http://linux.die.net/man/3/forkpty
# (find-man "3 forkpty")
# (find-man "3 forkpty" "Link with -lutil")
#*
rm -Rv ~/usrc/lua-gdb/
unzip -d ~/usrc/ $S/http/mysite.mweb.co.za/residents/sdonovan/lua/lua-gdb.zip
cd     ~/usrc/lua-gdb/

rm -Rv *.dll
rm -Rv *.so
gcc -shared -I$LUA51SRC/src -lutil spawnx.c -o spawnx.so
gcc -shared -I$LUA51SRC/src        stubby.c -o stubby.so

#*
rm -Rv ~/usrc/lua-gdb/
unzip -d ~/usrc/ $S/http/mysite.mweb.co.za/residents/sdonovan/lua/lua-gdb.zip
cd     ~/usrc/lua-gdb/

cat > Makefile <<'%%%'
clean:
	-rm -v *.dll
	-rm -v *.so
spawnx.so:
	gcc -shared -I${LUASODIR} -lutil spawnx.c -o spawnx.so
stubby.so:
	gcc -shared -I${LUASODIR}        stubby.c -o stubby.so
sos: spawnx.so stubby.so
test: sos
	${LUA} examples/ftp.lua
%%%

# (find-fline "$LUA51SRC/")

make clean
make LUASODIR=$LUA51SRC/src sos
make LUA=$LUA51SRC/bin/lua test

#*
# (find-luamanualw3m "#pdf-package.loadlib")
# (code-c-d "luagdb" "~/usrc/lua-gdb/")
# (find-luagdbfile "")
# (find-luagdbfile "lexpect.lua")
# (find-luagdbfile "spawnx.c")
# (find-luagdbfile "spawnx.c" 149)
# (find-luagdbfile "examples/ftp.lua")

# Old stuff:

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rv ~/usrc/lua-gdb/
unzip -d ~/usrc/ $S/http/mysite.mweb.co.za/residents/sdonovan/lua/lua-gdb.zip
cd     ~/usrc/lua-gdb/
rm -Rv *.dll
rm -Rv *.so
gcc -shared -I$LUA51SRC/src -lutil spawnx.c -o spawnx.so
gcc -shared -I$LUA51SRC/src        stubby.c -o stubby.so
cd ~/usrc/lua-gdb/
lua51
-- require "path"
-- = path.loadlib('lexpect','spawnx')
L = require 'lexpect'
L.open 'ftp'
L.writeln 'open ftp.csir.co.za'
L.expect(': $',true)
L.writeln 'anonymous'
L.expect(':%s*$',true)
L.writeln 'sjdonova@csir.co.za'
L.prompt = 'ftp>'
print(L.read_response_string())
print(L.command_string 'ls')
L.command 'quit'

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
chdir "~/usrc/lua-gdb/"
require 'path'
if not path.loadlib('lexpect','spawnx') then
	print 'cannot find spawnx in same directory as lexpect.lua'
end
PP(path.loadlib('lexpect','spawnx'))
-- (find-luagdbfile "spawnx.c" "forkpty")
-- (find-luagdbfile "")
-- (find-luagdbfile "examples/ftp.lua")
-- (find-angg "LUA/lua50init.lua" "chdir")
chdir "~/usrc/lua-gdb/"
-- (find-luagdbfile "lexpect.lua")
L = require 'lexpect'
L.open 'ftp'
L.writeln 'open ftp.csir.co.za'
L.expect(': $',true)
L.writeln 'anonymous'
L.expect(':%s*$',true)
L.writeln 'sjdonova@csir.co.za'
L.prompt = 'ftp>'
print(L.read_response_string())
print(L.command_string 'ls')
L.command 'quit'

# (find-man "3 execvp")
# (find-node "(libc)Executing a File" "Function: int execvp")

To: steve donovan
Date: 2009sep25
Subj: Status of lexpect?
Hi Steve,

what is the status of lexpect? Is the version from

  http://mysite.mweb.co.za/residents/sdonovan/lua/lua-gdb.zip

the latest one? I'm trying to run it - recompiling the ".so"s in a
naive way - and I'm getting a linking error...

Here's what I've done:

  rm -Rv ~/usrc/lua-gdb/
  unzip -d ~/usrc/ $S/http/mysite.mweb.co.za/residents/sdonovan/lua/lua-gdb.zip
  cd     ~/usrc/lua-gdb/

  rm -Rv *.dll
  rm -Rv *.so
  gcc -shared -I$LUA51SRC/src spawnx.c -o spawnx.so
  gcc -shared -I$LUA51SRC/src stubby.c -o stubby.so

and then doing a "require 'lexpect'" in Lua fails, and if I try to
debug the problem here's what I get:

  /home/edrx/usrc/lua-gdb(edrx:pe)# $LUA51SRC/bin/lua
  Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
  > require "path"
  > if not path.loadlib('lexpect','spawnx') then
  >>     print 'cannot find spawnx in same directory as lexpect.lua'
  >> end
  cannot find spawnx in same directory as lexpect.lua
  > = path.loadlib('lexpect','spawnx')
  nil	cannot load extension: ./spawnx.so: undefined symbol: forkpty
  > 

Any hints? What is the right way to build the ".so"s? 8-\

  Cheers & thanks in advance,
    Eduardo Ochs
    eduardoochs@gmail.com
    http://angg.twu.net/

P.S.: I'm running all this in a Debian Stable ("Lenny") box...

---
(His answer:)

(...)

The only thing missing is -lutil for spawnx.c so that forkpty() can be found.

x in same directory as lexpect.lua
>  > = path.loadlib('lexpect','spawnx')
>  nil   cannot load extension: ./spawnx.so: undefined symbol: forkpty
>  >

It would help if the code actually gave the proper error message ;)

I'll package it properly, sorry packaging quality ain't always my
strong point. I'm intending to make lexpect/luagdb available as rocks,
but I'll sort out the makefiles as well.

steve d.




#####
#
# lpty (similar to lexpect)
# 2010aug17
#
#####

# «lpty»  (to ".lpty")
# http://www.tset.de/lpty/
# http://www.tset.de/downloads/lpty-0.8-2.tar.gz
# (find-man "7 pty")
# (find-node "(libc)Pseudo-Terminals")






#####
#
# shells in lua
# 2008may02
#
#####

# «shells-in-lua»  (to ".shells-in-lua")

Ei, acabei de ter uma ideia muito legal relacionada a essa historia de
passar os scripts todos pra Lua...

Quando o shell recebe uma linha como

  wget -q -O - http://foo/bar | apt-key add -

ele separa ela em "comandos" (o "|" e' um sinal de diz como conectar
dois comandos separados) e depois em "palavras"; cada comando vira um
processo, e estes processos estao ligados entre si de certos modos...
por exemplo, o output do "wget" e' um pipe que e' o input do
"apt-key", e se o shell receber certos "signals" do wget ou do apt-key
ele retransmiste esses signals pro outro programa da pipeline...

Bom, shells interpretam essas pipelines criando processos conectados -
e fazem isso com umas rotinas em C que nao sao compridas (umas 100
linhas, acho, em codigo de baixo nivel que chama diretamente as kernel
calls) e que eu sempre quis entender...

Acho ate' que a parte em C necessaria pra gente fazer tudo isso a
partir de Lua ja' deve estar toda pronta dentro do lposix... e, bom,
tendo as ideias e as desculpas certas da' pra mandar umas mensagens
pra lista de Lua e os bichos de C e POSIX da lista vao produzir num
instante o codigo em lua que executa coisas como:

  w = command({"wget", "-q", "-O", "-", "http://foo/bar"})
  a = command({"apt-key", "add", "-"})
  p = pipeline({w, "|", a})
  run(p)

E ai' vamos ter uma biblioteca para fazer shells em Lua, que e' algo
que vai interessar a muita gente...

Ah, a parte de editar os arquivos de configuracao do Plurall usando
Lua e' facilima, claro...

  []oooooo,
    Edrx





#####
#
# coxpcall-1.12.0
# 2008may09
#
#####

# «coxpcall»  (to ".coxpcall")
# http://luaforge.net/frs/download.php/3351/coxpcall-1.12.0.tar.gz
#*
rm -Rv ~/usrc/coxpcall-1.12.0/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/3351/coxpcall-1.12.0.tar.gz
cd     ~/usrc/coxpcall-1.12.0/

#*
# (code-c-d "coxpcall" "~/usrc/coxpcall-1.12.0/")
# (find-coxpcallfile "")




#####
#
# elua and grub
# 2008jul08
#
#####

# «elua-and-grub»  (to ".elua-and-grub")
# (find-fline "/boot/grub/menu.lst")

# http://elua.luaforge.net/tut_boot_lua.html
# http://elua.luaforge.net/surprise
# (find-sh0 "mount | grep hd")
# (find-sh0 "sudo cp -v $S/http/elua.luaforge.net/surprise /boot/surprise")
# (find-fline "/boot/")
#
title ELua
root (hd0,0)
kernel /surprise




#####
#
# elua
# 2008sep02
#
#####

# «elua»  (to ".elua")
# (find-es "anatocc" "newlib-upstream")
# http://download.berlios.de/elua/elua_0.4.tgz
# http://elua.berlios.de/download.html
# http://elua.berlios.de/doc_building.html
# http://elua.berlios.de/doc_use_i386.html
# http://elua.berlios.de/tut_boot_lua.html
# http://elua.berlios.de/tut_gcc_i386.html
# http://elua.berlios.de/tut_gcc_arm.html
# https://lists.berlios.de/pipermail/elua-dev/
# http://developer.berlios.de/mail/?group_id=9919
#*
rm -Rv ~/usrc/elua/
tar -C ~/usrc/ -xvzf \
  $S/http/download.berlios.de/elua/elua_0.4.tgz
cd     ~/usrc/elua/

#*
# (code-c-d "elua" "~/usrc/elua/")
# (find-eluafile "")
# (find-eluafile "docs/")
# (find-eluagrep "grep -nriH -e grub *")
# (find-eluafile "src/platform/i386/")

# (find-zsh "dmissing newlib")
# (find-zsh "dmissing i686-elf-gcc")

# (find-status   "libnewlib-dev")
# (find-vldifile "libnewlib-dev.list")
# (find-udfile   "libnewlib-dev/")
# http://ftp.debian.org/debian/pool/main/n/newlib/
# http://ftp.debian.org/debian/pool/main/n/newlib/newlib_1.16.0-3.dsc

apti scons nasm libnewlib-dev

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd     ~/usrc/elua/
scons cpu=i386

# 2011nov25:
# http://eluabrain.blogspot.com/





#####
#
# apairs and print
# 2008jul10
#
#####

# «apairs-and-print»  (to ".apairs-and-print")
# From a message by Thomas Lauer on lua-l, 2008jul10
# http://lua-users.org/lists/lua-l/2008-07/msg00188.html
# [...] the print() function [...] is hardcoded to use the output
# handle that was in place when the interpreter was started (print()
# has for obvious reasons no notion of module io).

-- Or use this as a replacement for print()
function apairs(...)
       local function _apairs(a,i)
               if i<a.n then return i+1,a[i+1] end
       end
       return _apairs,{n=select('#',...),...},0
end

function print(...)
       local t={}
       -- the much simpler local t={...} doesn't cut it if there's
       -- a terminating nil in ... so this does it bit by bit
       for i,v in apairs(...) do t[i]=tostring(v) end
       io.stdout:write(table.concat(t,'\t'),'\n')
end

print(1,2,3,"four",nil)
print(1,2,3,"four",nil,true)




#####
#
# LUA_COMPAT_VARARG
# 2008jul18
#
#####

# «LUA_COMPAT_VARARG»  (to ".LUA_COMPAT_VARARG")
# (find-angg "LUA/lua50init.lua" "pack-and-unpack")
# http://lua-users.org/lists/lua-l/2008-07/msg00369.html
# (find-luamanualw3m "#pdf-select")
# (find-luamanualw3m "#7.1" "LUA_COMPAT_VARARG")
# (find-lua51file "src/luaconf.h" "LUA_COMPAT_VARARG")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)

pack51 = function (...) return {n=select("#",...), ...} end
PP(pack51(1, 2))
PP(pack51(1, 2, nil))
PP({10, 20, a=30, 40, 50})




#####
#
# Coroutines as iterators
# 2008aug02
#
#####

# «coroutine-iterator»  (to ".coroutine-iterator")
# (find-pilw3m "9.3.html")
# (find-pilw3m "9.3.html" "9.3 - Coroutines as Iterators")
# (find-luamanualw3m "#2.11" "coroutine.wrap")
# (find-luamanualw3m "#pdf-coroutine.wrap")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
function permgen (a, n)
  if n == 0 then
    coroutine.yield(a)
  else
    for i=1,n do
      a[n], a[i] = a[i], a[n]
      permgen(a, n - 1)
      a[n], a[i] = a[i], a[n]
    end
  end
end
function perm (a)
  return coroutine.wrap(function () permgen(a, #a) end)
end
for p in perm{"a", "b", "c", "d"} do
  print(table.concat(p, " "))
end

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)

uples = function (A)
    return coroutine.wrap(function ()
        for _,a in ipairs(A) do
          for _,b in ipairs(A) do
            coroutine.yield(a, b)
          end
        end
      end)
  end
for a,b in uples({"aa", "bb"}) do print(a, b) end




#####
#
# Modal and intuitionistic logic
# 2008aug03
#
#####

# «modal.lua»  (to ".modal.lua")
# (find-angg "LUA/modal.lua")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
ee_dofile "~/LUA/modal.lua"   -- (find-angg "LUA/modal.lua")

-- I want to check that the implication
--   (P*\/Q)*=>(P\/Q)*
-- is strict; that is, I need a countermodel for
--   (P*\/Q)*<=>(P\/Q)*,  i.e., for:
--   (P*\/Q)*<=(P\/Q)*
--
formula = function (p, q)
    return iimp(star(iimp(p, q)), star(iimp(star(p), q)))
  end

Setup(Meta_Two)
for a,p,q in generatetriples(itvs) do
  star = star_or(a)
  if formula(p, q) ~= t then print(a, p, q) end
end
PP(t)

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
dofile "/home/edrx/LUA/modal.lua"   -- (find-angg "LUA/modal.lua")
Setup(Meta_House); printneight(iand, 4)
Setup(Meta_House); printneight(ior, 5)
Setup(Meta_House); printneight(iimp, 3)
Setup(Meta_House); printeight (iimp, 3)
Setup(Meta_Bighouse); printeight (iimp, 3)

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
dofile "/home/edrx/LUA/modal.lua"   -- (find-angg "LUA/modal.lua")
setup(5, Nec_House); printneight(iand, 4)
setup(5, Nec_House); printneight(ior, 5)
setup(5, Nec_House); printneight(iimp, 3)
setup(5, Nec_House); printeight (iimp, 3)

Setup(Meta_Vee)
PP(itvs)
printeight(iand)
printneight(iand)

PP(toset{"aaa", "bb", "cccc", "aaa"})
PP(keys(toset{"aaa", "bb", "cccc", "aaa"}))
= #keys(toset{"aaa", "bb", "cccc", "aaa"})
= differents{"aaa", "bb", "cccc", "aaa"}
Setup(Meta_Reh)
PP(addss({}, 4))
= iimp("0101", "0011")
= S(mand(M"0011", M"0101"))
= S(mimp(M"0011", M"0101"))
= S(Nec_Reh(M"1001"))




#####
#
# lpeg.Cmt
# 2008aug06
#
#####

# «lpeg.Cmt»  (to ".lpeg.Cmt")
# (find-lpegw3m "lpeg.html#matchtime")
# (find-lpegw3m "lpeg.html#func")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
loadlpeg()

Open        = lpeg.S "("
Close       = lpeg.S ")"
Middlechar  = 1 - lpeg.S "()"
Middlechars = Middlechar^1
Middle      = lpeg.P { (Middlechars + Open * lpeg.V(1) * Close)^0 }
Block       = Open * Middle * Close
CBlock      = Open * Middle:C() * Close

Middlechars:test "foo (bar)"
Block:test "foo"
Block:test "(foo) bar"
Block:test "(foo (bar)) hmm"
Block:test "(foo (bar) ((plic) (ploc)) plec) hmm"
CBlock:test "(foo (bar)) hmm"

Onearg      = CBlock * lpeg.Cp()
Twoargs     = CBlock * CBlock * lpeg.Cp()

-- (find-lpegw3m "lpeg.html#matchtime")
-- (find-lpegw3m "lpeg.html#func")
Cmdname = lpeg.R "az" ^1
Cmd     = lpeg.P "/" * Cmdname:Cmt(function(subj, pos, cmdname)
    if cmdname == "one" then
      local a, newpos = Onearg:match(subj, pos)
      if newpos then return newpos, "<"..a..">" end
    elseif cmdname == "two" then
      local a, b, newpos = Twoargs:match(subj, pos)
      if newpos then return newpos, "<"..a..">", "<"..b..">" end
    end
  end)

Cmd:test "/one(aa)(bb)"
Cmd:test "/two(cc)(dd)(ee) blah"
Cmd:test "/two(cc) (dd)(ee) blah"



# «lpeg.Cmt-2»  (to ".lpeg.Cmt-2")
-- (find-angg "LUA/preproc.lua")
-- (find-lpegw3m "lpeg.html#matchtime")
-- (find-lpegw3m "lpeg.html#func")
-- (find-fline "~/LOGS/2008sep19.lua")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
loadlpeg()
lpeg.togsub = lpeg_togsub  -- (find-angg "LUA/lua50init.lua" "lpeg_togsub")
lpeg.gsub   = lpeg_gsub    -- (find-angg "LUA/lua50init.lua" "lpeg_gsub")
Uppers  = lpeg.R"AZ" ^1
Lowers  = lpeg.R"az" ^1
Comma   = lpeg.P","
OneArg  = Lowers:C()
TwoArgs = Lowers:C()*Comma*Lowers:C()

OneArg:testt "foo,bar,plic"
TwoArgs:testt "foo,bar,plic"

setcommandname = function (subj, pos, name)
    -- PP("sc:", subj, pos, name)
    if not A[name] then return end
    commandname = name
    return true
  end
setcommandargs = function (subj, pos, ...)
    -- PP("sa:", subj, pos, ...)
    commandargs = pack(...)
    return true
  end

A = {}  -- argument parsers
C = {}  -- what "command" to run on the arguments
A["ONE"] = OneArg:Cmt(setcommandargs)
C["ONE"] = function (a)    return format("(one: %s)", a) end
A["TWO"] = TwoArgs:Cmt(setcommandargs)
C["TWO"] = function (a, b) return format("(two: %s %s)", a, b) end

CommandName = Uppers:Cmt(setcommandname)
CommandArgs = lpeg.P(function (subj, pos)
    return A[commandname]:match(subj, pos)
  end)
BadArgs     = lpeg.P(function (subj, pos)
    error("Bad args for "..commandname)
  end)
CommandRun  = lpeg.P(function (subj, pos)
    return pos, C[commandname](unpack(commandargs))
  end)
Command     = lpeg.P"@" * CommandName * (CommandArgs + BadArgs) * CommandRun

Command:testt "@ONEabc,def"
Command:testt "@TWOabc,def,ghi"
Command:testt "@TWOabc,def"
Command:testt "@TWOabc"      -- error
Command:testt "@THREEabc,def,ghi"

id = function (...) return ... end
= Command:gsub("ab@ONEabc,def @TWOa,b,c,d", id)




#####
#
# preproc
# 2008sep26
#
#####

# «preproc»  (to ".preproc")
# (find-anggfile "LUA/preproc.lua")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
ee_dofile "~/LUA/preproc.lua"   -- (find-angg "LUA/preproc.lua")
F = function (fmt) return function (...) return format(fmt, ...) end end
cmddef("ONE",   Curly1, F"(one: %s)")
cmddef("TWO",   Curly2, F"(two: %s %s)")
cmddef("THREE", Curly3, F"(three: %s %s %s)")
= preproc "\\ONE{foo}{bar}_\\TWO{plic}{ploc}{woo} bleh"
      --> "(one: foo){bar}_(two: plic ploc){woo} bleh"




#####
#
# ee_loadlib
# 2008aug06
#
#####

# «ee_loadlib»  (to ".ee_loadlib")
# (find-luamanualw3m "#pdf-require")
# (find-angg "LUA/lua50init.lua" "ee_loadlib")
# (find-angg "LUA/lua50init.lua" "loadlpeg")
# Should I create low-level versions of my load___ functions?...

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
ee_loadlib = function (libname, funcname)
    return assert(package.loadlib(ee_expand(libname), funcname))()
  end
loadlpeg = function (fname)
    if lpeg then return "already loaded" end
    ee_loadlib(fname or "~/usrc/lpeg-0.8.1/lpeg.so", "luaopen_lpeg")
    lpeg.test = function (pat, str) PP(pat:C():match(str)) end
  end
loadlpeg()
PP(lpeg)




#####
#
# shake-1.0.1
# 2008sep26
#
#####

# «shake»  (to ".shake")
# http://luaforge.net/frs/download.php/3009/shake-1.0.1.tar.gz
#*
rm -Rv ~/usrc/shake-1.0.1/
tar -C ~/usrc/ -xvzf \
  $S/http/luaforge.net/frs/download.php/3009/shake-1.0.1.tar.gz
cd     ~/usrc/shake-1.0.1/

#*
# (code-c-d "shake" "~/usrc/shake-1.0.1/")
# (find-shakefile "")
# (find-shakew3m "doc/us/index.html")




#####
#
# ctemplate
# 2008oct12
#
#####

# «ctemplate»  (to ".ctemplate")
# (find-angg "LUA/ctemplate.lua")
# (find-angg "LUA/ctemplate.lua" "demo")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
ee_dofile "~/LUA/ctemplate.lua"  -- (find-angg "LUA/ctemplate.lua")
T = ccompile {name="foo", body=[[printf("Hello 2!\n"); return 0;]]}
T:load()
foo()

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
ee_dofile "~/LUA/ctemplate.lua"  -- (find-angg "LUA/ctemplate.lua")
cbody = [[lua_pushnumber(L, 44); return 1;]]
cloadfoo()
= foo()

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
ee_dofile "~/LUA/ctemplate.lua"  -- (find-angg "LUA/ctemplate.lua")
cbody = [[lua_pushnumber(L, 44); return 1;]]
cloadfoo()
= foo()

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
ee_dofile "~/LUA/ctemplate.lua"  -- (find-angg "LUA/ctemplate.lua")
cbody = [[
  lua_pushnumber(L, 100 * lua_tonumber(L, -2) /* 1st arg */
                        + lua_tonumber(L, -1) /* 2nd arg */ );
                         /*  ^ 1st result */
  lua_pushnumber(L, 44); /* <- 2nd result */
  return 2;
]]
cloadfoo()
= foo(2, 3)   --> 203 44




#####
#
# string.__call
# 2008oct20
#
#####

# «string.__call»  (to ".string.__call")
# (find-luamanualw3m "#pdf-string.byte")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
= getmetatable("foo")
= getmetatable("foo").__index
= string
  ("foo")("bar")   --> error: attempt to call a string value
= getmetatable("foo").__call
  getmetatable("foo").__call = PP
  ("foo")("bar")   --> "foo" "bar"
  getmetatable("foo").__call = string.byte
= ("foobar")(2)    --> 111
= ("foobar")(2, 4) --> 111 111 98
  getmetatable("foo").__call = nil
  ("foo")("bar")   --> error: attempt to call a string value




#####
#
# wordgrinder (has ncurses support)
# 2008nov20
#
#####

# «wordgrinder»  (to ".wordgrinder")
# http://wordgrinder.sourceforge.net/
# http://downloads.sourceforge.net/wordgrinder/wordgrinder-0.3.2.tar.bz2
#*
rm -Rv ~/usrc/wordgrinder-0.3.2/
tar -C ~/usrc/ -xvjf \
  $S/http/downloads.sourceforge.net/wordgrinder/wordgrinder-0.3.2.tar.bz2
cd     ~/usrc/wordgrinder-0.3.2/

#*
# (code-c-d "wordgrinder" "~/usrc/wordgrinder-0.3.2/")
# (find-wordgrinderfile "")
# (find-wordgrinderfile "README.Unix" "Debian")

# libncursesw5-dev liblua5.1-0-dev liblua5.1-filesystem0
# (find-available "liblua5.1-0-dev")
# (find-available "liblua5.1-filesystem0")



#####
#
# primemover (used by wordgrinder)
# 2008nov20
#
#####

# «primemover»  (to ".primemover")
# http://downloads.sourceforge.net/primemover/primemover-0.1.4.tar.bz2
#*
rm -Rv ~/usrc/primemover-0.1.4/
tar -C ~/usrc/ -xvjf \
  $S/http/downloads.sourceforge.net/primemover/primemover-0.1.4.tar.bz2
cd     ~/usrc/primemover-0.1.4/

#*
# (code-c-d "primemover" "~/usrc/primemover-0.1.4/")
# (find-primemoverfile "")





#####
#
# vectors
# 2009may01
#
#####

# «vectors»  (to ".vectors")
# (find-luamanualw3m "#2.8" "Metatables")
# (find-luamanualw3m "#2.8" "Metatables" "__add")
# (find-luamanualw3m "#pdf-setmetatable")
# (find-anggfile "LUA/tos.lua")
# (find-pilw3m "index.html" "13 Metatables and Metamethods")
# (find-pilw3m "13.1.html" "function Set.union")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
ee_dofile "~/LUA/tos.lua"
vector_mt = {
  __add = function (a, b, c, d) PP("__add", a, b, c, d); return 99 end,
  __sub = function (a, b, c, d) PP("__sub", a, b, c, d); return 99 end,
  __unm = function (a, b, c, d) PP("__unm", a, b, c, d); return 99 end,
  __mul = function (a, b, c, d) PP("__mul", a, b, c, d); return 99 end,
}
vector = function (x, y) return setmetatable({x, y}, vector_mt) end

v = {2, 3}
setmetatable(v, vector_mt)
= v + v

= vector(2, 3) + vector(4, 5)
= vector(2, 3) + 45
=           23 + vector(4, 5)
=              - vector(4, 5)

vector_mt.__add = function(v, w) return vector(v[1]+w[1], v[2]+w[2]) end
vector_mt.__sub = function(v, w) return vector(v[1]-w[1], v[2]-w[2]) end
vector_mt.__mul = function(x, v) return vector(x*v[1], x*v[2]) end
vector_mt.__unm = function(v)    return vector(-v[1], -v[2]) end
vector_mt.__tostring = function(v)
    return "["..tostring(v[1])..", "..tostring(v[2]).."]"
  end

= vector(2, 3) + vector(4, 5)
= vector(2, 3) - vector(4, 5)
=           20 * vector(4, 5)
=              - vector(4, 5)

-- This one gives an error ("attempt to index local 'w' (a number value)"):
= vector(2, 3) + 45





#####
#
# Löve2D - stuff moved to love.e
#
#####

# «love»		(to ".love")
# «love-deb-src»	(to ".love-deb-src")
# «tableauxprover»	(to ".tableauxprover")
# «love-vilua»		(to ".love-vilua")

# (find-es "love" "love")
# (find-es "love" "love-deb-src")
# (find-es "love" "tableauxprover")
# (find-es "love" "love-vilua")




#####
#
# lua-gnuplot
# 2009oct02
#
#####

# «lua-gnuplot»  (to ".lua-gnuplot")
# (find-es "gnuplot")
# (find-es "maxima")
# http://luaforge.net/projects/gnuplot/
# http://luaforge.net/frs/download.php/3007/gnuplot_t.lua





#####
#
# lua5.1-tests
# 2009oct02
#
#####

# «lua5.1-tests»  (to ".lua5.1-tests")
# http://lua-users.org/lists/lua-l/2008-06/msg00124.html
# http://www.inf.puc-rio.br/~roberto/lua/lua5.1-tests.tar.gz
#*
rm -Rv ~/usrc/lua5.1-tests/
tar -C ~/usrc/ -xvzf \
  $S/http/www.inf.puc-rio.br/~roberto/lua/lua5.1-tests.tar.gz
cd     ~/usrc/lua5.1-tests/

#*
# (code-c-d "lua51tests" "~/usrc/lua5.1-tests/")
# (find-lua51testsfile "")
# (find-lua51testsfile "README")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd     ~/usrc/lua5.1-tests/
export LUA_PATH="?;./?.lua"
export LUA_PATH="./?.lua;;"
export LUA_INIT="package.path = '?;'..package.path"
w lua51
  lua51 all.lua

# They fail:
# (find-lua51testsfile "main.lua" 31)
# (find-lua51testsfile "main.lua" 99)
# (find-lua51testsfile "all.lua" 69)




#####
#
# lua-5.2 tests
# 2012may31
#
#####

# «lua5.2-tests»  (to ".lua5.2-tests")
# http://www.lua.org/tests/5.2/
# http://www.lua.org/tests/5.2/index.html
# http://www.lua.org/tests/5.2/lua-5.2.0-tests.tar.gz
#*
rm -Rv ~/usrc/lua-5.2.0-tests/
tar -C ~/usrc/ -xvzf \
  $S/http/www.lua.org/tests/5.2/lua-5.2.0-tests.tar.gz
cd     ~/usrc/lua-5.2.0-tests/

#*
* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd     ~/usrc/lua-5.2.0-tests/
lua52 -e"_U=true" all.lua   |& tee ot

# (code-c-d "lua52tests" "~/usrc/lua-5.2.0-tests/")
# (find-lua52testsfile "")




#####
#
# ltcltk
# 2010mar23
#
#####

# «ltcl»  (to ".ltcl")
# «ltcltk»  (to ".ltcltk")
# (find-es "tcl" "bibtex")
# (find-angg ".emacs" "ltcltk")
# (find-luarocks-links "ltcltk")
# (find-luarocks-links "ltcltk" "0.9-2" "")
# http://www.tset.de/ltcltk/
# http://www.tset.de/ltcltk/README.html
# http://www.tset.de/ltcltk/README_ltcl.html
# http://www.tset.de/ltcltk/README_ltk.html
# (find-ltcltkfile "")
# (find-ltcltkfile "doc/")
# (find-ltcltkfile "doc/README")
# (find-ltcltkfile "doc/README_ltcl")
# (find-ltcltkfile "doc/README_ltk")
# (find-ltcltkfile "samples/")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
userocks()
chdir "~/usrc/ltcltk-0.9-2/"
chdir "~/usrc/ltcltk-0.9-2/samples/"
-- (find-ltcltkfile "samples/")
dofile "ltcltest.lua"
dofile "ltkcheckers.lua"

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
userocks()
require "ltk"
ltk.update()
c = ltk.canvas {width = 300, height = 200} 
cc = ltk.wcmd(c)
ltk.pack {c}
ltk.update()

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
userocks()
chdir "~/dednat5/"
require "repl"
tcl_incomplete3 = function (repl, body) return false end
tcl_eval3       = function (repl, body) print(tcl:eval(body)) end
Repl.__index.incomplete3 = tcl_incomplete3
Repl.__index.eval3       = tcl_eval3

require "ltcl"
tcl = ltcl.new()
repl()
=== expr "1+2"
=== package require Tk
=== update
=== canvas .c -background bisque
=== pack .c -expand yes -fill both
=== update
=== .c create line 10 20 30 50
=== update

-- (find-man "3tcl update")
-- (find-angg "LUA/vectors.lua")
-- (find-angg "LUA/vectors.tcl")

# Old stuff:
# http://www.tset.de/downloads/ltcltk-0.9-1.tar.gz
# http://www.tset.de/ltcltk/README.html
# http://www.tset.de/ltcltk/README_ltcl.html
# http://www.tset.de/ltcltk/README_ltk.html
#*
rm -Rv ~/usrc/ltcltk-0.9-1/
tar -C ~/usrc/ -xvzf \
  $S/http/www.tset.de/downloads/ltcltk-0.9-1.tar.gz
cd     ~/usrc/ltcltk-0.9-1/

gcc --shared -ltcl8.4 \
  -Wall \
  -I$LUA51SRC/src/ -I/usr/include/tcl8.4/ \
  -o ltcl.so ltcl.c

#*
# (code-c-d "ltcltk" "~/usrc/ltcltk-0.9-1/")
# (find-ltcltkfile "")
# (find-ltcltkfile "doc/")
# (find-ltcltkfile "doc/README")
# (find-ltcltkfile "doc/README_ltcl")
# (find-ltcltkfile "doc/README_ltk")
# (find-ltcltkfile "ltcltk-0.9-1.rockspec")
# (find-lua51w3m "doc/manual.html#pdf-require")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
chdir "~/usrc/ltcltk-0.9-1/"
ee_loadlib("~/usrc/ltcltk-0.9-1/ltcl.so", "luaopen_ltcl")
PP(tcl)   --> wrong - what's this?
PP(ltcl)
tcl = ltcl.new()
PP(tcl)
= tcl:eval("expr 1+2")
= tcl:eval("expr 1+")
dofile "ltk.lua"


* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
chdir "~/usrc/ltcltk-0.9-1/"
ee_loadlib("~/usrc/ltcltk-0.9-1/ltcl.so", "luaopen_ltcl")
tcl = ltcl.new()
dofile "ltk.lua"
b=ltk.button { text="Ok" }
bcmd = ltk.wcmd(b)
ltk.pack{b}
ltk.mainloop()

-- (find-ltcltkfile "doc/README_ltk")
-- (find-ltcltkfile "samples/ltcltest.lua")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
package.cpath = package.cpath..";/home/edrx/usrc/luaposix-5.1.4/?.so"
package.cpath = package.cpath..";/home/edrx/usrc/ltcltk-0.9-1/?.so"
package.path  = package. path..";/home/edrx/usrc/ltcltk-0.9-1/?.lua"
require "ltk"

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
package.cpath = package.cpath..";/home/edrx/usrc/luaposix-5.1.4/?.so"
package.cpath = package.cpath..";/home/edrx/usrc/ltcltk-0.9-1/?.so"
package.path  = package. path..";/home/edrx/usrc/ltcltk-0.9-1/?.lua"
ee_dofile "~/usrc/ltcltk-0.9-1/samples/ltkfuncplotter.lua"

-- require "ltk"
* (find-ltcltkfile "samples/ltcltest.lua")
* (find-ltcltkfile "samples/")
* (find-ltcltkfile "samples/ltkfuncplotter.lua")




#####
#
# ltcltk-1.9-1
# 2011nov09
#
#####

# «ltcltk-new»  (to ".ltcltk-new")
# http://www.tset.de/downloads/ltcltk-1.9-1.tar.gz
#*
rm -Rv ~/usrc/ltcltk-1.9-1/
tar -C ~/usrc/ -xvzf \
  $S/http/www.tset.de/downloads/ltcltk-1.9-1.tar.gz
cd     ~/usrc/ltcltk-1.9-1/

#*
# (code-c-d "ltcltk" "~/usrc/ltcltk-1.9-1/")
# (find-ltcltkfile "")





#####
#
# addlayer and removelayer
# 2010jun18
#
#####

# «addlayer»  (to ".addlayer")
# (find-luamanualw3m "#2.8" "\"index\"")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
set__index  = function (T, I)
    local mt = getmetatable(T) or {}
    mt.__index = I
    setmetatable(T, mt)
    return T
  end
addlayer    = function (T) return setmetatable({}, {__index = T}) end
removelayer = function (T) return getmetatable(T).__index end
T = {10, 20, 3}
T = addlayer(T)       --  T is now an {} whose whose mt.__index is the old T
PP(T)                 --> {}
PP(T[2])              --> 20
PP(removelayer(T)[3]) --> 30
PP(T)                 --> {} (still the same)
T = removelayer(T)    --> P is now {10, 20, 30} again
PP(T)                 --> {10, 20, 30}




#####
#
# Phyzios Lab (warning: closed source)
# 2010jul10
#
#####

# «phyzios»  (to ".phyzios")

http://phyzios.net/Lab/Scene.aspx?id=PSLAB00000000066
http://phyzios.net/Lab/Wiki/

Hello. I am a developer from Phyzios, Inc. We've created a web application
using Lua Alchemy (http://code.google.com/p/lua-alchemy) and Box2d Flash
World Construction Kit (http://github.com/jesses/wck). By using the
application, you can create your own physics world by writing Lua codes.

Phyzios Lab: http://phyzios.net/Lab/

This is a research project and currently is a closed beta version. We
appreciate any comment/feedback/suggestion from you. Thanks.

Best regards,
Teruyoshi Sasaki


# file:///tmp/phyzios_6.html
# file:///home/edrx/PHYZIOS/phyzios_6.html
# (find-fline "~/PHYZIOS/")



#####
#
# Bison and Lua
# 2010jul30
#
#####

# «bison-and-lua»  (to ".bison-and-lua")
# (find-luamanualw3m "#2.4.1" "Chunks")
# (find-luamanualw3m "#8" "The Complete Syntax of Lua")
# (find-es "lexyacc")
# (find-node "(libc)Formatted Output Functions")
# (find-dn4 "newtrees.lua" "trees")
# (find-bison "foo1.y")

Just a vague idea at the moment... Here it is. It shouldn't be hard to
code in Bison and Lexx the syntax of Lua; the result of parsing a lua
chunk should be a Lua chunk that creates a tree-ish data structure in
Lua -- something like what I do in "newtrees.lua" --, and these tress
will then be easy to process.




#####
#
# luainspect
# 2010aug15
#
#####

# «luainspect»  (to ".luainspect")
# (find-es "cvs" "git")

# http://github.com/davidm/lua-inspect

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rv ~/usrc/lua-inspect/
cd     ~/usrc/
git clone http://github.com/davidm/lua-inspect.git
cd     ~/usrc/lua-inspect/

# (code-c-d "luainspect" "~/usrc/lua-inspect/")
# (find-luainspectfile "")
# (find-luainspectsh "find | sort")
# (find-luainspectfile "luainspectlib/luainspect/")
# (find-luainspectfile "luainspectlib/luainspect/html.lua")



#####
#
# Sticky metatables
# 2010sep30
#
#####

# «sticky-metatables»  (to ".sticky-metatables")
# «metatable-reductions»  (to ".metatable-reductions")
# The trick is based on these reduction rules:
#   T(...)       -~->  T.__mt.__call(T, ...)
#   tostring(T)  -~->  T.__mt.__tostring(T)
# I am not sure if these reductions hold:
#   A + B        -~->  A.__mt.__add(A, B)
#   A - B        -~->  A.__mt.__sub(A, B)
#   A * B        -~->  A.__mt.__mul(A, B)
#   A / B        -~->  A.__mt.__div(A, B)
#   A % B        -~->  A.__mt.__mod(A, B)
#   A ^ B        -~->  A.__mt.__pow(A, B)
#   A .. B       -~->  A.__mt.__concat(A, B)
#   A[B]         -~->  A.__mt.__index(A, B)
#   -A           -~->  A.__mt.__unm(A, A)
# Other: (find-es "lua-intro" "quick-presentation" "Missing:")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)

minitostring = function (o) return type(o)=="string" and o or mytostring(o) end
Format = function (fmt, ...)
    return format(fmt, unpack(map(minitostring, {...})))
  end

formatfields = function (T, fmt, ...)
    -- local formatfield = function (field) return     tostring(T[field]) end
    -- local formatfield = function (field) return   mytostring(T[field]) end
    local    formatfield = function (field) return minitostring(T[field]) end
    return format(fmt, unpack(map(formatfield, {...})))
  end
lazyformat = function (args)
    return function (T)
        return formatfields(T, unpack(args))
      end
  end

revsetmetatable = function (mt, T) return setmetatable(T, mt) end
sticky = function (mt)
    return setmetatable(mt, {__call = revsetmetatable})
  end

stickyformat = function (fmtargs)
    return sticky {__tostring = lazyformat(fmtargs)}
  end

= lazyformat {"[%s %s]", 1, 2} {20, 30}        --> [20 30]
= lazyformat {"[%s %s]", 1, 2} {20, {30, 40}}  --> [20 {1=30, 2=40}]

prodprint = lazyformat {"(%s*%s)", 1, 2}
prod      = sticky {__tostring = prodprint}
= prod {10, 20}

prod = stickyformat {"(%s*%s)", 1, 2}
= prod {10, 20}                        --> (10*20)
= prod {10, {20, 30}}                  --> (10*{1=20, 2=30})
= prod {10, prod {20, 30}}             --> (10*(20*30))

-- Stuff for Category Theory:

name     = stickyformat {"%s", 1}
object   = stickyformat {"%s", "name"}
morphism = stickyformat {"(%s: %s -> %s)", "name", "src", "tgt"}
morphism = stickyformat { "%s",            "name"}
longfun  = lazyformat   {"(%s: %s -> %s)", "name", "src", "tgt"}

A = name {"A"}
B = name {"B"}
f = morphism {name="f", src=A, tgt=B}
= f
= f.src
= longfun(f)

L0       = stickyformat {"L(%s)", 1}
L1       = stickyformat {"L(%s)", 1}
R0       = stickyformat {"R(%s)", 1}
R1       = stickyformat {"R(%s)", 1}
sc       = stickyformat {"%s;%s", 1, 2}
eta      = stickyformat {"eta(%s)", 1}
eps      = stickyformat {"eps(%s)", 1}
flat     = stickyformat {"flat(%s)", 1}
sharp    = stickyformat {"sharp(%s)", 1}

UNR0     = function (f) return f[1] end
UNL0     = function (f) return f[1] end
SRC      = function (f) return f.src end
TGT      = function (f) return f.tgt end
FLAT     = function (g) return morphism {name=flat{g},  src=L0{SRC(g)}, tgt=UNR0(TGT(g))} end
SHARP    = function (f) return morphism {name=sharp{f}, src=UNL0(SRC(f)), tgt=R0{TGT(f)}} end
ETA      = function (A) return morphism {name=eta{A}, src=A, tgt=R0{L0{A}}} end
EPS      = function (B) return morphism {name=eps{B}, src=L0{R0{B}}, tgt=B} end

A = object {name="A"}
B = object {name="B"}
LA = L0 {A}
RB = R0 {B}
f = morphism {name="f", src=LA, tgt=B}
g = morphism {name="g", src=A, tgt=RB}
= TGT(g)
= UNR0(TGT(g))

gflat = FLAT(g)
fsharp = SHARP(f)

= longfun(FLAT(g))
= longfun(SHARP(FLAT(g)))
= longfun(ETA(A))
= longfun(EPS(B))

-- (find-854 "" "cheap-and-exp-adjs-2")




#####
#
# Rima
# 2010oct29
#
#####

# «rima»  (to ".rima")
# http://code.google.com/p/rima/
# http://code.google.com/p/rima/wiki/RoadMap
# http://rima.googlecode.com/files/rima-latest.tar.gz
# http://rima.incremental.co.nz/contents.html
# http://rima.incremental.co.nz/expressions.html
# http://www.incremental.co.nz/projects/lua.html
#*
rm -Rv ~/usrc/rima-0.04/
tar -C ~/usrc/ -xvzf \
  $S/http/rima.googlecode.com/files/rima-latest.tar.gz
cd     ~/usrc/rima-0.04/

#*
# (code-c-d "rima"     "~/usrc/rima-0.04/")
# (code-c-d "rimahtml" "~/usrc/rima-0.04/htmldocs/")
# (find-rimafile "")
# (find-rimahtmlfile "")
# (find-rimahtmlw3m "expressions.html")




#####
#
# Multiplication tables (for Violeta)
# 2010oct31
#
#####

# «mult-table»  (to ".mult-table")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
fmt = "%4d"
tabuada = function (nlines, ncols)
    if ncols==nil then ncols = nlines end
    for y=1,nlines do
      for x=1,ncols do
        printf(fmt, x*y)
      end
      print()
    end
  end
tab = tabuada
tab(10)
tab(16)
tab(40, 5)
tab(31)






#####
#
# LA.lua
# 2010dec18
#
#####

# «LA.lua»  (to ".LA.lua")
from	Doug Lua
to	lua-l@lists.lua.org
date	Sat, Dec 18, 2010 at 2:19 AM
subject	Re: point to plane projections and algebra

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rv   ~/usrc/lua-la/
mkdir    ~/usrc/lua-la/
unzip -d ~/usrc/lua-la/ $S/http/www.dkrogers.com/lua/LA.zip
cd       ~/usrc/lua-la/
lua51 LA_test.lua

# (code-c-d "luala" "~/usrc/lua-la/")
# (find-lualafile "LA.lua")
# (find-lualafile "LA_test.lua")
# (find-lualafile "")





#####
#
# Marc's oop.lua
# 2010dec28
#
#####

# «oop.lua»  (to ".oop.lua")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
PP(LUA_PATH)
PP(package.path)
package.path = package.path..";/tmp/?.lua"
require "shape"
-- (find-fline "/tmp/oop.lua")
-- (find-fline "/tmp/shape.lua")

PP(square_)
PP(s1)
PP(s2)
PP(getmetatable(s1))

-- (find-fline "/tmp/bank.lua")
require "bank"
PP(a)
PP(b)
PP(a_o)
PP(b_o)

gmt = getmetatable
smt = setmetatable
PP(a)
PP(gmt(a))
PP(gmt(a).__private)


* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
-- (find-fline "/tmp/oop.lua")
-- (find-fline "/tmp/foo.lua")
package.path = package.path..";/tmp/?.lua"
gmt = getmetatable
smt = setmetatable
require "foo"
PP(foo)
PP(foo_)


foo_ = { a = 10, p = \() print(this.a) end }

foo = class(foo_) 
-~-> foo = (\(t) => \(...) => instance(t, ...) end end)(foo_)
-~-> foo =       \(...) => instance(foo_, ...) end

f = foo()
-~-> f = (\(...) => instance(foo_, ...) end)()
-~-> f =            instance(foo_)
-~-> f = (\() local me = {__mt={}}
              prepare(me, "a", foo_.a)
              prepare(me, "p", foo_.p)
              => me) ()


instance = function(fields, ...)
  --
  local me = {}
  local mt = {}
  setmetatable(me, mt)
  -- Inheritance:
  if ( fields.super ) then
    for k,v in pairs(fields.super) do
      prepare(me, k, v)
    end
  end
  -- Construction:
  for k,v in pairs(fields) do
    prepare(me, k, v)
  end
  -- this isn't a constructor as such, more a post-construction initialiser
  if ( me.new ) then me.new(...) end
  return me
end


class = function(t,...) return function(...) return instance(t,...) end end




#####
#
# Closure reductions (e-mail sent to Marc Simpson)
# 2010dec29
#
#####

# «closure-reductions»  (to ".closure-reductions")
# (find-TH "__mt")

Hi Marc!
This is my favourite example for explaining closures:

  foo = function ()              -- foo returns two functions...
    local storage
    return
      function () return storage end,         -- a "getter",
      function (x) storage = x; return x end  -- and a "setter".
  end

  get1, set1 = foo()     -- get1 and set1 use a first "storage"
  get2, set2 = foo()     -- get2 and set2 use a second, different "storage"
  print(set1(22), get1())          --> 22 22
  print(set2(33), get1(), get2())  --> 33 22 33

Rewriting it with \, =>, and shorter var names, it becomes:

  foo = \ () local st
           => \ () => st end,
              \ (x) st = x; => x end
        end
  g1, s1 = foo()
  g2, s2 = foo()
  print(s1(22), g1())
  print(s2(33), g1(), g2()

Only yesterday I realized that we can distinguish different local
variables with same name but with different scopes - and that includes
the ones used in closures, of course - by writing their time of
creation as a subscript... so:

  foo = \() local st; => \() => st end, \(x) st = x; => x end end
  g1, s1 = foo()
    --~-> (\() local st;   => \() => st   end, \(x) st   = x; => x end end)()
    --~-> (\() local st_1; => \() => st_1 end, \(x) st_1 = x; => x end end)()
    --~->                     \() => st_1 end, \(x) st_1 = x; => x end
  g2, s2 = foo()
    --~-> (\() local st;   => \() => st   end, \(x) st   = x; => x end end)()
    --~-> (\() local st_2; => \() => st_2 end, \(x) st_2 = x; => x end end)()
    --~->                     \() => st_2 end, \(x) st_2 = x; => x end
  -- Now we have:
  -- g1 =                     \() => st_1 end                          
  -- s1 =                                      \(x) st_1 = x; => x end
  -- g2 =                     \() => st_2 end                          
  -- s2 =                                      \(x) st_2 = x; => x end
  print(s1(22), g1())
    --~-> print((\(x) st_1 = x; => x end)(22), (\() => st_1 end)())
    --~-> print(     (st_1 = 22;   22)       ,         st_1       )
  print(s2(33), g1(), g2()
    --~-> print((\(x) st_2 = x; => x end)(33), (\() => st_1 end)(),
    --                                         (\() => st_2 end)())
    --~-> print(     (st_2 = 33;   33)       ,         st_1       ,
    --                                                 st_2       )

Maybe this trick would be enough to display your classes and instances
- and the ones in chapter 16 of PiL - as static objects, maybe not...
Probably your trick to backup "this" and "priv" deserves another
shortand...

More soon!
  [[]], Eduardo




#####
#
# luatcc
# 2011jan04
#
#####

# «luatcc»  (to ".luatcc")
# http://luatcc.luaforge.net/
# http://www.gnu.org/software/lightning/
# http://bellard.org/tcc/tcc-doc.html#SEC10

# 2013mar14:
# http://en.wikipedia.org/wiki/Tiny_C_Compiler
# https://github.com/spc476/lua-conmanorg/blob/master/src/tcc.c
# https://github.com/spc476/lua-conmanorg/blob/master/lua/cc.lua
# https://github.com/spc476/LPeg-Parsers/blob/master/json.lua





#####
#
# libaoo - A library for audio output
# 2011jan16
#
#####

# «ao»  (to ".ao")
# (find-luarocks-links "ao" "-1.0.0" "-1")
# http://luarocks.org/repositories/rocks/index.html#ao

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/luarocks/bin/
./luarocks install  ao  |& tee oli-ao

# Error: Could not find expected file ao/ao.h for LIBAO -- you may
# have to install LIBAO in your system and/or set the LIBAO_DIR
# variable



#####
#
# vlists (and dracula)
# 2011feb27
#
#####

# «vlists»  (to ".vlists")
# http://lua-users.org/lists/lua-l/2011-02/msg01467.html
# http://lua-users.org/lists/lua-l/2011-02/msg01477.html
# (find-lua52manualw3m "#pdf-table.pack")




#####
#
# Environments
# 2011feb03
#
#####

# «environments»  (to ".environments")
# (find-luamanualw3m "#2.9" "Environments")
# (find-lua52manualw3m "#2.2" "Environments and the Global Environment")
# (find-lua52manualw3m "#3.2" "Variables")
# (find-lua52manualw3m "#3.2" "Variables" "_ENV.x")
# (find-lua52manualw3m "#3.3.3")
# (find-lua52manualw3m "#pdf-setmetatable")
# http://lua-users.org/lists/lua-l/2012-11/msg00401.html _ENV and HTML

* (eepitch-lua52)
* (eepitch-kill)
* (eepitch-lua52)
metacopy = function (T) return setmetatable({}, {__index=T}) end
do local _ENV = metacopy(_G)
   oldprint = print
   print = function (...) oldprint("=>", ...) end
   print("hello", "bye")
end
print("hello", "bye")
print(oldprint)








#####
#
# LuaJit
# 2011sep27
#
#####

# «luajit»  (to ".luajit")
# (find-angg ".emacs" "luajit")
# http://luajit.org/
# http://luajit.org/luajit.html
# http://luajit.org/download.html
# http://luajit.org/download/LuaJIT-2.0.2.tar.gz
# http://luajit.org/download/LuaJIT-2.0.0-beta8.tar.gz
# http://luajit.org/ext_ffi.html
# http://luajit.org/ext_ffi_tutorial.html
# http://luajit.org/ext_ffi_semantics.html#init_table
# <NotDeco> You can access structs with indexing, e.g: x =
#           ffi.new("struct foo", {a=22}) x.a = 9 print(x.a)
# (find-luajitfile "")
# (find-luajitfile "doc/")
# (find-luajitw3m "doc/install.html")
# (find-luajitw3m "doc/install.html" "If you've already embedded Lua")
# (find-luajitw3m "doc/ext_ffi_tutorial.html")
# http://lua-users.org/wiki/SimpleLuaApiExample

#*
rm -Rv ~/usrc/LuaJIT-2.0.2/
tar -C ~/usrc/ -xvzf \
  $S/http/luajit.org/download/LuaJIT-2.0.2.tar.gz
cd     ~/usrc/LuaJIT-2.0.2/

make  |& tee om

#*
# (find-fline "~/bin/" " luajit")
# (find-fline "~/usrc/LuaJIT-2.0.2/src/" " luajit")
rm -v ~/bin/luajit
ln -s ~/usrc/LuaJIT-2.0.2/src/luajit ~/bin/luajit

#*

* (eepitch-luajit)
* (eepitch-kill)
* (eepitch-luajit)
local ffi = require("ffi")
ffi = require("ffi")
ffi.cdef[[
  unsigned long compressBound(unsigned long sourceLen);
  int compress2(uint8_t *dest, unsigned long *destLen,
                const uint8_t *source, unsigned long sourceLen, int level);
  int uncompress(uint8_t *dest, unsigned long *destLen,
                 const uint8_t *source, unsigned long sourceLen);
]]
zlib = ffi.load(ffi.os == "Windows" and "zlib1" or "z")

compress = function (txt)
    local n = zlib.compressBound(#txt)
    local buf = ffi.new("uint8_t[?]", n)
    local buflen = ffi.new("unsigned long[1]", n)
    local res = zlib.compress2(buf, buflen, txt, #txt, 9)
    assert(res == 0)
    return ffi.string(buf, buflen[0])
  end

uncompress = function (comp, n)
    local buf = ffi.new("uint8_t[?]", n)
    local buflen = ffi.new("unsigned long[1]", n)
    local res = zlib.uncompress(buf, buflen, comp, #comp)
    assert(res == 0)
    return ffi.string(buf, buflen[0])
  end

-- Simple test code.
txt = string.rep("abcd", 1000)
print("Uncompressed size: ", #txt)
c = compress(txt)
print("Compressed size: ", #c)
txt2 = uncompress(c, #txt)
assert(txt2 == txt)


# (find-luajitfile "src/lib_ffi.c")
# (find-luajitfile "src/luajit")
# (find-libcnode "Numeric Input Conversions")
# (find-libcnode "Formatted Input Functions" "sscanf")

* (eepitch-luajit)
* (eepitch-kill)
* (eepitch-luajit)
ffi = require "ffi"
ffi.cdef [[
  int printf(const char *fmt, ...);
]]
PP(ffi.C.printf("Hello\n"))
PP(ffi.C.printf("Number: %d\n", 100))   -- doesn't work
PP(ffi.C.printf("Number: %f\n", 100))   -- works






#####
#
# luadist
# 2011oct26
#
#####

# «luadist»  (to ".luadist")
# http://www.luadist.org/
# https://github.com/LuaDist/Repository

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)

rm -Rv ~/usrc/luadist/
mkdir  ~/usrc/luadist/
cd     ~/usrc/luadist/
# tar -xvzf ~/tmp/luadist-git.tgz
git clone git://github.com/LuaDist/Repository.git
cd Repository
git submodule update --init bootstrap
cd bootstrap
git submodule update --init
cd ..

cd     ~/usrc/luadist/
tar -cvzf ~/tmp/luadist-git.tgz *
# (find-fline "~/tmp/" "luadist.tgz")

# (find-fline "~/usrc/luadist/")


# (find-man "1 git-submodule")


./install bootstrap


rm -Rv ~/usrc/lua-inspect/
cd     ~/usrc/
git clone http://github.com/davidm/lua-inspect.git
cd     ~/usrc/lua-inspect/




#####
#
# package.path
# 2011nov04
#
#####

# «package.path»  (to ".package.path")
# (find-lua51manualw3m "#pdf-package.path")
# (find-lua51file "")
# (find-lua51grep "grep -nH -e path $(cat .files.ch)")
# (find-lua51grep "grep -nH -e LUA_PATH_DEFAULT $(cat .files.ch)")
# (find-lua51srcfile "loadlib.c" "\"path\", LUA_PATH")
# (find-lua51srcfile "luaconf.h" "#define LUA_PATH_DEFAULT")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
= package.path

--> ./?.lua;/usr/local/share/lua/5.1/?.lua;/usr/local/share/lua/5.1/?/init.lua;/usr/local/lib/lua/5.1/?.lua;/usr/local/lib/lua/5.1/?/init.lua

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
lua5.1
= package.path
--> ./?.lua;/usr/local/share/lua/5.1/?.lua;/usr/local/share/lua/5.1/?/init.lua;/usr/local/lib/lua/5.1/?.lua;/usr/local/lib/lua/5.1/?/init.lua;/usr/share/lua/5.1/?.lua;/usr/share/lua/5.1/?/init.lua





#####
#
# gsl-shell-2.0-beta1
# 2011nov14
#
#####

# «gsl-shell»  (to ".gsl-shell")
# (find-es "math" "gsl")
# (find-es "python" "python-sphinx")
# http://download.savannah.gnu.org/releases/gsl-shell/gsl-shell-2.0-beta1.tar.gz
# (find-zsh "availabledebs | sort | grep gsl")
# (find-zsh "installeddebs | sort | grep gsl")
#*
rm -Rv ~/usrc/gsl-shell-2.0-beta1/
tar -C ~/usrc/ -xvzf \
  $S/http/download.savannah.gnu.org/releases/gsl-shell/gsl-shell-2.0-beta1.tar.gz
cd     ~/usrc/gsl-shell-2.0-beta1/

make   |& tee om

#*
apti gsl-doc-info gsl-doc-pdf gsl-ref-html libgsl0-dev
apti libagg-dev
apti python-sphinx
# (find-status   "libagg-dev")
# (find-vldifile "libagg-dev.list")
# (find-udfile   "libagg-dev/")

# (code-c-d "gslshell" "~/usrc/gsl-shell-2.0-beta1/")
# (find-gslshellfile "")
# (find-gslshellfile "Makefile")
# (find-gslshellfile "om")
# (find-gslshellfile "luagdb.txt")
# (find-gslshellsh "find .* * | sort")
# (find-gslshellsh "find .* * -type f | sort")
# (find-gslshellfile "demos/")
# (find-gslshellfile "doc/gsl-shell-index/")
# (find-gslshellfile "doc/gsl-shell-index/older-news.rst")
# (find-gslshellfile "doc/gsl-shell-index/older-news.rst" "JavaScript/Lua")
# (find-gslshellfile "doc/user-manual/")
# (find-gslshellfile "doc/user-manual/Makefile")
# (find-gslshellfile "examples/")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/gsl-shell-2.0-beta1/
./gsl-shell
  dofile "examples/3d.lua"
  demo1()
  os.exit()

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/gsl-shell-2.0-beta1/
./gsl-shell
  -- ODE = {}
  -- cODE = {}
  Ode = dofile "demos/ode.lua"
  -- (find-gslshellfile "demos/")
  -- (find-gslshellfile "demos/ode.lua")
  Ode
  Ode[2]
  Ode[2][1]
  Ode[2][1].f
  Ode[2][1].f()
  Ode[2][2].f()
  Ode[2][3].f()
  os.exit()

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/gsl-shell-2.0-beta1/
cd ~/usrc/gsl-shell-2.0-beta1/doc/user-manual/
make text  |& tee omt

# 2013apr23:
# http://www.nongnu.org/gsl-shell/doc/gdt.html
# http://www.nongnu.org/gsl-shell/doc/
# http://download.savannah.gnu.org/releases/gsl-shell/
# https://github.com/franko/gsl-shell







#####
#
# lua-codegen
# 2011nov14
#
#####

# «lua-codegen»  (to ".lua-codegen")
# http://fperrad.github.com/lua-CodeGen/
# http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf
# http://www.cs.usfca.edu/~parrt/papers/ST.pdf




#####
#
# JNLua (Java Native Lua)
# 2012jan30
#
#####

# «jnlua»  (to ".jnlua")
# http://code.google.com/p/jnlua/
# http://jnlua.googlecode.com/files/jnlua-1.0.2-src.zip




#####
#
# goto
# 2012feb01
#
#####

# «goto»  (to ".goto")
# http://lua-users.org/wiki/GotoStatement

* (eepitch-lua52)
* (eepitch-kill)
* (eepitch-lua52)
for i=1,10 do
  if i%3 == 0 then goto continue end
  local v = i*2
  print(v)
  ::continue::
end




#####
#
# A variant of lua_getstack
# 2012feb22
#
#####

# «lua_getstack»  (to ".lua_getstack")
# My message about getstack:
# http://article.gmane.org/gmane.comp.lang.lua.general/88610
# http://lua-users.org/lists/lua-l/2012-02/msg00767.html



#####
#
# xctrl
# 2012mar11
#
#####

# «xctrl»  (to ".xctrl")
# (find-es "x" "wmctrl")
# http://lua-users.org/lists/lua-l/2010-10/msg00698.html xctrl
# http://luarocks.org/repositories/rocks/index.html#xctrl



#####
#
# Leg - a parser for Lua written in Lpeg
# 2012apr13
#
#####

# «leg»  (to ".leg")
# http://lua-users.org/wiki/LpegRecipes
# http://leg.luaforge.net/
# http://leg.luaforge.net/index.html
# http://leg.luaforge.net/grammar.html
# http://leg.luaforge.net/parser.html
# http://leg.luaforge.net/scanner.html
# http://leg.luaforge.net/doc.css
# http://files.luaforge.net/releases/leg/leg/0.1.2/leg-0.1.2.tar.gz
#*
rm -Rv ~/usrc/leg/
tar -C ~/usrc/ -xvzf \
  $S/http/files.luaforge.net/releases/leg/leg/0.1.2/leg-0.1.2.tar.gz
cd     ~/usrc/leg/

cd     ~/usrc/leg/tests/
ln -s  ../src leg
# cp -v  ~/usrc/lpeg-0.7/lpeg.so .
  cp -v  ~/usrc/lpeg-0.8.1/lpeg.so .

cd     ~/usrc/leg/
make test    |& tee omt

#*
# (code-c-d "leg" "~/usrc/leg/")
# (find-legfile "")
# (find-legfile "Makefile")
# (find-legfile "Makefile" "test:")
# (find-legfile "src/")
# (find-legfile "src/parser.lua" "-- EXPRESSIONS")
# (find-legfile "src/parser.lua" ", _SimpleExp")
# (find-legfile "src/parser.lua" ", BinOp")
# (find-legfile "tests/")
# (find-legfile "tests/test.lua")
# (find-legfile "tests/test_scanner.lua")
# (find-legfile "omt")
# (find-fline "~/usrc/lpeg-0.9/lpeg.so")
# make LUA_LIB=$PWD/lib leg install test   |& tee om

# (find-lua51manualw3m "#pdf-require")
# (find-lua51manualw3m "#pdf-package.path")
# (find-lua51manualw3m "#pdf-package.cpath")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
ee
cd     ~/usrc/leg/
make test

laf leg
LUA_PATH=$PWD \
  make LUA_LIB=$PWD/lib  test




#####
#
# NaN and infinity
# 2012apr13
#
#####

# «nan-and-inf»  (to ".nan-and-inf")
# Not described in the manual?

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
nan = 0/0
inf = 1/0
print(nan, inf)




#####
#
# ZeroBrane
# 2012oct13
#
#####

# «zerobrane»  (to ".zerobrane")
# http://studio.zerobrane.com/
# https://github.com/pkulchenko/zerobranestudio/
# http://notebook.kulchenko.com/
# http://bowerhaus.eu/blog/files/live_coding.html
# (find-google-links "lua for android")
#   http://www.google.com/search?q=lua+for+android
#   http://code.google.com/p/android-scripting/

# 2013nov01:
# https://download.zerobrane.com/ZeroBraneStudioEduPack-0.39-linux.sh
cd             $S/https/download.zerobrane.com/

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# (find-fline "$S/https/download.zerobrane.com/")
cd             $S/https/download.zerobrane.com/
chmod 755 ./ZeroBraneStudioEduPack-0.39-linux.sh
./ZeroBraneStudioEduPack-0.39-linux.sh --help
./ZeroBraneStudioEduPack-0.39-linux.sh --info
./ZeroBraneStudioEduPack-0.39-linux.sh --target ~/usrc/zb/

# (find-fline "~/usrc/zb/")
# (find-fline "/opt/zbstudio/")
(code-c-d "zb" "/opt/zbstudio/")
;; (find-zbfile "")
;; (find-zbsh "find * | sort")
;; (find-zbsh "find * | sort" "src/editor")
;; (find-zbfile "myprograms/turtle-samples/")
;; (find-zbfile "src/editor/")


# 2013mar14:

# https://download.zerobrane.com/ZeroBraneStudio-0.35-linux-i386.sh
# https://github.com/megastep/makeself

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# (find-fline "$S/https/download.zerobrane.com/")
cd             $S/https/download.zerobrane.com/
./ZeroBraneStudio-0.35-linux-i386.sh --help
./ZeroBraneStudio-0.35-linux-i386.sh --info
./ZeroBraneStudio-0.35-linux-i386.sh --lsm
./ZeroBraneStudio-0.35-linux-i386.sh --list
./ZeroBraneStudio-0.35-linux-i386.sh --noexec --keep

# (find-fline "$S/https/download.zerobrane.com/debs/")
cd             $S/https/download.zerobrane.com/debs/
sudo dpkg -i wxlua*

# (find-zsh "dmissing add-apt-repository")
http://stackoverflow.com/questions/13018626/add-apt-repository-not-found

apti libwxbase2.8-0


# 2013mar14, a possible bug fix:

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# (find-fline "~/usrc/zerobrane/")
rm -Rfv ~/usrc/zerobrane/
mkdir   ~/usrc/zerobrane/
cd      ~/usrc/zerobrane/
git clone git://github.com/pkulchenko/ZeroBraneStudio.git zbs

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# (find-fline "~/usrc/zerobrane/")
# (find-fline "~/usrc/zerobrane/zbs/")
cd             ~/usrc/zerobrane/
cd             ~/usrc/zerobrane/zbs/
git checkout wxwidgets
./zbstudio.sh




# Old:

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv /tmp/zb/
mkdir   /tmp/zb/
cd      /tmp/zb/
git clone https://github.com/pkulchenko/zerobranestudio/

/tmp/zb/


Hi Tom,

> The ZeroBrane site has no link to download the Linux version.

You can get the latest version from the repository and run "bash
./zbstudio.sh" (or use CMake build file in the build/ directory).
Running zbstudio.sh the first time will install the dependencies and
then run the IDE (tested on Ubuntu and Mint versions of Linux, but
should work anywhere with deb packaging support). I'll have a packaged
shell archive when the next version (0.33) is out.

I've described how this is done in my debugger (MobDebug:
https://github.com/pkulchenko/MobDebug) in this SO answer:
http://stackoverflow.com/a/11026978/1442917. It also integrates with
an IDE (in the signature), so you can see how this type of debugging
can work.

Paul.

ZeroBrane Studio - slick Lua IDE and debugger for Windows, OSX, and
Linux - http://studio.zerobrane.com/

https://github.com/pkulchenko/ZeroBraneStudio/blob/master/CHANGELOG.md







#####
#
# Printable functions
# 2012nov07
#
#####

# «printable-functions» (to ".printable-functions")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
ee_dofile "~/dednat5/eoo.lua"   -- (find-dn5 "eoo.lua")

Callable = Class {
  type    = "Callable",
  __call  = function (o, ...) return o.f(...); end,
  __tostring = function (o) return o.name; end,
  __index = {
  },
}

F = Callable {f=PP, name="(PP)"}
F(1, 2, 3)
= F

nf0 = function (name, f)
    return Callable {name=name, f=f}
  end

f = nf0 ([[ a,b . a*b ]], function (a, b) return a*b end)
f = nf0 ([[(a,b: a*b)]], function (a, b) return a*b end)
= f(2,3)
= f

lambda = function (str)
    local vars,rest = str:match "^ *([%w_,]*)[ .:]*(.-) *$"
    local body = rest:gsub("=>", " return ")
    body = "return function ("..vars..")\n"..body.."\nend"
    local name = "("..vars..": "..rest..")"
    -- PP(vars, rest)
    -- PP(name)
    -- PP(body)
    local f = assert(loadstring(body))()
    return Callable {name=name, f=f}
  end

f = lambda [[ a,b: =>a*b ]]
= f
= f(2,3)



#####
#
# Named functions
# 2012nov17
#
#####

# «NamedFunction» (to ".NamedFunction")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
ee_dofile "~/dednat5/eoo.lua"  -- (find-dn5 "eoo.lua")
NamedFunction = Class {
  type    = "NamedFunction",
  __tostring = function (o) return o.name end,
  __call     = function (o, ...) return o.f(...) end,
  __index = {
  },
}
lambda = function (str)
    local vars,rest = str:match "^ *([%w_,]*)[ .:]*(.-) *$"
    local body = rest:gsub("=>", " return ")
    local code = "return function ("..vars..")\n"..body.."\nend"
    local name = "("..vars..": "..rest..")"
    local f = assert(loadstring(code))()
    return NamedFunction {name=name, f=f}
  end


add = NamedFunction {
  name="(a,b: => a+b)",
  f = function (a, b) return a+b end,
}
= add(2, 3)
= add


mul = lambda "a,b: => a*b"
= mul(2,3)
= mul


* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
= lambda "a,b => a*b"
= lambda "a,b => a*b" .code
= lambda "a,b => a*b" (2, 3)




#####
#
# string.format
# 2012dec14
#
#####

# «string.format» (to ".string.format")
# (find-luamanualw3m "#pdf-string.format")
# (find-libcnode "Formatted Output")
# (find-libcnode "Floating-Point Conversions")
# (find-libcnode "Floating-Point Conversions" "%13.4f")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
for _,x in ipairs {0, 0.5, 1, -1, 100, 1000, 10000, 12345, 100000, 123456,} do
  printf("|%6.2f|\n", x)
end





#####
#
# histogram
# 2012dec14
#
#####

# «histogram» (to ".histogram")
# (find-angg "LUA/2013.2-ES-diags")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
letters = "ABCDEFGHIJ"
L = function (n) return letters:sub(n,n) end
V = {3, 3, 5, 5, 6, 6, 7, 7, 9, 9}
V = {3, 3, 3, 3, 4, 4, 4, 6, 6, 9}
histo = {
  addpoint = function (histo, x, name)
      if not x then error() end
      histo.minx = histo.minx and min(histo.minx, x) or x
      histo.maxx = histo.maxx and max(histo.maxx, x) or x
      histo[x] = histo[x] or {}
      table.insert(histo[x], name)
      local y = #(histo[x])
      histo.maxy = histo.maxy and max(histo.maxy, y) or y
    end,
  point = function (histo, x, y)
      if y==0 then return format("%4.1f ", x/5) end
      return (histo[x] or {})[y] or "     "
    end,
  line = function (histo, y)
      local T = {}
      for x=histo.minx, histo.maxx do
        table.insert(T, histo:point(x, y))
      end
      return table.concat(T, " ")
    end,
}
n = 0
for a=1,10 do
  for b=a+1,10 do
    for c=b+1,10 do
      for d=c+1,10 do
        for e=d+1,10 do
          name = L(a)..L(b)..L(c)..L(d)..L(e)
          tot  = V[a]+V[b]+V[c]+V[d]+V[e]
          n = n+1
          -- histo[tot] = histo[tot] or {}
          -- table.insert(histo[tot], name)
          histo:addpoint(tot, name)
          print(n, name)
        end
      end
    end
  end
end

PP(histo)

for tot=histo.minx,histo.maxx do
  print(tot, table.concat(histo[tot], " "))
end

for tot=histo.minx,histo.maxx do
  print(tot/5, #(histo[tot]))
end

for y=histo.maxy,0,-1 do
  print(histo:line(y))
end






#####
#
# (Many) histograms
# 2013jun07
#
#####

# «histograms» (to ".histograms")

* (eepitch-gab)
* (eepitch-kill)
* (eepitch-gab)
-- (find-gab "gab.lua")
-- (find-gabfile "gab.lua" "stringtorect =")
Rect.__index.setxy = function (rect, x, y, str)
    local str0 = rect[y] or ""
    local minw = x+#str
    if #str0 < minw then str0 = str0..string.rep(" ", minw-#str0) end
    local strl = str0:sub(1, x)
    local strr = str0:sub(x+1+#str)
    rect:set(y, strl..str..strr)
    return rect
  end
Rect.__index.putbox = function (rect, x)
    local x0, y0 = x*4, rect.heights[x]*-2+1
    rect:setxy(x0+1, y0-2,  "___")
    rect:setxy(x0,   y0-1, "|   |")
    rect:setxy(x0,   y0,   "|___|")
    rect.heights[x] = rect.heights[x]+1
  end
histo_ = function ()
    local h = stringtorect(
      "_____________________________________________\n"..
      "  0   1   2   3   4   5   6   7   8   9   10")
    h.heights = {[0]=0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    return h
  end
histo = function (str)
    local h = histo_()
    for c in str:gmatch"." do
      h:putbox(0 + c:gsub("a","10"))
    end
    return h
  end

h = histo_()
h:putbox(1)
h:putbox(1)
= h

= histo "3355a"
= "a) " .. histo "3355a"

histos = function (str)
    print(str)
    print(str:len())
    for label, values in str:gmatch("(%S+) (%S+)") do
      print(label.."  "..histo(values))
      print()
    end
  end

histos [[ a) 123   b) 135  c) 2235555788  d) 113355
          e) 144   f) 114444  g) 147  h) 44556677
          i) 2334445555  j) 6778889999  k) 4444555667 l) 1111333557
          m) 2223334449  n) 33577  o) 45556   p) 34556678
]]






#####
#
# 64-bit integers
# 2012nov13
#
#####

# «64-bit-integers» (to ".64-bit-integers")
# From Shmuel Zeigerman, lua-l, 2012nov13:
# http://farmanager.com/svn/trunk/plugins/luamacro/luafar/bit64.c





#####
#
# penlight (from rocks)
# 2014oct07
#
#####

# «penlight» (to ".penlight")
# (find-luarocks-links "penlight" "1.3.1" "-1" "penlight")
# (find-sh "unzip -l ~/usrc/luarocks/bin/penlight-1.3.1-1.src.rock")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# (find-fline "~/usrc/penlight/")
rm -Rv ~/usrc/penlight/
mkdir  ~/usrc/penlight/
cd     ~/usrc/penlight/
unzip ~/usrc/luarocks/bin/penlight-1.3.1-1.src.rock




#####
#
# penlight's pl.pretty
# 2014oct07
#
#####

# «pl.pretty» (to ".pl.pretty")
# (find-penlightfile "")
# (find-penlightfile "examples/test-pretty.lua")
# (find-penlightgrep "grep -nH -e pretty doc/manual/*")
# (find-penlightfile "lua/pl/pretty.lua")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
userocks()
pretty = require 'pl.pretty'
pp = function (o) print(pretty.write(o)) end

tb = {
    'one','two','three',{1,2,3},
    alpha=1,beta=2,gamma=3,['&']=true,[0]=false,
    _fred = {true,true},
    s = [[
hello dolly
you're so fine
]]
}
pp(tb)

# «pl.wrap» (to ".pl.wrap")
# «pl.text.wrap» (to ".pl.text.wrap")
# (find-penlightfile "doc/manual/03-strings.md" "`wrap`")
# (find-penlightgrep "grep -nH -e wrap lua/pl/*.lua")
# (find-penlightfile "lua/pl/text.lua" "text.wrap")



#####
#
# Penlight from Git
# 2014oct23
#
#####

# «penlight-git» (to ".penlight-git")
# (find-git-links "https://github.com/stevedonovan/Penlight" "penlightgit")
# (code-c-d "penlightgit" "~/usrc/Penlight/")
# (find-penlightgitfile "")
# (find-penlightgitfile "lua/pl/pretty.lua")



#####
#
# A fix for pl.write
# 2014oct23
#
#####

# «pl.pretty-fix» (to ".pl.pretty-fix")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# (find-angg ".zshrc" "strace")
strace-to /tmp/s lua5.1
userocks()
pretty = require 'pl.pretty'
= pretty.write {20, 30, 40}
= pretty.write {20, 30, 40, "Hello\nworld"}
longquote = function (str) return '[[\n'..str..']]' end
= pretty.write {20, 30, 40, "Hello\nworld"}
os.exit()

# (find-fline "/tmp/s")
# (find-sh "grep '= 3' /tmp/s")
# (find-luarocksfile "share/lua/5.1/pl/pretty.lua")
# (find-luarocksfile "share/lua/5.1/pl/pretty.lua" "[[")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
userocks()
pretty = require 'pl.pretty'

-- longquote = function (str) return '[[\n'..str..']]' end
longquote = function (str)
    local T = {}
    local f = function (eqs) T[#eqs+1] = 1; print(#eqs) end
    if str:gsub("%](=*)", f) then
      local eqs = string.rep("=", #T)
      return '['..eqs..'[\n'..str..']'..eqs..']'
    end
    return '[[\n'..str..']]'
  end

badstr = "Hello\nworld].]=.]==="
= pretty.write {20, 30, 40, badstr}
= pretty.write {20, 30, 40, "Hello\nworld"}
= pretty.write {20, 30, 40, "Hello\nworld]"}
= pretty.write {20, 30, 40, "Hello\nworld]]"}
= pretty.write {20, 30, 40, "Hello\nworld]==]"}






#####
#
# Penlight
# 2012dec27
#
#####

# «penlight-old» (to ".penlight-old")
# (find-status   "luadoc")
# (find-vldifile "luadoc.list")
# (find-udfile   "luadoc/")

# (find-man "1 luadoc")
# (find-fline "/usr/bin/luadoc")

rm -Rfv ~/usrc/PenLight/
cd      ~/usrc/ && \
  git clone https://github.com/stevedonovan/Penlight
cd      ~/usrc/ && tar -cvzf ~/tmp/PenLight.tgz Penlight/

rm -Rfv ~/usrc/LDoc/
cd      ~/usrc/ && \
  git clone https://github.com/stevedonovan/LDoc
cd      ~/usrc/ && tar -cvzf ~/tmp/LDoc.tgz LDoc/

rm -Rfv ~/usrc/LuaMacro/
cd      ~/usrc/ && \
  git clone https://github.com/stevedonovan/LuaMacro
cd      ~/usrc/ && tar -cvzf ~/tmp/LuaMacro.tgz LuaMacro/


http://lua-users.org/wiki/SlightlyLessSimpleLuaPreprocessor
https://github.com/stevedonovan/Penlight/blob/master/lua/pl/template.lua
http://penlight.luaforge.net/FAQ/

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)

#*
# (find-fline "~/tmp/LuaMacro.tgz")
# (code-c-d "luamacro" "~/usrc/LuaMacro/")
# (code-c-d "ldoc" "~/usrc/LDoc/")
# (find-ldocfile "")


# (find-luamacrofile "")
# (find-luamacrofile "readme.txt")
# (find-luamacrofile "luam.lua")

rm -Rfv ~/usrc/LuaMacro/
tar -C  ~/usrc/ \
  -xvzf ~/tmp/LuaMacro.tgz
cd      ~/usrc/LuaMacro/
cp -v $S/http/www.frykholm.se/files/markdown.lua .
pandoc readme.md -o readme.txt

# (find-es "lua5" "markdown.lua")


http://en.wikipedia.org/wiki/Markdown
# (find-status   "pandoc")
# (find-vldifile "pandoc.list")
# (find-udfile   "pandoc/")
# (find-udfile   "pandoc/README.gz")




#####
#
# Microlight
# 2012dec27
#
#####

# «microlight» (to ".microlight")
# https://github.com/stevedonovan/Microlight
# http://stevedonovan.github.com/files/microlight-1.1.zip
# http://stevedonovan.github.com/microlight/
# https://github.com/stevedonovan/Microlight/tags




#####
#
# lua-repl
# 2012dec27
#
#####

# «lua-repl» (to ".lua-repl")
# https://github.com/downloads/hoelzro/lua-repl/lua-repl-0.3.tar.gz
#*
rm -Rv ~/usrc/lua-repl-0.3/
tar -C ~/usrc/ -xvzf \
  $S/https/github.com/downloads/hoelzro/lua-repl/lua-repl-0.3.tar.gz
cd     ~/usrc/lua-repl-0.3/

#*
# (code-c-d "luarepl" "~/usrc/lua-repl-0.3/")
# (find-luareplfile "")
# (find-luareplsh "find * -type f | sort")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/lua-repl-0.3/
lua51 rep.lua
laf
laf repl/

cd ~/usrc/lua-repl-0.3/repl/
lua51 ../rep.lua

# (find-luarocks-links "luarepl" "0.3" "-1" "luarepl")
# (find-luarocksfile "share/lua/5.1/repl/")
# (find-fline "~/usrc/luarocks/bin/")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
~/usrc/luarocks/bin/rep.lua
2+3
2+
  3
print(2+
        3)
= 2+3

# http://repl.it/languages/Lua




#####
#
# luarepl as a rock
# 2014aug29
#
#####

# «lua-repl-rock» (to ".lua-repl-rock")
# (find-luarocksrocksfile "luarepl/0.4-1/")
# (find-luarocks-links "luarepl" "{ver}" "{sub}" "luarepl")
# (find-luarocks-links "luarepl" "0.4" "-1" "luarepl")
# https://github.com/hoelzro/lua-repl/archive/0.5.tar.gz

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/luarocks/bin/
./luarocks download luarepl
./luarocks build    luarepl  |& tee olb-luarepl
./luarocks install  luarepl  |& tee oli-luarepl
# (find-luarocksbinfile "")
# (find-luarocksbinfile "olb-luarepl")
# (find-luarocksbinfile "oli-luarepl")
# (find-luarocksbinfile "luarepl-0.4-1.src.rock")
# (find-luarocksbinfile "rep.lua")
# (find-luarocksrocksfile "luarepl/0.4-1/")
# (find-luarocksrocksfile "")
# (find-luarocksrockssh "find luarepl | sort")
# (find-luarocksfile "")
# (find-luarockssh "find * | grep repl")
# (find-luarocksfile "share/lua/5.1/repl/")

unzip -l ~/usrc/luarocks/bin/luarepl-0.4-1.src.rock
unzip -p ~/usrc/luarocks/bin/luarepl-0.4-1.src.rock 0.4.tar.gz \
  | tar -tvzf -
rm -Rfv ~/usrc/lua-repl-0.4/
unzip -p ~/usrc/luarocks/bin/luarepl-0.4-1.src.rock 0.4.tar.gz \
  | tar -C ~/usrc/ -xvzf -
cd     ~/usrc/lua-repl-0.4/

;; (find-angg ".emacs" "luarocks")
;; (find-luarocks-links "luarepl" "0.4" "-1")
;; (find-luareplfile "")
(code-c-d "luarepl" "~/usrc/lua-repl-0.4/")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
-- userocks()
require "repl"
require "rep"
= package.path

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
lua5.1
= package.path



#####
#
# lua-repl-0.5
# 2015jan11
#
#####

# «lua-repl-0.5» (to ".lua-repl-0.5")
# https://github.com/hoelzro/lua-repl/archive/0.5.tar.gz

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rv ~/usrc/lua-repl-0.5/
tar -C ~/usrc/ -xvzf \
  /home/edrx/snarf/https/github.com/hoelzro/lua-repl/archive/0.5.tar.gz
cd     ~/usrc/lua-repl-0.5/

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
repldir = ee_expand "~/usrc/lua-repl-0.5/"
package.path = repldir.."?/init.lua;"..package.path
package.path = repldir.."?.lua;"     ..package.path
repl = require 'repl'
PP(repl)
PP(repl._plugins)
repl:loadplugin 'history'
PP(repl._plugins)

sync = require 'repl.sync'
PP(sync)
repl:run()
sync:run()

function sync:showprompt() print ">>>" end
function sync:lines() return io.stdin:lines() end
function sync:displayerror(err) print(err) end
function sync:displayresults(results)
    if results.n == 0 then return end
    print(unpack(results, 1, results.n))
  end

sync:run()
  print(2+3)
  2+3




* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
repldir      = ee_expand "~/usrc/lua-repl-0.5/"
package.path = repldir.."?/init.lua;"..package.path
package.path = repldir.."?.lua;"     ..package.path
repl         = require "repl"
sync         = require "repl.sync"
function sync:showprompt() print ">>>" end
function sync:showprompt() io.write ">>> " end
function sync:showprompt(n) print(n); io.write ">>> " end
function sync:showprompt(p) io.write(p == ">" and ">>> " or ">>>> ") end
function sync:lines() return io.stdin:lines() end
function sync:displayerror(err) print(err) end
function sync:displayresults(results)
    if results.n == 0 then return end
    print(unpack(results, 1, results.n))
  end
sync:run()
print(2+3)
print(2+
  3+
  4)
= 2+3



# (find-luareplgrep "grep -nRH -e showprompt *")
# (find-luareplgrep "grep -nRH -e :lines *")
# (find-luareplgrep "grep -nRH -e :displayerror *")
# (find-luareplgrep "grep -nRH -e :displayresult *")


# (code-c-d "luarepl" "~/usrc/lua-repl-0.5/")
# (find-luareplfile "")
# (find-luareplfile "README.md")
# (find-luareplfile "rep.lua")
# (find-luareplfile "repl/")
# (find-luareplgrep "grep -nRH -e pretty *")
# (find-luareplfile "t/plugin-basic-tests.lua")
# (find-luareplfile "rep.lua" "repl:run()")
# (find-luareplgrep "grep -nwrH -e run *")
# (find-luareplgrep "grep -nwrH -e loadplugin *")
# (find-luareplgrep "grep -nwrH -e hasplugin *")
# (find-luareplgrep "grep -nwrH -e sync *")
# (find-luareplfile "repl/init.lua" "function repl:loadplugin(chunk)")
# (find-luareplfile "repl/sync.lua")




#####
#
# lua-repl-0.8
# 2015aug23
#
#####

# «lua-repl-0.8» (to ".lua-repl-0.8")
# (find-angg ".emacs" "lua-repl")
# (find-angg "LUA/lua50init.lua" "loadluarepl")
# https://mail.google.com/mail/ca/u/0/#inbox/14f5bba4abb13d01
# https://github.com/hoelzro/lua-repl/blob/0.8/README.md#removal-of-default-plugins-in-08
# https://github.com/hoelzro/lua-repl/archive/0.8.tar.gz
#*
rm -Rv ~/usrc/lua-repl-0.8/
tar -C ~/usrc/ -xvzf \
  /home/edrx/snarf/https/github.com/hoelzro/lua-repl/archive/0.8.tar.gz
cd     ~/usrc/lua-repl-0.8/

#*
# (code-c-d "luarepl" "~/usrc/lua-repl-0.8/")
# (find-luareplfile "")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
repldir      = ee_expand "~/usrc/lua-repl-0.8/"
package.path = repldir.."?/init.lua;"..package.path
package.path = repldir.."?.lua;"     ..package.path
repl         = require "repl"
sync         = require "repl.sync"
function sync:showprompt() print ">>>" end
function sync:showprompt() io.write ">>> " end
function sync:showprompt(n) print(n); io.write ">>> " end
function sync:showprompt(p) io.write(p == ">" and ">>> " or ">>>> ") end
function sync:lines() return io.stdin:lines() end
function sync:displayerror(err) print(err) end
function sync:displayresults(results)
    if results.n == 0 then return end
    print(unpack(results, 1, results.n))
  end
sync:run()
print(2+3)
print(2+
  3+
  4)
= 2+3       --> [string "REPL"]:1: unexpected symbol near '='
2+3         --> [string "REPL"]:1: unexpected symbol near '2'

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
loadluarepl()
sync:run()
print(mytabletostring(sync))
print(mytabletostring(repl))
print(repl:name())



#####
#
# luarepl for lualatex
# 2016sep18
#
#####

# «lua-repl-2016» (to ".lua-repl-2016")
# «luarepl-2016»  (to ".luarepl-2016")
# https://github.com/hoelzro/lua-repl/

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv ~/usrc/lua-repl/
cd      ~/usrc/
git clone --depth 1 https://github.com/hoelzro/lua-repl/
cd       ~/usrc/lua-repl/
git pull --depth 1
# git pull
# (find-fline "~/usrc/")
# (find-fline "~/usrc/lua-repl/")
# (find-fline "~/usrc/lua-repl/repl/")
# (find-fline "~/usrc/lua-repl-0.8/")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd      ~/usrc/lua-repl/repl/
tar -cvzf /tmp/lua-repl-repl.tgz *

cd      ~/usrc/lua-repl/
tar -cvzf /tmp/lua-repl-repl.tgz rep.lua repl/*

rm -Rv ~/LATEX/lua-repl/
mkdir  ~/LATEX/lua-repl/
tar -C ~/LATEX/lua-repl/ -xvzf /tmp/lua-repl-repl.tgz
# (find-fline "~/LATEX/lua-repl/")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/LATEX/
lua5.1
  loadluarepl("lua-repl/")
  sync:run()
  os.exit()
lua5.2
  loadluarepl()
  sync:run()
  os.exit()

export REPL=0
lualatex -record 2016-2-GA-algebra.tex

export REPL=1
lualatex -record 2016-2-GA-algebra.tex
  os.exit()

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/LATEX/
REPL=0 lualatex -record 2016-2-GA-algebra.tex
REPL=1 lualatex -record 2016-2-GA-algebra.tex
  os.exit()



# (find-LATEX "2016-2-GA-algebra.tex" "repl")
# loadluarepl("~/LATEX/lua-repl/"); 

# (code-c-d "luarepl" "~/usrc/lua-repl/")
# (find-luareplfile "")
# (find-luareplfile "RELEASE-GUIDE.md")
# (find-luareplfile "RELEASE-GUIDE.md" "0.8.tar.gz")

# https://github.com/hoelzro/lua-repl/commits/master
# https://github.com/hoelzro/lua-repl/compare/0.8-prep
# https://github.com/hoelzro/lua-repl/commit/c130b628df6611ad7857c9aba6aaeb0525bd2589 rcfile



#####
#
# lua-repl 2017
# 2017ago04
#
#####

# «luarepl-2017» (to ".luarepl-2017")
# (find-es "luarepl")
# https://github.com/hoelzro/lua-repl
# (find-git-links "https://github.com/hoelzro/lua-repl" "luarepl")
# https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop
# (find-angg "LUA/lua50init.lua" "loadluarepl")
# (find-fline "~/LATEX/dednat6/lua-repl/")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv ~/usrc/lua-repl/
cd      ~/usrc/
git clone https://github.com/hoelzro/lua-repl
cd      ~/usrc/lua-repl/

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rv ~/LATEX/dednat6/lua-repl/
mkdir  ~/LATEX/dednat6/lua-repl/
mkdir  ~/LATEX/dednat6/lua-repl/repl/
cd ~/usrc/lua-repl/
cp -v rep.lua \
       ~/LATEX/dednat6/lua-repl/
cd ~/usrc/lua-repl/repl/
cp -v init.lua compat.lua sync.lua utils.lua \
       ~/LATEX/dednat6/lua-repl/repl/


# (find-fline "~/usrc/")
# (find-fline "~/usrc/lua-repl/")

# (code-c-d "luarepl" "~/usrc/lua-repl/")
# (find-luareplfile "")
# (find-gitk "~/usrc/lua-repl/")

# (find-angg "LUA/lua50init.lua" "loadluarepl")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
= (package.path:gsub(";", "\n"))
= loadluarepl("~/usrc/lua-repl/")
= (package.path:gsub(";", "\n"))
PPV(keys(package.loaded))
PPV(package.loaded["repl"])
PPV(package.loaded["repl.sync"])
PPV(package.loaded["repl.utils"])
PPV(package.loaded["repl.compat"])
sync:run()
  print(repl:name())
  PPV(sync)
  PPV(repl)





#####
#
# luarepl-2017 in latex: tests
# 2017ago05
#
#####

# «luarepl-2017-latex» (to ".luarepl-2017-latex")
# (find-LATEXfile "2017planar-has-1.tex")
# (find-LATEXfile "2017planar-has-1.tex" "\\repl")
# (find-LATEXfile "dednat6/dednat6.lua" "luarepl")
# (find-dn6file "luarepl.lua")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/LATEX/
       lualatex -record 2017planar-has-1.tex
REPL=1 lualatex -record 2017planar-has-1.tex





#####
#
# lua-repl: displayresults
# 2016oct07
#
#####

# «luarepl-displayresults» (to ".luarepl-displayresults")
# (find-LATEXgrep "grep --color -nrH -e display lua-repl/*")
;; (find-LATEXfile "lua-repl/repl/init.lua" "function repl:displayresults")




#####
#
# luaprompt
# 2015jun12
#
#####

# «luaprompt» (to ".luaprompt")
# https://github.com/dpapavas/luaprompt




#####
#
# Repl (my owl REPL, built on top of eoo)
# 2013jan05
#
#####

# «Repl» (to ".Repl")
# (find-angg "LUA/lua50init.lua" "Repl")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
repl = Repl{}
= repl:read_()
print(2+
3+
4)

repl:repl()
print(2+
      3)
= 2
= 3+
  4
== {2,
    3}
!



#####
#
# over and Over
# 2013aug30
#
#####

# «over» (to ".over")
# (find-angg "LUA/lua50init.lua" "over")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
over = function (B)
    return function (A)
        return setmetatable(A, {__index=B})
      end
  end
Over = function (class)
    return over(class.__index)
  end

b = {bb="BB"}
a = over(b) {aa="AA"}
= a.aa  --> "AA"
= a.bb  --> "BB"

B = Class {
  type    = "B",
  __index = {
    b = "bb",
  },
}
A = Class {
  type    = "A",
  __index = Over(B) {
    a = "aa",
  },
}
= A{}.a  --> "aa"
= A{}.b  --> "bb"




#####
#
# follow
# 2013aug28
#
#####

# «follow» (to ".follow")
# A tool to debug metatable & inheritance schemes
-- (find-angg "LUA/lua50init.lua" "Repl")
-- (find-angg "LUA/lua50init.lua" "follow")
-- (find-dn5file "eoo.lua")
-- (find-dn5 "eoo.lua" "box-diagram")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
PlainRep = Class {
  type    = "MetaRep",
  __index = {
    incompletep0 = function (r, str)
        return str:find(": unexpected symbol near '<eof>'$")
      end,
    incompletep = function (r, str)
        local f, err = loadstring(str)
        return f == nil and r:incompletep0(err)
      end,
    read0 = function (r, prompt) io.write(prompt); return io.read() end,
    read1 = function (r) return r:read0 ">>> "  end,
    read2 = function (r) return r:read0 "... " end,
    -- readinitial = function (r, str) return r, (str or r:read1()) end,
    -- readrest = function (r, str)
    --     while r:incompletep(str) do str = str..r:read2() end
    --     return r,str
    --   end,
    -- read = function (r, str)
    --     r,str = r:readinitial(str)
    --     return r:readrest(str)
    --   end,
    prefixhack = function (r, str) return r, str end,
    read = function (r, str)
        str = str or r:read1()      -- first line
        r, str = r:prefixhack(str)  -- a trick for "=" and friends
        while r:incompletep(str) do str = str..r:read2() end  -- complete
        return r, str
      end,
    eval = function (r, str) return assert(loadstring(str))() end,
    print = function (r, ...) end,
    ep  = function (r, str) r:print(r:eval(str)) end,
    rep = function (r, str) r,str = r:read(str); return r:ep(str) end,
  },
}

ExprRep = Class {
  type    = "ExprRep",
  __index = Over(PlainRep) {
    print = function (r, ...) print(...) end,
  },
}

LuaRep = Class {
  type    = "LuaRep",
  __index = Over(PlainRep) {
    read = function (r)
        local str = r:read1()
        local expr = str:match("^=(.*)$")  
        if expr then return ExprRep{}:read("return "..expr) end
        return PlainRep{}:read(str)
        end
      end,
  },
}

LuaRep = Class {
  type    = "LuaRep",
  __index = Over(PlainRep) {
  },
}


LuaRep{}:rep()
=1+
 2
LuaRep{}:rep()
print(1+
      2)

ExprRep{}:rep("return 1+2")



pf = function (str) PP(follow(LuaRep, str)) end

pf ""
pf "__index"
pf "__index mt"
pf "__index mt __index"
pf "mt"
pf "mt __call"
pf "mt __call"
pf "{}"
pf "{} mt"
pf "{} mt __index"
pf "{} mt __index mt"

pf "{} rep"
pf "{} ep"







#####
#
# icollect
# 2013jan01
#
#####

# «icollect» (to ".icollect")
# (find-angg "LUA/lua50init.lua" "icollect")





#####
#
# Low-level access to the innards
# 2013jan09
#
#####

# «lua-innards-gdb» (to ".lua-innards-gdb")
# (find-angg ".emacs" "eepitch-gdb-lua")
# (find-es "gdb" "main-commands")
# (find-es "gdb" "macros")
# http://lua-users.org/lists/lua-l/2013-01/msg00203.html
# http://article.gmane.org/gmane.comp.lang.lua.general/96395

# http://zeuxcg.org/2010/11/07/lua-callstack-with-c-debugger/
# http://www.altdevblogaday.com/2011/04/15/scripting-rant/
# https://github.com/mkottman/lua-gdb-helper

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
gdb -q ~/usrc/lua-5.1.4/src/lua_O0
br math_sin
run

  outer_fun = function (a, b)
      local c, d, e = "CC", "DD", "EE"
      return 1 + inner_fun("FF", "GG")
    end

  inner_fun = function (f, g)
      local h, i, j = "HH", "II", "JJ"
      return math.sin(0)
    end

  twentytwo = "22"
  twentytwon = 22
  outer_fun("AA", "BB")
#/--
set $mystr = "inner_fun"
tbr luaS_newlstr
p lua_getglobal(L, $mystr)
#    (find-lua51tag "luaS_newlstr")
u
u
u
u
u
info locals
p lmod(h, G(L)->strt.size)
macro expand G(L)
p L->l_G->strt.hash[384]
u
p o
p *o
p LUA_TSTRING
p o->ts.tsv.tt
p o->ts.tsv.tt == LUA_TSTRING
n
n
p ts
p getstr(ts)

macro expand rawgco2ts(o)


p getstr(o)


pt o->gch
pt o->ts
pt o->ts.dummy
p &(o->gch   .tt)
p &(o->ts.tsv.tt)

ptype o

#***

# gdb:
# (find-gdbnode "Convenience Vars" "set $foo =")
set $twentytwo = "twentytwo"
pt  $twentytwo
p printf("\"%s\"\n", $twentytwo)

macro expand lua_getglobal(L, $twentytwo)
# (find-lua51tag "lua_getglobal")
# (find-lua51tag "lua_getfield")
# (find-lua51tag "luaS_new")
# (find-lua51tag "luaS_newlstr")
#
tbr luaS_newlstr
# p luaS_newlstr(L, $twentytwo, strlen($twentytwo))
p lua_getglobal(L, $twentytwo)
n
n
n
n
# We're in a loop, so let's use `u' (`until') to trace past it
u
p h
info args
info locals
# (find-gdbnode "Frame Info")
#
macro expand G(L)
macro expand lmod(h, G(L)->strt.size)
p lmod(h, G(L)->strt.size)
n
p ts
p *ts
#
# (find-lua51tag "luaS_newlstr")
macro expand getstr(ts)
p getstr(ts)
n
n
cont

pt L
pt L->env
p  L->env.tt
pt L->env.value
pt L->env.value.gc
pt L->env.value.gc.h
pt L->env.value.gc.h
p  L->env.value.gc.h.sizearray
tbr luaS_newlstr
p lua_getfield(L, -10002, "twentytwo")
bt 4
n
tbr 82
c
info line
l 82
l $(info line)
p h
# h = 178388671
n
p o
ptype o
p o->gch.tt
p o->ts
p &(o->ts)
n
p ts
# (find-lua51tag "luaS_newlstr")
p (char *)((ts) + 1)
p str

p ts

# (find-lua51file "")
# (find-lua51tag "main")
# (find-lua51tag "lua_getglobal")
# (find-lua51tag "LUA_GLOBALSINDEX" "-10002")
# (find-lua51tag "lua_getfield")
# (find-lua51tag "luaS_new")
# (find-lua51tag "rawgco2ts")
# (find-lua51tag "LUA_TSTRING" "4")
# (find-lua51tag "getstr")
# (find-lua51tag "lmod")
# (find-lua51tag "G")

# (find-eevgrep "grep -nH -e ee-find-tag *.el")
# (find-lua51manualw3m "#lua_getglobal")
# lua_getfield(L, LUA_GLOBALSINDEX, s)

# (find-gdbnode "Continuing and Stepping" "`until'")
# (find-gdbnode "Continuing and Stepping" "`next [COUNT]'")
# (find-gdbnode "Auto Display")
# (find-gdbnode "Convenience Vars")





#####
#
# The Sexp class (for htmlizing elisp sexps, from blogme3, rewritten)
# 2013jan17
#
#####

# «Sexp» (to ".Sexp")
# (find-angg "LUA/lua50init.lua" "Sexp")
# (find-angg "LUA/lua50init.lua" "Sexp" "hrefto =")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
h = function (line) print(Sexp{line=line}:getlinehtml()) end
h '# foo:  (find-angg "dir" "tatag")'
h '# sexp: (to "target")'
h '# foo:  (find-angg "dir" "tatag")'
h '# foo:  (find-es "lua5" "goto")'
h '# foo:  (find-fooaudio "12:34" "comment")'

-- print(Q"commént")
-- (find-blogme3 "charset.lua")




#####
#
# Sean Conner's Kitchen Sink Lua
# 2013mar07
#
#####

# «kslua» (to ".kslua")
# (find-fline "~/tmp/kitchen-sink-lua-2013-03-07.txt")




#####
#
# Lua for Windows
# 2013may17
#
#####

# «luaforwindows» (to ".luaforwindows")
# (find-es "w32" "emacs-for-windows-2012")
# http://luabinaries.sourceforge.net/
# https://code.google.com/p/luaforwindows/
# https://luaforwindows.googlecode.com/files/LuaForWindows_v5.1.4-46.exe
# http://article.gmane.org/gmane.comp.lang.lua.general/100153

c:/eev2/
c:/eev2/eev-readme.el
c:/eev2/Lua/5.1/
c:/eev2/Lua/5.1/lua.exe
c:/eev2/Lua/5.1/ilua.cmd

* (setenv "LUA_INIT" "@c:/eev2/luainit.lua")
* (eev "io.stdout:setvbuf'no'; print'Hello'" nil "/tmp/o") 
* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
lua
print(1+2)




#####
#
# hex
# 2013jul01
#
#####

# «hex» (to ".hex")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
tohex2  = function (n)   return format("%02X", n) end
tohex2s = function (...) return table.concat(map(tohex2, {...}), " ") end
strtohex = function (s)  return tohex2s(string.byte(s, 1, #s)) end
hextoc   = function (h)  return string.char(tonumber(h, 16)) end
hextostr = function (hs) return (hs:gsub("(%x%x) ?", hextoc)) end

= tohex2s(3, 17)     --> 03 11
= strtohex "Hello"   --> 48 65 6C 6C 6F
= hextoc("40")       --> @
= hextostr("40 41")  --> @A

hextopstr = function (s) return "("..strtohex(s)..")" end
strtouhex = function (s) return (s:gsub("[\127-\255]+", hextopstr)) end

big = readfile "/home/edrx/UTF8/greek-glyphs"
= big
= strtouhex(big)
= hextostr "CE B3 CE B2 CE B1"
= strtohex "abc"





#####
#
# LaTeX parsing
# 2013sep23
#
#####

# «latex-parsing» (to ".latex-parsing")
# (find-lpegw3m "lpeg.html")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
loadlpeg()

whitespacechar = lpeg.S " \t"
restofline     = (1 - lpeg.S "\n")^0
whitespace_r   = lpeg.P "%" * restofline
newline        = lpeg.P "\n"
whitespace_l   = whitespacechar^0
whitespace_rl  = whitespace_r * newline * whitespace_l
ignore         = whitespace_rl^0

whitespace_m   = whitespacechar^1

comment = 




#####
#
# Using coroutines in a for
# 2013sep24
#
#####

# «coroutine-for» (to ".coroutine-for")
# (find-anggfile "LUA/youtube-db.lua" "coy = coroutine.yield")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
Y = coroutine.yield
W = coroutine.wrap
f = function () Y(11, 111); Y(22, 222); Y(33, 333) end
for a,b in W(f) do print(a,b) end   --> 11 111 | 22 222 | 33 333
g = function () for i=1,4 do Y(i) end for i=10,12 do Y(i) end end
for a   in W(g) do print(a) end     --> 1 | 2 | 3 | 4 | 10 | 11 | 12

-- This part does not work yet:
C = coroutine.create
R = coroutine.resume
= R(C(f))
= R(R(C(f)))




#####
#
# cow and coy
# 2014apr03
#
#####

# «cow-and-coy» (to ".cow-and-coy")
# (find-angg "LUA/lua50init.lua" "cow-and-coy")
# (find-anggfile "LUA/youtube-db.lua" "coy = coroutine.yield")
# (find-anggfile "LUA/youtube-db.lua" "return cow(function ()")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
coy = coroutine.yield
cow = coroutine.wrap

dominos = function (prefix, n)
    if     n <= 0 then coy(prefix)
    elseif n == 1 then coy(prefix.."1")
    else
      dominos(prefix.."1", n-1)
      dominos(prefix.."2", n-2)
    end
  end
gen_dominos = function (n)
    return cow(function ()
        dominos("", n)
      end)
  end
for d in gen_dominos(6) do print(d) end





#####
#
# video_fnames_js
# 2013sep26
#
#####

# «video_fnames_js» (to ".video_fnames_js")
# (find-angg "HTML/local-videos.js")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
coy = coroutine.yield
cow = coroutine.wrap
coc = coroutine.create
cor = coroutine.resume
cos = coroutine.status

video_fnames = function (bigstr)
    return cow(function ()
        for fname in bigstr:gmatch("%S+") do
          local hash = fname:match "(...........)%.mp4$"
          if hash then coy(hash, fname) end
        end
      end)
  end
video_fnames_js = function (bigstr, filter)
    local A = {}
    for hash,fname in video_fnames(ols) do
      if not filter or filter(hash) then
        table.insert(A, format("  '%s': '%s'", hash, fname))
      end
    end
    return "{\n"..table.concat(A, ",\n").."\n}"
  end

ols = getoutput("cd ~/TH/L/ && ls manifs/*.mp4")
ols = getoutput("cd ~/TH/L/ && ls manifs/*.mp4 | head -n 4")
ols = getoutput("cd ~/TH/L/ && ls manifs/*.mp4 | awk 'length($0)<60'")
for h,fn in video_fnames(ols) do printf("  '%s': '%s',\n", h, fn) end
= "youtube_mp4s = "..video_fnames_js(ols)

youtube_mp4s = {
  'y7E5Vy0PinY': 'manifs/7_de_setembro-y7E5Vy0PinY.mp4',
  'cfxnZHuL-OQ': 'manifs/Black_Bloc_-_o_Brasil_de_preto-cfxnZHuL-OQ.mp4',
  'T0ITOENS8qE': 'manifs/CA_A_IMPRENSA_NO_7_DE_SETEMBRO-T0ITOENS8qE.mp4'
}



#####
#
# Thijs Schreier's post about threads
# 2013oct03
#
#####

# «thijs-threads» (to ".thijs-threads")
# http://www.thijsschreijer.nl/blog/?p=693




#####
#
# Worp
# 2013nov14
#
#####

# «worp» (to ".worp")
# Worp: a LuaJIT based engine for audio / music / DSP
# http://lua-users.org/lists/lua-l/2013-11/msg00229.html
# http://worp.zevv.nl/
# https://github.com/zevv/worp.git
# (find-git-links "https://github.com/zevv/worp.git" "worp")
# (find-angg ".emacs" "luajit")

# (code-c-d "worp" "~/usrc/worp/")
# (find-worpfile "")
# (find-worpfile "app/")
# (find-worpfile "app/Makefile")
# (find-worpfile "worp")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/worp/
git clean -dfx
git reset --hard
make   |& tee om

cd ~/usrc/worp/
luajit
userocks()
loadposix()

dofile "worp"
require "luaposix"

luajit worp





#####
#
# rawtostring
# 2014feb06
#
#####

# «rawtostring» (to ".rawtostring")
# More metatable abuse: useful __tostring for functions
# http://lua-users.org/lists/lua-l/2014-02/msg00050.html
# https://github.com/dlaurie/lua-ihelp
# (find-lua51srcgrep "grep -nH -e tostring *.c")
# (find-lua51srcfile "lbaselib.c" "luaB_tostring")




#####
#
# re
# 2014feb14
#
#####

# «re» (to ".re")

# http://fanf.livejournal.com/97572.html
# http://www.inf.puc-rio.br/~roberto/lpeg/re.html
# (find-es "lua5" "lpeg-0.12")
# (find-lpegw3m  "re.html")
# (find-angg "LUA/precedenceparser.lua")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
userocks()
require "re"
parser = re.compile([[
  add <- ( num ( { '+' } num ) * ) -> print
  num <- {%d+}
]], {
  bin = function (a, op, b)
      local r = a.." "..b.." "..op
      print(r)
      return r
    end,
  print = print
})
= parser:match "23+100+45"


local parser = re.compile([[
    line <- ( <stamp> ' ' {%a*} ' ' <count> !. ) -> process
    stamp <- ( <date> ' ' <time> ' ' <zone>   ) -> tostamp
    date  <- ( <num><num> '-' <num> '-' <num> ) -> todate
    time  <- (      <num> ':' <num> ':' <num> ) -> totime
    zone  <- ( {[+-]} <num> <num>             ) -> tozone
    count <- {'@'*} -> tocount
    num   <- {%d^2} -> tonumber
]], {
    process = process,
    tonumber = tonumber,
    tocount = function (s) return #s end,
    todate = function (c,y,m,d)
        if m > 2 then m = m + 1;  y = c*100 + y
                 else m = m + 13; y = c*100 + y - 1 end
        return int(y*1461/4) - int(y/100) + int(y/400)
             + int(m*153/5) + d - 719591
    end,
    totime = function (H,M,S)
        return H*3600 + M*60 + S
    end,
    tozone = function (zs,zh,zm)
        local z = zh*3600 - zm*60
        if zs == "-" then return -z
                     else return  z  end
    end,
    tostamp = function (date,time,zone)
        return date*86400 + time - zone
    end
})

for line in io.stdin:lines() do
    if not parser:match(line) then
        io.stdout:write("skipping "..line.."\n")
    end
end




#####
#
# lbc
# 2014mar06
#
#####

# «lbc» (to ".lbc")
# (find-luarocksbinfile "")
# (find-luarocks-links "lbc" "" "20120430-1" "lbc")
# (find-luarocks-links "lbc" "20120430" "-1" "lbc")
# (find-luarocks-links "lbc" "20120430-1" "" "lbc")

# Inspect and unpack:
* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# (find-luarocksfile "bin/" "lbc")
# (find-luarocksfile    "bin/lbc-20120430-1.src.rock")
unzip -l ~/usrc/luarocks/bin/lbc-20120430-1.src.rock
unzip -p ~/usrc/luarocks/bin/lbc-20120430-1.src.rock lbc.tar.gz \
  | tar -tvzf -
rm -Rfv ~/usrc/bc/
unzip -p ~/usrc/luarocks/bin/lbc-20120430-1.src.rock lbc.tar.gz \
  | tar -C ~/usrc/ -xvzf -
cd     ~/usrc/bc/

;; (find-angg ".emacs" "luarocks")
;; (find-luarocks-links "lbc" "" "20120430-1")
;; (find-lbcfile "")
(code-c-d "lbc" "~/usrc/bc/")




#####
#
# HTML parsers
# 2014aug30
#
#####

# «html-parsers» (to ".html-parsers")
# (find-es "netsurf" "lua-hubbub")
# http://lua-users.org/lists/lua-l/2013-05/threads.html#00581
# http://lua-users.org/lists/lua-l/2013-05/msg00636.html



#####
#
# gumbo-parser
# 2014aug30
#
#####

# «gumbo-parser» (to ".gumbo-parser")
# Moved to: (find-es "html" "gumbo-parser")




#####
#
# lua-gumbo: building (with thanks to Craig Barnes)
# 2015nov21
#
#####

# «lua-gumbo-build» (to ".lua-gumbo-build")
# Uses: (find-es "html" "gumbo-parser-deb-src")
# https://github.com/craigbarnes/lua-gumbo
# https://github.com/craigbarnes/lua-gumbo#persistent-build-configuration
# http://lua-users.org/lists/lua-l/2015-11/msg00192.html
# https://mail.google.com/mail/ca/u/0/#inbox/15123247666963ee craig<->me
# (find-git-links "https://github.com/craigbarnes/lua-gumbo" "luagumbo")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv ~/usrc/lua-gumbo/
cd      ~/usrc/
git clone https://github.com/craigbarnes/lua-gumbo

cd      ~/usrc/lua-gumbo/
# (find-gitk "~/usrc/lua-gumbo/")
git checkout
git clean -f

cd      ~/usrc/lua-gumbo/
# export LD_LIBRARY_PATH=/usr/local/lib
make              |& tee om
make check        |& tee omc
sudo make install |& tee omi
installeddebs | sort |& tee oinstalleddebs
# (find-angg ".zshrc" "installeddebs")

tar -cvzf      /tmp/lua-gumbo-logs.tgz o*
# (find-fline "/tmp/lua-gumbo-logs.tgz")

# (code-c-d "luagumbo" "~/usrc/lua-gumbo/")
# (find-luagumbofile "")
# (find-luagumbofile "om")
# (find-luagumbofile "omc")
# (find-luagumbofile "omi")
# (find-luagumbofile "gumbo/" "parse.so")

# (find-luagumbofile "README.md")
# (find-luagumbofile "README.md" "make LUA_CFLAGS=")
# (find-luagumbofile "test/dom/")
# (find-luagumbofile "test/dom/interfaces.lua")
# (find-luagumbofile "test/dom/Document-title.lua")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/lua-gumbo/test/
for i in *.lua; do echo; echo $i; lua5.1 $i; done

# lua5.1: error loading module 'gumbo.parse' from file '/usr/local/lib/lua/5.1/gumbo/parse.so':
#     libgumbo.so.1: cannot open shared object file: No such file or directory

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
chdir "~/usrc/lua-gumbo/test/"
-- (find-luagumbofile "test/")
-- (find-luagumbofile "test/dom/")
-- (find-luagumbofile "test/dom/Document-title.lua")
dofile "Set.lua"




#####
#
# lua-gumbo
# 2015nov21
#
#####

# «lua-gumbo» (to ".lua-gumbo")
# https://github.com/craigbarnes/lua-gumbo#example

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
gumbo = require "gumbo"
document = gumbo.parse('<div id="foo">Hello World</div>')
foo = document:getElementById("foo")
text = foo.childNodes[1].data
print(text) --> Hello World

-- file:///home/edrx/TH/L/uma-policia-que.html
fname = "/home/edrx/TH/L/uma-policia-que.html"
bigstr = ee_readfile(fname)
document = gumbo.parse(bigstr)
= document.title

-- (find-luagumbofile "test/htmlfmt.lua")
serialize = require "gumbo.serialize.html"
serialize(document, io.stdout)



#####
#
# PegDebug
# 2014sep23
#
#####

# «pegdebug» (to ".pegdebug")
# https://github.com/pkulchenko/PegDebug
# http://lua-users.org/lists/lua-l/2009-10/msg00774.html
# http://lua-users.org/lists/lua-l/2014-09/msg00119.html
# Message-Id: <CADUw5q3coxbLPUEsG4sGU5g1D6EZF9hKbpm1rYK46pLniNo0WQ@mail.gmail.com>




#####
#
# Syntax trees (using Rect)
# 2014sep27
#
#####

# «syntax-trees» (to ".syntax-trees")
# (find-angg "LUA/lua50init.lua" "Rect")
# (find-angg "LUA/lua50init.lua" "syntree")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
rf = function (str) return Rect.from(str) end
r1 = rf "*__.\n|  |\n2  3"
= r1
= syntree0("a", {r1, 44, r1})


* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)

syntreeg = function (...)
    local A = {...}
    local rf = function (i, op, h)
        return Rect.from(A[i]):syntree1(op, h)
      end
    if #A == 1 then return A[1] end
    r = rf(#A)
    for i=#A-2,1,-2 do
      r = rf(i, A[i+1], "_")..r
    end
    return r
  end

abc = syntreeg("a", "+", "b", "-", "c")
= abc
= syntreeg(abc, "*", "b", "-", abc)
= syntreeg("e")




#####
#
# pkg-config
# 2014oct02
#
#####

# «pkg-config» (to ".pkg-config")
# (find-angg "peek/Makefile")
# (find-status   "pkg-config")
# (find-vldifile "pkg-config.list")
# (find-udfile   "pkg-config/")
# (find-status   "liblua5.1-0-dev")
# (find-vldifile "liblua5.1-0-dev:i386.list")
# (find-udfile   "liblua5.1-0-dev/")
# (find-fline "/usr/lib/i386-linux-gnu/pkgconfig/")
# (find-fline "/usr/lib/i386-linux-gnu/pkgconfig/" "lua")
# (find-fline "/usr/lib/i386-linux-gnu/pkgconfig/lua5.1.pc")
# (find-fline "/usr/lib/i386-linux-gnu/pkgconfig/lua5.1-c++.pc")
# http://lua-users.org/lists/lua-l/2012-02/msg00748.html
# (find-fline "~/LOGS/2014oct02.lua")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
pkg-config --cflags lua5.1
pkg-config --libs lua5.1

# See: https://github.com/stevedonovan/ldeb
# http://lua.2524044.n2.nabble.com/ANN-ldeb-a-Debian-packager-for-Lua-scripts-td7538861.html



#####
#
# pluto
# 2014oct07
#
#####

# «pluto» (to ".pluto")
# (find-luarocks-links "pluto" "2.4" "-1" "pluto")
# (find-luarocksfile "bin/olb-pluto")
# (find-luarocksfile "bin/" "pluto")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
userocks()
require "pluto"
o = {20, 30}
= pluto.persist({}, o)




#####
#
# serpent
# 2014oct07
#
#####

# «serpent» (to ".serpent")
# https://rocks.moonscript.org/modules/luarocks/serpent
# (find-luarocks-links "serpent" "0.27" "-1" "serpent")
# (find-sh "unzip -l ~/usrc/luarocks/bin/serpent-0.27-1.src.rock")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rv ~/usrc/serpent/
mkdir  ~/usrc/serpent/
cd     ~/usrc/
unzip ~/usrc/luarocks/bin/serpent-0.27-1.src.rock

# (find-serpentfile "")
# (find-serpentfile "README.md")
# (find-serpentfile "t/bench.lua")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
userocks()
serpent = require "serpent"
= serpent
PP(serpent)
= serpent.dump({20, 30})
--> do local _={20,30};return _;end




#####
#
# LDoc
# 2014nov10
#
#####

# «ldoc» (to ".ldoc")
# https://github.com/stevedonovan/LDoc
# http://keplerproject.github.io/luadoc/
# http://stevedonovan.github.io/ldoc/
# http://lua-users.org/wiki/DocumentingLuaCode
# (find-luarocks-links "ldoc" "1.4.2" "-1" "")
# (find-luarocks-links "markdown" "0.32" "-2" "")

* (eepitch-shel)
* (eepitch-kill)
* (eepitch-shel)
rm -Rfv ~/usrc/ldoc-1.4.2/
mkdir   ~/usrc/ldoc-1.4.2/
cd      ~/usrc/ldoc-1.4.2/
unzip   ~/usrc/luarocks/bin/ldoc-1.4.2-1.src.rock

# (find-ldocfile "")
# (find-ldocfile "doc/doc.md")
# (find-ldocfile "readme.md")




#####
#
# Firestar
# 2014dec01
#
#####

# «firestar» (to ".firestar")
# http://www.firestr.com
# http://www.github.com/mempko/firestr
# http://fire.readthedocs.org/en/latest/api/reference/




#####
#
# debug.lua
# 2014dec03
#
#####

# «debug.lua» (to ".debug.lua")
# (find-luarocks-links "debug.lua" "{ver}" "{sub}" "")
# (find-luarocks-links "debug" "{ver}" "{sub}" "")
# http://www.tset.de/debug.lua/
# http://www.tset.de/debug.lua/README.html
# http://www.tset.de/downloads/debug.lua-0.8-1.tar.gz
#*
rm -Rv ~/usrc/debug.lua-0.8-1/
tar -C ~/usrc/ -xvzf $S/http/www.tset.de/downloads/debug.lua-0.8-1.tar.gz
cd     ~/usrc/debug.lua-0.8-1/

#*
# (code-c-d "debuglua" "~/usrc/debug.lua-0.8-1/")
# (find-debugluafile "")






#####
#
# graph-toolkit
# 2014dec19
#
#####

# «graph-toolkit» (to ".graph-toolkit")
# https://github.com/franko/graph-toolkit
# http://franko.github.io/graph-toolkit/
# http://franko.github.io/graph-toolkit/graphics.html#module-graph

# (find-git-links "https://github.com/franko/graph-toolkit" "graphtoolkit")
# (code-c-d "graphtoolkit" "~/usrc/graph-toolkit/")
# (find-graphtoolkitfile "")
# (find-graphtoolkitfile "src/makeconfig")
# (find-debpkg-links "libagg-dev")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/usrc/graph-toolkit/
make        |& tee om
make debian |& tee omd
sudo dpkg -i *.deb

# (find-status   "lua-graph-toolkit")
# (find-vldifile "lua-graph-toolkit.list")
# (find-udfile   "lua-graph-toolkit/")
# (find-fline "/usr/share/lua/5.1/graph/")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
require "graph"
-- define the function
function f(x) return math.sin(x) * x^2 end

-- create a plot of f(x) for x going from 0 to 25
p = graph.plot("y = sin(x) * x^2")
line = graph.fxline(f, 0, 25)
p:addline(line, "red")
p:show()






#####
#
# debug2
# 2015jan02
#
#####

# «debug2» (to ".debug2")
# (find-es "lua5" "pkg-config")
# (find-lua51srcfile "ldebug.c")
# (find-lua51srcfile "ldebug.h")
# (find-lua51srcfile "ldblib.c")
# (find-angg "peek/peek-0.0.1-0.rockspec" "build")
# (find-angg "peek/olm-peek")
# (find-angg "peek/peek.c" "init")
# (find-sh0 "pkg-config --cflags lua5.1")
# (find-sh0 "pkg-config --libs lua5.1")
# (find-lua51srcgrep "grep -nH -e '\"debug\"' *")
#
# (defun eejump-9  () (find-freenode    "#lua"))
# (defun eejump-99 () (find-freenode-3a "#lua"))
# (defun u () (interactive) (find-escript-upload-links "lua5" "debug2"))
# (defun u () (interactive) (find-escript-upload-links "lua5" "debug2-compile-0"))

# «debug2-compile-0» (to ".debug2-compile-0")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd /tmp/
cp -v ~/usrc/lua-5.1.4/src/ldblib.c /tmp/debug2.c

cat >> /tmp/debug2.c <<'%%%'
LUALIB_API int luaopen_debug2 (lua_State *L) {
  luaL_register(L, "debug2", dblib);
  return 1;
}
%%%
tail /tmp/debug2.c
# (find-fline "/tmp/debug2.c")

cd /tmp/
gcc -O2 -fPIC $(pkg-config --cflags lua5.1) -c debug2.c -o debug2.o
gcc -shared   $(pkg-config --libs lua5.1)      debug2.o -o debug2.so

lua5.1
  require "debug2"
  PP(debug2)
  os.exit()



# (find-fline "/tmp/debug2.c")
# (find-lua51srcfile "ldblib.c" "db_getlocal")
# (find-lua51srcfile "ldebug.c" "lua_getlocal")
# (find-lua51manualw3m "#luaL_checkudata")
# (find-lua51manualw3m "#lua_islightuserdata")
# (find-lua51manualw3m "#lua_pushlightuserdata")
# (find-lua51manualw3m "#lua_touserdata")




#####
#
# 30log - Roland Yonaba's "30 Lines Of Goodness" (oo)
# 2015apr02
#
#####

# «30log» (to ".30log")
# https://github.com/Yonaba/30log
# https://github.com/Yonaba/30log/blob/master/README.md
# http://github.com/Yonaba/30log/blob/master/30logclean.lua




#####
#
# Lua5.2 in Debian
# 2015may09
#
#####

# «lua5.2-debian» (to ".lua5.2-debian")
# (find-angg ".emacs" "lua5.2-debian")
# (find-zsh "installeddebs | sort | grep lua5.2")
# (find-zsh "availabledebs | sort | grep lua5.2")
# (find-zsh "availabledebs | sort | grep lua5")

# (find-status   "lua5.2")
# (find-vldifile "lua5.2.list")
# (find-udfile   "lua5.2/")
# (find-status   "lua5.2-doc")
# (find-vldifile "lua5.2-doc.list")
# (find-udfile   "lua5.2-doc/")



#####
#
# utf8
# 2015may09
#
#####

# «utf8» (to ".utf8")
# http://lua-users.org/wiki/LuaUnicode
# https://github.com/alexander-yakushev/awesompd/blob/master/utf8.lua
# https://github.com/alexander-yakushev/awesompd/raw/master/utf8.lua
# http://www.lua.org/manual/5.3/manual.html#6.5

# (find-esgrep "grep -niH -e utf *.e")
# (find-man "7 utf-8")
# (find-man "7 utf-8" "0x00000080 - 0x000007FF:")

0x00000000 - 0x0000007F:
    0xxxxxxx
    0-127    

0x00000080 - 0x000007FF:
    110xxxxx 10xxxxxx
    192-223  128-191

0x00000800 - 0x0000FFFF:
    1110xxxx 10xxxxxx 10xxxxxx
    224-239  128-191  128-191

0x00010000 - 0x001FFFFF:
    11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
    240-247  128-191  128-191  128-191

0x00200000 - 0x03FFFFFF:
    111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
    248-251  128-191  128-191  128-191  128-191

0x04000000 - 0x7FFFFFFF:
    1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
    252-253  128-191  128-191  128-191  128-191  128-191

An utf8-char matches this pattern: "[\192-\253][\128-\191]+"
 string.len8 = function (str) return str:gsub("[\128-\191]+", ""):len() end

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
utf8pat = "[\192-\253][\128-\191]+"
bigstr = ee_readfile "~/LATEX/istanbul1.org"
lines = splitlines(bigstr)
ulines = {}
for _,li in ipairs(lines) do
  if li:match(utf8pat) then
    table.insert(ulines, li)
  end
end
= #lines
= #ulines
= ulines[1]
u = ulines[1]:match(utf8pat)
= u
= #u
= u:byte(1, 2)
a, b = u:byte(1, 2)
= (a-192)*64+(b-128)
= tostring(183, 16)
= format("%x", 183)
= format("%X", 183)
= format("&#x%X;", 183)
A9";"


# (find-blogme3grep "grep -nH -e '&gt;' *.lua")

= utohtml(u)
= ustohtml(ulines[1])



#####
#
# utf8 to html
# 2015aug06
#
#####

# «utf8-to-html» (to ".utf8-to-html")
# Note: I wrote this as a quick hack for the Istanbul minicourse,
# then abandoned it - it is much better to generate a PDF from Org
# using verbatim blocks and ttchars.

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)

utf8pat = "[\192-\253][\128-\191]+"
utohtml = function (u)
    local a, b = u:byte(1, 2)
    local code = (a-192)*64+(b-128)
    return format("&#x%X;", code)
  end
ustohtml = function (str)
    return (str:gsub(utf8pat, utohtml))
  end
ustohtml2 = function (str)
    local str2 = str:gsub("[&<>]", {["&"]="&amp;", ["<"]="&lt;", [">"]="&gt;"})
    return ustohtml(str2)
  end

-- (find-es "org" "parse-org-with-lua")
-- dofile "istanbulall.lua"
-- parseorg_utils()
bigstr = ee_readfile "~/LATEX/istanbul1.org"
bigstr2 = ustohtml2(bigstr)
ee_writefile("/tmp/uh", bigstr2)

-- (find-fline "/tmp/uh")





#####
#
# multiplication as composition
# 2015jun01
#
#####

# «mult-as-comp» (to ".mult-as-comp")
# (find-LATEXgrep "grep -nH -e __mul *")
# (find-LATEXfile "2014-1-GA-P2-gab.lua" "__mul =")
# (find-LATEXfile "2015-1-C2-figuras1.lua" "__mul =")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)

-- Make (f*g)(a, b, c) behave as f(g(a, b, c))
debug.setmetatable (print, {
    __mul = function (f, g) return
        function (...) return f(g(...)) end
      end,
  })

w = function (pre, post)
    return function (str)
        return pre..str..post
      end
  end

p = w("(", ")")
b = w("[", "]")
a = w("<", ">")

= (p*b*a) "foo"




#####
#
# Free hosting for Lua scripts
# 2015jul24
#
#####

# «free-hosting» (to ".free-hosting")
* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cat <(wget -qO- http://i.imgur.com/91HtaFp.gif)
# GIF89a=GIF89a
# print'Hello world'

lua <(wget -qO- http://i.imgur.com/91HtaFp.gif)
# Hello world




#####
#
# ElispHF (for elisp hyperlink functions, like "find-angg")
# 2015aug28
#
#####

# «ElispHF» (to ".ElispHF")
# (find-angg "LUA/lua50init.lua" "ElispHF")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
= _E["to"]:calchelp()
= _E["to"]:calctarget()
= _E["to"]:calctarget("anch")
= _E["find-angg"]:calctarget()
= _E["find-angg"]:calctarget("fil")
= _E["find-angg"]:calctarget("fil", "anch")





#####
#
# getsexpskel
# 2015aug05
#
#####

# «getsexpskel» (to ".getsexpskel")
# (find-angg "LUA/lua50init.lua" "getsexpskel")
# This can be a replacement for the lpeg-based sexp parsers at:
# (find-blogme3 "escripts.lua")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
str = [=[# (foo) (find-es "\\bar" (concat "pl" "ic"))]=]
print(str:sub(-1) == ")")
f = function (s) return '"'..string.rep("_", #s-2)..'"' end
g = function (s) return ')'..string.rep("_", #s-2)..'(' end
str2 = str:gsub("\\.", "__")                            print(str2)
str3 = str2:reverse()
str4 = str3:gsub('"[^"]*"', f)                          print(str4:reverse())
skel1 = str3:match("%b)(")                              print(skel1:reverse())
skel2 = skel1:sub(2, -2):gsub("%b)(", g)                print(skel2:reverse())
skel3 = skel2:reverse()

= str
skel = getsexpskel(str)
print(skel)
print(str)

getsexpcomponents = function (str, skel)
    local offset = #str - (#skel + 2)
    for a,b,c in skel:gmatch("()[^ \t]+()") do
      print(str:sub(offset+a+1, offset+b))
    end
  end




#####
#
# SexpLine
# 2015aug13
#
#####

# «SexpLine» (to ".SexpLine")
# (find-angg "LUA/lua50init.lua" "SexpLine")
    -- sl = SexpLine.from(li)
    -- local f = sl.skel and sl:skelf()
    if f then print(sl:split():splitt(), f, sl.skel) end
    if f then PP(sl:split():splitsexp().nth) end
    if f then print(sl:n(), sl:rawarg(2), sl:arg(2)) end

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
li = [[foo (ab "cde")]]
li = [[foo (to "cde")]]
sl = SexpLine.from(li):sethtml()
= sl


PP(sl)
PP(keys(sl))
= sl.html

test = function (li)
    sl = SexpLine.from(li):sethtml()
    local f = sl.f
    if sl.f then print(sl:split():splitt(), f, sl.skel) end
    print(sl)
  end



test [[foo (ab cd ef)]]
test [[foo (ab "cde")]]
test [[foo (ab "c\"")]]
test [[foo (ab "c e")]]
test [[foo (ab "c \"")]]
test [[foo ()]]
test [[foo .ab cd.]]

for i,li in ipairs(splitlines(ee_readfile "~/LUA/lua50init.lua")) do
  test(li)
end





#####
#
# SetL
# 2015aug13
#
#####

# «SetL» (to ".SetL")
# (find-angg "LUA/lua50init.lua" "SetL")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
adds = function (A, str)
    for w in str:gmatch"%S+" do
      local k,v = w:match"(.-)->(.*)"
      if v then A:add(k, v) else A:add(w) end
    end
    return A
  end
A = adds(SetL.new(), "1 2->22 3->33")
B = adds(SetL.new(), "3->333 4->444 5->555")
= A:ksc" "
= B:ksc" "
= (A+B):ksc" "
= (A*B):ksc" "
= (A-B):ksc" "
SetL.__index.print = function (A) for k,v in A:gen() do print(k.."->"..v) end end
(A+B):print()
(A*B):print()
(A-B):print()




#####
#
# Tos
# 2015aug14
#
#####

# «Tos» (to ".Tos")
# (find-angg "LUA/lua50init.lua" "Tos")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
-- (find-es "lua-intro" "intro:keys")
c = {11, 22, 33, nil, 55, foo="FOO"}
d = {11, 22, 33, [5]=555, ["bar"]="BAR", [c]="!"}
PP(c)             --> {1=11, 2=55, 3=33, 5=55, "foo"="FOO"}
PP(d)             --> {1=11, 2=22, 3=33, 5=555, "bar"="BAR", {...}="!"}
d[2], d[c] = nil, nil
PP(d, d[2])       --> {1=11, 3=33, 5=555, "bar"="BAR"}  <nil>
x, y = {10, 20}, {10, 20}
PP(x, y)          --> {1=10, 2=20} {1=10, 2=20}
print(x, y)       --> table: 0x84fc048   table: 0x84fb770
x[1] = 1000
PP(x, y)          --> {1=1000, 2=20} {1=10, 2=20}

# «Tos-indented» (to ".Tos-indented")
# (find-angg "LUA/lua50init.lua" "Tos")
# (find-angg "LUA/lua50init.lua" "Tos" "Tos-indented")
* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
A = {11, {22, {33, 44}, 55}, {66, 77}}
= Tos{}:indented(A)
= "  "..Tos{}:indented(A, "  ")

-- «VerticalTable» (to ".VerticalTable")
-- (find-angg "LUA/lua50init.lua" "VerticalTable")
* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
-- (find-angg "LUA/lua50init.lua" "Tos")
a = {{11, 22}, {33, 44}}
= a                     --> table: 0x23e9ac0
= mytostring(a)         --> {1={1=11, 2=22}, 2={1=33, 2=44}}
= mytabletostring(a)    --> { 1={1=11, 2=22}, \n 2={1=33, 2=44} \n }
= VerticalTable(a)      --> { 1={1=11, 2=22}, \n 2={1=33, 2=44} \n }
= a                     --> { 1={1=11, 2=22}, \n 2={1=33, 2=44} \n }
PPV( {{11, 22}, {33, 44}} )



#####
#
# getdefs
# 2016apr10
#
#####

# «getdefs» (to ".getdefs")
# (find-angg "LUA/flsfiles.lua")

# This script extract functions from my $LUA_INIT file...
# I use it to make lua scripts that are self-contained.
#   (find-angg "LUA/lua50init.lua")

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
bigstr = ee_readfile "~/LUA/lua50init.lua"
lines  = splitlines(bigstr)
isdef  = function (i) return lines[i]:match "^(%w[%w_]*)%s+=" end 
iscom  = function (i) return lines[i]:match "^%-%-" end
isblnk = function (i) return lines[i]:match "^%s*$" end
ismore = function (i) return lines[i] and not isdef(i) and not iscom(i) and not isblnk(i) end
defj = function (i) for j=i+1,20000 do if not ismore(j) then return j-1 end end end
getdef = function (i)
    local name = isdef(i)
    if name then return name, table.concat(lines, "\n", i, defj(i)) end
  end
getdefs = function (names)
    local S = Set.from(split(names))
    for i=1,#lines do
      local name,def = getdef(i)
      if name and S:has(name) then print(def) end
    end
  end

getdefs "ee_expand ee_readfile Set readfile split"





#####
#
# Web frameworks
# 2016may01
#
#####

# «web-frameworks» (to ".web-frameworks")
# http://lua.space/webdev/the-best-lua-web-frameworks



#####
#
# Determining the Lua version
# 2016may22
#
#####

# «lua-version» (to ".lua-version")
# http://lua-users.org/lists/lua-l/2016-05/msg00297.html

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
f = function() return function() end end
t = {
  nil,
  [false]  = 'Lua 5.1',
  [true]   = 'Lua 5.2',
  [1/'-0'] = 'Lua 5.3',
  [1]      = 'LuaJIT'
}
version = t[1] or t[1/0] or t[f()==f()]
= version
PP(t)




#####
#
# tekui
# 2016jun11
#
#####

# «tekui» (to ".tekui")
# http://tekui.neoscientists.org/index.html
# http://tekui.neoscientists.org/installation.html




#####
#
# relative require
# 2017fev06
#
#####

# «relative-require» (to ".relative-require")
# http://lua-users.org/lists/lua-l/2017-02/msg00022.html
# (find-dn6 "dednat6.lua" "package.path")




#####
#
# finding underlined lines in a text file
# 2017jun24
#
#####

# «underlined-lines» (to ".underlined-lines")
# (find-fline "~/eev-intros/find-eev-quick-intro")
# (find-blogme3 "escripts.lua")
# (find-es "lua-intro" "lpeg-re-1")
# file:///usr/share/doc/lua-lpeg-dev/lpeg.html
# file:///usr/share/doc/lua-lpeg-dev/re.html

* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
bigstr = ee_readfile "~/eev-intros/find-eev-quick-intro"
-- = bigstr
require "lpeg"
require "re"

UnderLine = re.compile "('='+ / '-'+) '\n'"
HeadLine1 = re.compile "{{[0-9][.0-9]+} ' '+ {[^\n]*}} '\n'"
HeadLine  = HeadLine1 * #UnderLine

PP(HeadLine:match "123.4 Hello\n===\n")
PP(HeadLine:match "123.4 Hello\nOooo\n")

-- (find-lpegfile "re.lua" "local function find (s, p, i)")
function myfind (pat)
    return lpeg.P{ lpeg.Cp() * pat * lpeg.Cp() + 1 * lpeg.V(1) }
  end
FindHeadLine = myfind(HeadLine)
PP(FindHeadLine:match(bigstr))


Line = re.compile "{[^\n]*}\n"
= Line
PPV(getmetatable(Line))
PPV(getmetatable(Line).__index)
TwoLines = Line * Line
TwoLines = Line * lpeg.B(Line)
PP(Line:match(bigstr))
PP(TwoLines:match(bigstr))





#####
#
# O'Reilly ebook: Creating Solid APIs with Lua
# 2017set10
#
#####

# «creating-solid-apis» (to ".creating-solid-apis")
# https://mail.google.com/mail/ca/u/0/#inbox/15e6e009da4c819b
# https://github.com/tylerneylon/APIsWithLua
# https://medium.com/@tylerneylon/make-your-code-scriptable-19be885dda69






rm -Rfv ~/usrc/lua-mode/
cd      ~/usrc/ && \
  git clone https://github.com/immerrr/lua-mode.git
tar -cvzf ~/tmp/lua-mode-git.tgz lua-mode/




http://lua-users.org/wiki/StringIndexing






# http://packages.debian.org/search?searchon=sourcenames&keywords=lua
# http://packages.debian.org/search?keywords=lua&searchon=names&suite=stable§ion=all
# (find-zsh "availabledebs | sort | grep lua")

http://kotisivu.dnainternet.net/askok/bin/lanes/index.html#comparisons

# Constant folding:
# (find-sh "echo 'return 2^8' | luac -l -")
# (find-sh "echo 'return 2^8' | luac51 -l -")

Etc (2006aug19):

http://matexhu.org/eurotex2006/lectures/pdftex/luatex-prelim-demo.pdf
http://lua-users.org/files/wiki_insecure/users/NormanRamsey/luahelp

http://lua-users.org/wiki/ExtensionProposal
http://www.inf.puc-rio.br/~roberto/pil2/
http://www.inf.puc-rio.br/~roberto/pil2/chapter15.pdf

2006dec30:

http://ds9a.nl/webcoding.html
http://www.nongnu.org/cinvoke/lua.html
http://lua-users.org/wiki/SimpleMatrix
http://lua-users.org/files/wiki_insecure/users/chill/Matrix.V.0.4.lua

File descriptors:   http://lua-users.org/lists/lua-l/2006-08/msg00284.html
Commas (aaron):     http://lua-users.org/lists/lua-l/2007-09/msg00230.html
Commas (edrx):      http://lua-users.org/lists/lua-l/2007-09/msg00231.html
Windows's CRT.dll:  http://lua-users.org/lists/lua-l/2007-11/msg00514.html
In-house languages: http://lua-users.org/lists/lua-l/2007-11/msg00526.html
IP-to-Country:      http://lua-users.org/lists/lua-l/2008-01/msg00465.html
Dirname/basename:   http://lua-users.org/lists/lua-l/2008-04/msg00025.html
  and from mathias.guijarro: os.pathsep = package.config:sub(1,1)
Help I'm new:       http://lua-users.org/lists/lua-l/2008-05/msg00175.html
Rewriting "print":  http://lua-users.org/lists/lua-l/2008-07/msg00188.html
Title case:         http://lua-users.org/lists/lua-l/2008-08/msg00353.html
IP mnemonics:       http://lua-users.org/lists/lua-l/2008-08/msg00666.html
Comprehensions:     http://lua-users.org/lists/lua-l/2008-09/msg00182.html




Scripting (luash):  http://lua-users.org/lists/lua-l/2008-09/msg00286.html
                    http://lua-users.org/lists/lua-l/2008-09/msg00300.html

-- From Natanael Copa on lua-l, 2008sep15
-- shell utility library
function quote(s)
    -- complement what doesn't need quotes
    local quote_me = "[^%w%+%-%=%@%_%/]"
    if s == nil then return nil end
    if s:find(quote_me) or s == '' then
      return "\'"..string.gsub(s, "\'", "\'\"\'\"\'").."'"
    else
      return s
    end
  end

function execv(...)
    local args = {}
    for _,i in ipairs{...} do table.insert(args, quote(i)) end
    return os.execute(table.concat(args, " "))
  end

function capture(cmd)
    local p = io.popen(cmd)
    if p == nil then return nil end
    local ret = p:read("*all")
    p:close()
    return ret
  end
                      
# Luashell:
# http://ztact.com/software/Luashell
# http://ztact.com/software/pozix.c
# http://ztact.com/files/
# http://ztact.com/files/src/ztact-lua/
# http://ztact.com/files/downloads/ztact-lua-20080407.2123.zip


# http://www.cowlark.com/objective-lua/
# http://www.cowlark.com/objective-lua/olua-0.0.1.tar.bz2
# http://www.reddit.com/r/programming/comments/9r1r3/objective_lua_now_you_can_mix_lua_and_smalltalk/



http://lua-users.org/wiki/UnofficialFaqDiscussion

http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.1/demo.tar.gz
http://software.schmorp.de/pkg/libev.html
http://twistedmatrix.com/
http://lists.schmorp.de/pipermail/libev/

http://www.inf.puc-rio.br/~roberto/docs/ry08-05.pdf
http://luaforge.net/frs/download.php/3955/luaproc.tgz

http://lua-users.org/lists/lua-l/2009-06/msg00611.html
http://article.gmane.org/gmane.comp.lang.lua.general/55735

Strict 'struct' pattern:
http://lua-users.org/lists/lua-l/2009-08/msg00142.html
http://lua-users.org/lists/lua-l/2009-08/msg00214.html

http://www.lua.org/doc/jai2009.pdf
http://batbytes.com/luafaq

http://www.cons.org/cracauer/sigint.html
What you can do is simply use pcall, and check that the error message
is "interrupted!".



http://trylua.org/
It's in the same vain as tryruby.org and the like. It will remember the
state of your session until the next browser reload.

CliDebugger:
http://luaforge.net/frs/?group_id=228
http://luaforge.net/frs/download.php/2498/debugger.lua

Announced on lua-l on 2011jun09:
http://stevedonovan.github.com/winapi/
http://stevedonovan.github.com/winapi/api.html

http://smbolton.com/lua/lbitlib-5.2.0-beta-rc1-backport3.c
http://loop.luaforge.net/library/compiler/Expression.html
http://lua-users.org/wiki/ListComprehensions
http://luaforge.net/projects/lcurses

Hyperbananas:
http://lua-users.org/lists/lua-l/2011-08/msg00207.html

My message on return vs return nil:
http://lua-users.org/lists/lua-l/2011-09/msg00301.html

http://luakit.org/projects/luakit/
http://packages.debian.org/luakit
http://packages.debian.org/sid/luakit
http://awesome.naquadah.org/

LuaRocks and GNU autotools:
http://article.gmane.org/gmane.comp.lang.lua.general/83600

http://lua-users.org/wiki/VarargTheSecondClassCitizen

# (find-lua52manualw3m "#3.3.4" "goto")

http://www.reddit.com/comments/63hth/ask_reddit_which_oss_codebases_out_there_are_so/c02pxbp
http://stevedonovan.github.com/lua-5.1.4/

Small is Beautiful:
http://lambda-the-ultimate.org/node/3894
http://www.stanford.edu/class/ee380/Abstracts/100310-slides.pdf

lpeg

http://www.tset.de/dbghelper/
http://cgit.gitano.org.uk/supple.git

A good example to look at is LuaSocket [1], where 'socket' is a Lua
module that builds on the undocumented "internal" C module,
'socket.core'.

[1] http://w3.impa.br/~diego/software/luasocket/

# From Dirk Laurie on lua-l, 2012nov14/2012nov15:
a={}; a[-0]=false; a[0]=true; for k,v in pairs(a) do print(k,v) end
  -->  -0  true

http://lua-users.org/wiki/CustomOperators

http://notebook.kulchenko.com/mt/mt-search.cgi?blog_id=2&tag=lua&limit=20

http://www.inf.puc-rio.br/~roberto/struct/ 

> TID3 = record
> signature: array[0..2] of char;
> title, artist, album: array[0..29] of char;
> year: array[0..3] of char;
> comment: array[0..29] of char;
> genre: byte;
> end;
>
> My first difficult is: how to represent a Lua 128 bytes structure like that.
> And how can I read the last 128 bytes of a file and attibutes it to a
> structure, probably a table, with this fields, sized with the given
> values?

function subl(s,i,l) return i+l,s:sub(i,i+l-1) end

f = io.open("foo.mp3","rb")
f:seek("end",-128)
h = f:read(128)
f:close()
t = {}
i = 1
i,t.signature   = subl(h,i,3)
i,t.title       = subl(h,i,30)
i,t.artist      = subl(h,i,30)
i,t.album       = subl(h,i,30)
i,t.year        = subl(h,i,4)
i,t.comment     = subl(h,i,30)
i,t.genre       = subl(h,i,1)


http://www.h-online.com/open/news/item/Wikimedia-adopts-Lua-for-page-generation-1825268.html
https://blog.wikimedia.org/2013/03/14/what-lua-scripting-means-wikimedia-open-source/

http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
http://web.cse.msu.edu/~cse320/Documents/FloatingPoint.pdf



> P.S.: is there a smarter way to get the link to the online archived
> version of a lua-l message?

You can query by message-id. Use this form:
 +Message-ID: <20130725151210.GA22303@magritte.tecgraf.puc-rio.br>



Terra:
http://terralang.org/
http://terralang.org/publications.html

http://www.dcc.ufrj.br/~fabiom/lua/


Even if you didn't have sleep. You can just use select with empty sets :)
    require "socket".select(nil,nil,0.5)

Or using SIP:

> res = {}
> = sip.match('Local Socket: $S{addr}..$i{port}',p,res)
true
> = res.port
750
> = res.addr

2014mar06 Typed Lua:
> [slides] <https://www.dropbox.com/s/8mfvnzagx2gixdb/luawshop13-fleutot.pptx>
> [notes] <https://github.com/fab13n/metalua/blob/tilo/src/tilo/readme.md>
> [video]<http://2013.capitoledulibre.org/conferences/lua-workshop/towards-practical-type-checking-for-lua.html>


# (find-es "console" "ansi.lua")


http://lua-users.org/lists/lua-l/2014-07/msg00174.html Horizon problem

https://github.com/pkulchenko/serpent#sorting
http://notebook.kulchenko.com/algorithms/alphanumeric-natural-sorting-for-humans-in-lua

On Thu, Jul 31, 2014 at 2:23 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
> What I have done in some of my modules is to make them
> return two values. Then `require "mymod"` only accesses the
> public part, but `mymod, private = dofile"mymod.lua"` also
> returns a table containing some local functions, cached
> while they were visible.


http://lua-users.org/lists/lua-l/2014-08/msg00492.html next and inext

https://groups.google.com/forum/#!forum/lua-table-semantics

http://www.youtube.com/watch?v=-rMC2s0s-zA Textadept - Behind the Scenes
https://github.com/dlaurie/lua-notes/blob/master/lpeg-brief.txt
http://lua-users.org/wiki/LpegRecipes

http://lua-users.org/lists/lua-l/2014-08/msg00529.html Narrative / conversational prose
http://lua-users.org/lists/lua-l/2014-05/msg00681.html the parsing room
http://lua-users.org/lists/lua-l/2014-08/msg00632.html gsub in lpeg
http://lua-users.org/lists/lua-l/2016-06/msg00277.html "n" field to be avoided at all costs

Sile:
Message-ID: <5404930A.20506@simon-cozens.org>

http://www.linuxfromscratch.org/~krejzi/blfs-git/general/lua.html
http://www.linuxfromscratch.org/patches/blfs/svn/lua-5.2.3-shared_library-1.patch
https://lua-toolbox.com/
http://stackoverflow.com/questions/tagged/lua
http://xyproblem.info/

http://hg.piratery.net/losix/get/tip.tar.gz
# (find-fline "$S/http/hg.piratery.net/losix/get/tip.tar.gz")

http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man7/patterns.7

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
which lua5.2
export LUA_INIT=
lua5.2
  PP()
= require "posix"

* (eepitch-lua52)
* (eepitch-kill)
* (eepitch-lua52)
table.sort({1,2,3,4,5}, function() return true end)
-- stdin:1: invalid order function for sorting

http://lua-users.org/lists/lua-l/2015-04/msg00429.html converting Lua C sources to HTML
http://lua-users.org/lists/lua-l/2015-04/msg00033.html table of metamethods
http://lua-users.org/lists/lua-l/2015-04/msg00101.html
http://linuxcommand.org/man_pages/ssconvert1.html
https://github.com/Yonaba/Algorithm-Implementations
http://sano.luaforge.net/
http://lua-users.org/lists/lua-l/2015-04/msg00341.html
http://lua.space/
http://oberon00.github.io/lua-cfuncidx/
https://github.com/arcapos/luaunix
http://lua-users.org/lists/lua-l/2016-05/msg00405.html try-catch
http://the-ravi-programming-language.readthedocs.io/en/latest/lua_bytecode_reference.html
https://aperezdc.github.io/lua-itertools/
http://blog.klipse.tech/lua/2017/03/19/blog-lua.html ***
http://lua-users.org/lists/lua-l/2017-04/msg00412.html Lua-y lambda syntax using ltokenp
http://lua-users.org/wiki/LuaStyleGuide
https://github.com/Olivine-Labs/lua-style-guide
https://github.com/zaki/lua-style-guide
https://github.com/ykst/lua-style-guide
http://lua.space/webdev/why-we-rewrote-lua-in-js
http://druidstone-game.com/object-decomposition-druidstone
http://leafo.net/guides/parsing-expression-grammars.html lpeg
http://the-ravi-programming-language.readthedocs.io/en/latest/lua-introduction.html





#  Local Variables:
#  coding:               raw-text-unix
#  ee-delimiter-hash:    "\n#*\n"
#  ee-delimiter-percent: "\n%*\n"
#  ee-anchor-format:     "«%s»"
#  modes: (fundamental-mode lua-mode c-mode)
#  End: