Targeting a specific occurence in a string and replacing it - replace

I have a string with multiple / in it and I am trying to convert this string in to LaTeX code. Basically (a)/(b) becomes \\dfrac{a}{b}.
The difficulty is that (a) and/or (b) could contain other /.
To respect the parentheses balancing, I would like to replace the / from left to right, and replacing them accordingly to what it around. I made a try but I don't know how target a specific / and replace. using position and length parameters seems to be very complicated.
function ToFrac (s)
while s:find ("/") ~= nil
do
-- Replace : \dfrac{}{}/() -> \dfrac{\dfrac...}{}
if ( s:find ( '\\dfrac%b{}%b{}/%b()' , j ) ~= nil )
then
x,y,num,den = s:find( '(\\dfrac%b{}%b{})/(%b())' )
den = den:gsub( '.(.+).' , '%1' )
s = s:gsub( '(\\dfrac%b{}%b{})/(%b())',
"\\dfrac{"..num.."}{"..den.."}" , 1 )
end
print ('### -- ', s)
-- Replace : ()/\dfrac{}{} -> \dfrac[}]{\dfrac...}
if ( s:find ( '(%b()/\\dfrac%b{}%b{}' ) ~= nil )
then
x,y,num,den = s:find( '((%b())/(\\dfrac%b{}%b{})' )
num = num:gsub( '.(.+).' , '%1' )
s = s:gsub( '((%b())/()\\dfrac%b{}%b{})',
"\\dfrac{"..num.."}{"..den.."}" , 1 )
end
print ('### -- ', s)
-- Replace : ()/() -> \dfrac{}{}
if ( s:find ( '%b()/%b()' , 1 ) ~= nil )
then
x,y,num,den = s:find( '(%b())/(%b())' )
num = num:gsub( '.(.+).' , '%1' )
den = den:gsub( '.(.+).' , '%1' )
s = s:gsub( '(%b())/(%b())',
"\\dfrac{"..num.."}{"..den.."}" , 1 )
Done = true
end
print ('### -- ', s)
end -- while
return (s)
end
s = "((a)/(b))/(c)"
print (s, ToFrac(s))
s = "(a)/((b)/(c))"
print (s, ToFrac(s))
s = "(a)/(b)/(c)/(d))"
print (s, ToFrac(s))
s = "((a)/(b))/((c)/(d))"
print (s, ToFrac(s))

Amended version of rpattiso's idea:
function to_frac(expr)
local t
return expr == '' and '' or (expr..'()'):gsub('(.-)(%b())',
function(prefix, subexpr)
local replace_with = ''
if not prefix:find'^%s*/%s*$' then
t, replace_with = {}, (not t and ''
or t[2] and '\\dfrac{'..t[1]..'}{'..t[2]..'}'
or '('..t[1]..')')..prefix
elseif t[2] then
t = {'\\dfrac{'..t[1]..'}{'..t[2]..'}'}
end
table.insert(t, to_frac(subexpr:sub(2,-2)))
return replace_with
end
)
end
print(to_frac' (a )/((b) / (c))') --> \dfrac{a }{\dfrac{b}{c}}
print(to_frac'((a)/((b)/(c)))/(e)') --> \dfrac{\dfrac{a}{\dfrac{b}{c}}}{e}
print(to_frac'(a)/(b)/(c)/(d)') --> \dfrac{\dfrac{\dfrac{a}{b}}{c}}{d}

The 'replace' argument of string.gsub can be a function.
Using that function, you can apply the substitution recursively to the numerator and denominator and build the result that way. string.sub can be used to remove the parentheses from the numerator and denominator.
function to_frac(expr)
return (expr:gsub('%s*(%b())%s*/%s*(%b())%s*',
function(num, denom)
return '\\dfrac{'..to_frac(num:sub(2,-2))..'}{'
..to_frac(denom:sub(2,-2))..'}'
end))
end
expr = ' (a )/((b) / (c))' -- \dfrac{a }{\dfrac{b}{c}}
print(to_frac(expr))
expr = '((a)/((b)/(c)))/(e)' -->\dfrac{\dfrac{a}{\dfrac{b}{c}}}{e}
print(to_frac(expr))
If you want to go beyond using parentheses for delimiting arguments and obey precedence rules, then look into LPeg.

Related

String trimming for output format

This is my code:
Program String_Triming
Implicit none
Open(15, File = 'Output.txt')
Write(15,'(A,1x,"j",1x,A)') Ispis(20.45),Ispis(20.45)
Write(15,'(A,1x,"j",1x,A)') Ispis(-20.45),Ispis(-20.45)
Close(15)
Contains
Function Ispis ( Deg ) result ( Str )
Real,intent(in)::Deg
Character(len=16):: Str
If ( Deg > 0 ) then
Write(Str,'(F0.3)') 1000.0 + Deg
Str = Str(2:)
Else
Write(Str,'(F8.3)') 1000.0 + abs(Deg)
Write(Str,'("-",A)') Str(3:)
End If
End Function Ispis
End program String_Triming
The content of Output.txt file is:
020.450 j 020.450
-20.450 j -20.450
The result I want to get from this code is:
020.450 j 020.450
-20.450 j -20.450
How do I get that result? Is there way to trim the length of Str to Len=8 which is the length of 020.450?
It's not quite clear what you want. If all you want is to remove the spaces from the output file, why not just run it through sed instead of writing a Fortran Program:
$ cat Output.txt
020.450 j 020.450
-20.450 j -20.450
$ sed -r 's/ +/ /g' Output.txt
020.450 j 020.450
-20.450 j -20.450
If you want to produce output like this in the first place, you could 'overwrite' the first three characters of str with an integer format. Something like this:
function Ispis(Deg) result(Str)
real, intent(in) :: Deg
character(len=7) :: Str
write(Str, '(F7.3)') Deg
if ( Deg < 0 ) then
write(Str(:3), '(I3.2)') int(Deg)
else
write(Str(:3), '(I3.3)') int(Deg)
end if
end function Ispis
note: the length of 020.450 is 7, not 8.
This is the solution for getting wanted result:
Program Main
Implicit none
Open(15,File='Output.txt')
Write(15,'(1x,a,1x,"j",1x,a,1x,"Juhu!")') Writing_01(67.45),Writing_01(-4.04)
Write(15,'(1x,a,1x,"j",1x,a,1x,"Juhu!")') Writing_02(67.45),Writing_02(-4.04)
Close(15)
Contains
Function Writing_01 ( Deg ) Result ( Str )
Real,intent(in) :: Deg
Character(:),allocatable :: Str
Character(len = 15 ) :: Str_temp
If ( int( Deg ) > 0 ) then
Write(Str_temp , '(F0.2)' ) 100000.0 + Deg
Str_temp = Str_temp(2:)
Else
Write(Str_temp, '(F0.2)' ) 100000.0 + abs(Deg)
Str_temp = "-"//Str_temp(3:)
Endif
Str = trim ( adjustl ( Str_temp ))
End Function Writing_01
Function Writing_02 ( Deg ) Result ( Str_temp )
Real,intent(in) :: Deg
Character(:),allocatable :: Str_temp
Character(len=1561) :: Form_02 , Res
If (int( Deg ) > 0 ) then
Form_02 = '(i5.5,f0.2)' ! allow a total of 4 leading zeros.
Else
Form_02 = '(i5.4,f0.2)' ! "-" sign takes up one space, so 3 leading zeros remain.
Endif
Write(Res , Form_02 ) int( Deg ), abs( Deg - int( Deg ) )
Str_temp = trim ( adjustl ( Res ))
End Function Writing_02
End program Main

How to parse an url and get query parameters in lua? [duplicate]

I have a URL and would like to parse its Parameter out of it, like:
function unescape (s)
s = string.gsub(s, "+", " ")
s = string.gsub(s, "%%(%x%x)", function (h)
return string.char(tonumber(h, 16))
end)
return s
end
function parseurl (s,param)
for k, v in string.gmatch( s, "([^&=?]+)=([^&=?]+)" ) do
--t[k] = v
if k == param then
--print (k.." "..v)
return unescape(v)
end
end
s = "http://www.page.com/link.php uname=Hans+Testmann&uemail=myemail%40gmail.com&utext=Now+this+is+working+great.%0D%0A++&mdt=1#&mydays:themeupload"s
Than I would call it and get Results like after -->
parseurl (s, "uname") --> "Hans Testmann"
parseurl (s, "uemail") --> "myemail#gmail.com"
parseurl (s, "utext") --> "Now this is working great"
I already fixed a lot and seems to work,
but could you look how its possible to improve?
I would return all parameters in a table and use like so:
function urldecode(s)
s = s:gsub('+', ' ')
:gsub('%%(%x%x)', function(h)
return string.char(tonumber(h, 16))
end)
return s
end
function parseurl(s)
s = s:match('%s+(.+)')
local ans = {}
for k,v in s:gmatch('([^&=?]-)=([^&=?]+)' ) do
ans[ k ] = urldecode(v)
end
return ans
end
t = parseurl(s)
print(t.uname ) --> 'Hans Testmann'
print(t.uemail) --> 'myemail#gmail.com'
print(t.utext ) --> 'Now this is working great'

How to read a mixed text file and extract numbers only

I need to read the output of one of my simulators and store the values. the file name is forces.dat and contains a similar thing as the following:
# Forces
# CofR : (4.750000e-01 3.500000e-02 2.000000e-02)
# Time forces(pressure viscous porous) moment(pressure viscous porous)
2.633022e-02 ((6.268858e-02 -1.468850e+01 1.542745e-20) (1.000906e-03 8.405854e-06 -5.657665e-17) (0.000000e+00 0.000000e+00 0.000000e+00)) ((-8.779466e-18 8.442993e-19 -3.225599e-03) (-2.082489e-18 4.435609e-18 -1.572485e-03) (0.000000e+00 0.000000e+00 0.000000e+00))
8.095238e-02 ((1.781333e-01 -1.468455e+01 -3.545427e-19) (2.362118e-03 2.014609e-05 1.691584e-16) (0.000000e+00 0.000000e+00 0.000000e+00)) ((-3.344781e-18 -5.448339e-19 2.227502e-02) (5.092628e-18 -3.538718e-18 -1.203074e-03) (0.000000e+00 0.000000e+00 0.000000e+00))
1.600000e-01 ((3.204471e-01 -1.467482e+01 -4.599174e-18) (6.936764e-03 1.303800e-04 4.836650e-17) (0.000000e+00 0.000000e+00 0.000000e+00)) ((-1.123589e-17 -4.344967e-19 5.591623e-02) (1.532415e-18 -1.345592e-18 -9.550750e-04) (0.000000e+00 0.000000e+00 0.000000e+00))
I want to know how should I write a Fortran subroutine to ignore the first 3 lines and then read the number of next lines and then the values of each line.
You can use this snippet which will keep a track of line numbers. Based on your requirement and nature of file, you can get the values of respective lines and can do the required.
string CurrentLine;
int LastLineNumber;
void NextLine()
{
// using will make sure the file is closed
using(System.IO.StreamReader file = new System.IO.StreamReader ("c:\\forces.dat"))
{
// Skip lines
for (int i=0;i<LastLineNumber;++i)
file.ReadLine();
// Store your line
CurrentLine = file.ReadLine();
LastLineNumber++;
}
}
In the above code, inside for loop you can put in your logic of file processing based on the lines you want to read.
Although I think it is easier to preprocess the file by some command-line tool (e.g. sed -e 's/(/ /g' -e 's/)/ /g' input.dat), we can also use Fortran directly by reading each line into a long character string and removing all the unnecessary parentheses:
program main
implicit none
integer, parameter :: mxline = 5000 !! choose appropriately
integer i, ios, finp, nl
character(500) str
real, save :: time( mxline )
real, dimension( 3, mxline ), save :: &
frc_pres, frc_visc, frc_poro, &
mom_pres, mom_visc, mom_poro
finp = 10
open( finp, file="input.dat", status="old" )
nl = 0
do
read( finp, "(a)", iostat=ios ) str
if ( ios /= 0 ) exit
str = trim( adjustL( str ) )
!! Skip comment or blank lines.
if ( str(1:1) == "#" .or. str == "" ) cycle
!! Replace parentheses with space.
do i = 1, len_trim( str )
if ( str(i:i) == "(" .or. str(i:i) == ")" ) str(i:i) = " "
enddo
!! Read data from the string.
nl = nl + 1
read( str, * ) time( nl ), &
frc_pres( :, nl ), frc_visc( :, nl ), frc_poro( :, nl ), &
mom_pres( :, nl ), mom_visc( :, nl ), mom_poro( :, nl )
enddo
close( finp )
!! Check.
do i = 1, nl
print *
print *, "time = ", time( i )
print *, "frc_pres = ", frc_pres( :, i )
print *, "frc_visc = ", frc_visc( :, i )
print *, "frc_poro = ", frc_poro( :, i )
print *, "mom_pres = ", mom_pres( :, i )
print *, "mom_visc = ", mom_visc( :, i )
print *, "mom_poro = ", mom_poro( :, i )
enddo
end program
If the data values can become very large (say, 1.0e100), please consider using double-precision reals so as not to loose necessary precision.

Matching enclosing characters Python

So I am trying to split characters a certain way.
If I provide this string:
text (text (adsf (asdfasdfjkl) asdfjlkasdjf) stuff) (morestuff stuff)
I want it to split it into:
['text', '(text (adsf (asdfasdfjkl) asdfjlkasdjf) stuff)', '(morestuff stuff)']
Code I had:
def pair_char(left, right, start, text, exclusive=False, verbose=False):
package = []
for e, c in enumerate(text):
left_c = right_c = 0
if text[e] == left:
left_c += 1
marker = start = e
while text[marker+1] != right or left_c > right_c:
marker += 1
if verbose:
print left_c, right_c, text[marker], left, right, text[marker]==left, text[marker]==right
if marker+1 >= len(text):
break
if text[marker] == left_c:
print "left_c"
left_c += 1
if text[marker] == right_c:
print "right_c"
right_c += 1
end = marker
if exclusive:
package.append(text[start+1:end])
else:
package.append(text[start:end+1])
e = end
package = "".join(package)
return package
Any suggestions?

Lua - Reflection - Get list of functions/fields on an object?

I'm new to Lua and dealing with Lua as a scripting language in an alpha release of a program. The developer is unresponsive and I need to get a list of functions provided by some C++ objects which are accessible from the Lua code.
Is there any easy way to see what fields and functions these objects expose?
In Lua, to view the members of a object, you can use:
for key,value in pairs(o) do
print("found member " .. key);
end
Unfortunately I don't know if this will work for objects imported from C++.
If allowed in the environment, looking at the metatable of the exported C++ object can help:
for key,value in pairs(getmetatable(o)) do
print(key, value)
end
Print all the globals:
-- globals.lua
-- show all global variables
local seen={}
function dump(t,i)
seen[t]=true
local s={}
local n=0
for k in pairs(t) do
n=n+1 s[n]=k
end
table.sort(s)
for k,v in ipairs(s) do
print(i,v)
v=t[v]
if type(v)=="table" and not seen[v] then
dump(v,i.."\t")
end
end
end
dump(_G,"")
source: http://www.lua.org/cgi-bin/demo
Output:
_G
_VERSION
assert
bit32
arshift
band
bnot
bor
btest
bxor
extract
lrotate
lshift
replace
rrotate
rshift
collectgarbage
coroutine
create
isyieldable
resume
running
status
wrap
yield
debug
gethook
getinfo
getlocal
getmetatable
getupvalue
getuservalue
sethook
setlocal
setmetatable
setupvalue
setuservalue
traceback
upvalueid
upvaluejoin
dump
error
getmetatable
io
write
ipairs
load
math
abs
acos
asin
atan
atan2
ceil
cos
cosh
deg
exp
floor
fmod
frexp
huge
ldexp
log
log10
max
maxinteger
min
mininteger
modf
pi
pow
rad
random
randomseed
sin
sinh
sqrt
tan
tanh
tointeger
type
ult
next
os
clock
date
difftime
exit
setlocale
time
pairs
pcall
print
rawequal
rawget
rawlen
rawset
select
setmetatable
string
byte
char
dump
find
format
gmatch
gsub
len
lower
match
pack
packsize
rep
reverse
sub
unpack
upper
table
concat
insert
move
pack
remove
sort
unpack
tonumber
tostring
type
utf8
char
charpattern
codepoint
codes
len
offset
xpcall
Something along the same vein as the answer Mr Stinky gave but a whole lot more information.
I made the below code originally for a running from a web server but have added the capability to run on lua for windows
on a web server options are passed in query string ?loadmodules=no&module=_G
in program form options are passed on command line functs loadmodules no module _G
if run with no arguments all modules in pkgpath are loaded and parsed
#!/usr/bin/lua
--------------------------------------------------------------------
--|Functs.lua load available modules parse tables give write to HTML|
--|Table Of Contents, modules, available functions, strings etc.. |
--------------------------------------------------------------------
-- CONFIGURE----------------------------------------------------------------------------------------
local sPkgPath = "/usr/lib/lua" --look here for modules to load in addition to the intrinsic ones
local sWpkgPath = "C:\\Program Files (x86)\\Lua\\5.1\\lua\\" --package path for windows
local sURLsearch = "http://pgl.yoyo.org/luai/i/" --for lua standard functions search this site
local iMaxStr = 1024 -- maximum characters in a string printed to HTML table
local sFileOut = "functs.html"
----------------------------------------------------------------------------------------------------
local tQuery = {} --key,val pairs of arguments
local sQuery = "" --string of arguments ex:'?modload=no&module=_G.math...'
local sResults = "" --Results of each step through
local sEnv = "web" --running on a web server?
----------------------------------------------------------------------------------------------------
----------------------------FUNCTIONS START----------------------------------------------
local function a2m_m2a(addr_member)
--turns members into addresses; addresses back into members
return addr_member
end
local function PrRes(sVal)
--cats results strings
sResults = sResults .. sVal
end
local function errorHandler( err )
PrRes(" ERROR:" .. err .. " ")
--print(debug.traceback())
end
local function putOutput(tData, iCt)
--keys are integer indices, values to iCt written, if iCt = nil whole table written
for k, v in ipairs(tData) do
if iCt == nil or k <= iCt then
io.write (v) --write to std out could be changed here, or as below we change stdout file
end
end
end
local function parse_url(s)
--http://www.flashair-developers.com/en/support/forum/#/discussion/880/getting-query-string-parameters-from-an-http-request-in-lua/
--splits on '=' and '&' puts argument string into named keys with value [Key1] = (val1)&[Key2] = (val2)
--ex: Key1=va1&Key2=val2
local ans = {[0]=""}
----FUNCTIONS for parse_url -----------------------------------------------------
local function decode(s)
s = s:gsub('+', ' ')
s = s:gsub('%%(%x%x)', function(h) return string.char(tonumber(h, 16)) end)
return s
end
----END FUNCTIONS for parse_url --------------------------------------------------
if s == nil then return ans end
--s = s:match('%s+(.+)')
for k,v in s:gmatch('([^&=]+)=([^&=]*)&?' ) do
--2 capture groups all chars (not '&' or '=') '=' all chars (not '&' or '=') followed by '' or '&' or '?'
ans[ k ] = decode(v)
end
return ans
end
local function tableByName(tName)
--find the longest match possible to an actual table
--Name comes in as (table) tName.var so we can pass back out the name found PITA
--returns the table found (key and value)
local ld = {}
local sMatch = ""
local kMatch = nil
local vMatch = nil
----FUNCTIONS for tableByName -----------------------------------------------------
local function search4Str(n, k, v)
local sKey = tostring(k)
if string.find (n, sKey,1,true) then
if sKey:len() > sMatch:len() then sMatch = sKey kMatch = k vMatch = v end
--find the longest match we can
end
end
----END FUNCTIONS for tableByName -------------------------------------------------
if tName.val ~= nil and tName.val ~= "" then
for k, v in pairs(_G) do --_G check both since some tables are only in _G or package.loaded
search4Str(tName.val, k, v)
end
for k, v in pairs(package.loaded) do --package.loaded
search4Str(tName.val, k, v)
end
if not string.find (sMatch, "_G",1,true) then sMatch = "_G." .. sMatch end -- put the root _G in if not exist
if kMatch and vMatch then ld[kMatch] = vMatch tName.val = sMatch return ld end
end
tName.val = "_G"
return package.loaded --Not Found return default
end
local function get_common_branches(t, tRet)
--load t 'names(values)' into keys
--strip off long paths then iterate value if it exists
--local tRet={}
local sBranch = ""
local tName
for k in pairs(t) do
tName={["val"]=k}
tableByName(tName)
sBranch = tName.val
if tRet[sBranch] == nil then
tRet[sBranch] = 1 --first instance of this branch
else
tRet[sBranch] = tRet[sBranch] + 1
end
end
end
local function pairsByPairs (t, tkSorted)
--tkSorted should be an already sorted (i)table with t[keys] in the values
--https://www.lua.org/pil/19.3.html
--!!Note: table sort default function does not like numbers as [KEY]!!
--see *sortbyKeys*cmp_alphanum*
--for n in pairs(t) do table.insert(kSorted, n) end
--table.sort(kSorted, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if tkSorted[i] == nil then return nil
else return tkSorted[i], t[tkSorted[i]]
end
end
return iter
end
local function sortbyKeys(t, tkSorted)
--loads keys of (t) into values of tkSorted
--and then sorts them
--tkSorted has integer keys (see ipairs)
----FUNCTIONS for sortByKeys -------------
local cmp_alphanum = function (op1, op2)
local type1= type(op1)
local type2 = type(op2)
if type1 ~= type2 then
return type1 < type2
else
return op1 < op2
end
end
----END FUNCTIONS for sortByKeys ---------
for n in pairs(t) do table.insert(tkSorted, n) end
table.sort(tkSorted, cmp_alphanum)--table.sort(tkSorted)
end
local function load_modules(sPkgRoot, sWinPkgRoot)
--attempt to load all found modules
--Modules may depend on other modules
--Supresses print, os.exit, rawset
--Ignores *.luac
PrRes("Functions Suspended, ")
local orig ={osexit = _G.os.exit, print = _G.print, rawset = _G.rawset} --save original functions for later restoration
_G.rawset = function(t, i, v) --orig.print ("rawset!")
if _G[i] == v then
orig.rawset(t,i,"_G["..tostring(i).."] !DUP!") --Don't allow global table to be copied
else
orig.rawset(t,i,v)
end
end
_G.os.exit = function() error(999) end --don't exit whole program just this function
_G.print = function()end --don't print
local st = io.popen("find "..sPkgRoot.." -type f -iname '*.so' -o -type f -iname '*.lua'" .." 2> nul")
if not st:read(0) then --find didn't work try windows dir instead
st = io.popen("dir /b /s " .."\""..sWinPkgRoot.."\\*.lua\" " .. "\""..sWinPkgRoot.."\\*.so\" " ) --simple output, subdir
end
if st:read(0) then
for module in st:lines() do
if (module) then
if not string.find (module, ".luac", 1, true) then --don't load precompiled code
local ok, res = pcall(loadfile(module))--protected call
end
end
end
end
_G.os.exit = orig.osexit
_G.print = orig.print
_G.rawset = orig.rawset
PrRes("Functions Restored, ")
end
local function dtTag(sType)
--convert named type; 'number'.. to short type '[n]...'
--if '?' supplied print out datatype key; number = [n]...
local retType = "?"
local typ = {
["nil"] = "nil",
["boolean"] = "b",
["number"] = "n",
["string"] = "s",
["userdata"] = "u",
["function"] = "f",
["thread"] = "thr",
["table"] = "t"
}
if sType == "?" then retType = "Datatypes: " end
for k,v in pairs(typ) do
if sType == k then
retType = v break
elseif (sType == "?") then
retType = retType .. " [" ..v.. "] = " .. k
end
end
return " [" ..retType.. "] "
end
local function dump_Tables(tBase,sFunc, tSeen, tRet)
--Based on: http://www.lua.org/cgi-bin/demo?globals
--Recurse through tBase tables copying all found Tables
local sSep=""
local ld={}
if sFunc ~= "" then sSep = "." end
for k, v in pairs(tBase) do
k = tostring(k)
if k ~= "loaded" and type(v) == "table" and not tSeen[v] then
tSeen[v]=sFunc
tRet[sFunc..sSep .. k] = a2m_m2a(v) --place all keys into ld[i]=value
dump_Tables(v, sFunc .. sSep .. k, tSeen, tRet)
end
end
--print("tables dumped")
end
local function dump_Functions(tBase)
--Based on: http://www.lua.org/cgi-bin/demo?globals
--We already recursed through tBase copying all found tables
--we look up the table by name and then (ab)use a2m_m2a() to load the address
--after finding the table by address in tBase we will put the table address of tFuncs in its place
for k,v in pairs(tBase) do
local tTable = a2m_m2a(v)
local tFuncs = {}
--print(type(tTable))
for key, val in pairs(tTable) do
if key ~= "loaded" then
tFuncs[dtTag(type(val)) .. tostring(key) ]= val --put the name and value in our tFuncs table
end
end
tBase[k] = a2m_m2a(tFuncs) -- copy the address back to tBase
end
--print("functions dumped")
end
local function html_Table(tBase, tkSorted, sId, fHeader, sTitle, iCols, fCellCond, fCell, fFooter, fOut)
--[[Prints HTML <table>
tBase, the table of items you want in your table [key] contains the cell data
tkSorted, the key sorted values of tBase (tkSorted keys are (i) based (see: ipairs)
sID, ID of div tag
fHeader, function returning <DIV></DIV>
sTitle, title of the table
iCols, number of cells wide
fCellCond, if return (TRUE) cell is displayed, fCellCond(k, v, n, iCells, i)
fCell, function returning contents of cell
fFooter, function returning tags at the end of the </table>
fOut, function to print the table[integer]=HTML_DATA based output
--]]
local oTbl={}
local i = 1
local strName=""
local iCells = 0
local n = 0 --counts columns
oTbl[i]=fHeader(sId,sTitle)
i = i + 1 oTbl[i] = "<table><tr><th colspan='"..iCols.."'>"..sTitle.."</th></tr>\r\n"
for k, v in pairsByPairs(tBase,tkSorted ) do
strName= tostring(k)
if fCellCond(k, v, n, iCells, i) then
if n == 0 then
i = i + 1 oTbl[i] = "\t<tr>\r\n"
end
n = n + 1 i = i + 1 iCells = iCells + 1
oTbl[i] = "\t\t"..fCell(strName, v, sTitle).."\r\n"
if n >= iCols then
n = 0
i = i + 1
oTbl[i] = "\t</tr>\r\n"
end
fOut(oTbl, i)
i = 0
end
end
if n ~= 0 then
i = i + 1 oTbl[i] = "\t</tr>\r\n"
end
i = i + 1 oTbl[i] = "</table>\r\n" .. fFooter(strName)
fOut(oTbl, i)
return iCells
end
local function html_function_tables(tBase, tkSortTbase, fOut, iCols)
--print a table of functions for every module in tBase
local strName=""
local iCt = 0
local tFuncs = {}
local tkSorted = {}
----FUNCTIONS for Funct Html-----------------------------------------------------
local function fCellTrue(k)
--return tostring(k) == strName
return true
end
local function fTableCell(strName, value, sTitle)
local sHref = ""
local sType = type(value)
local sPkg = string.match (sTitle, ".+%p(%a+%P)")
local sVal = ""
--strName = tostring(strName)
if string.len(strName) > iMaxStr then
strName=string.sub(strName,1 , iMaxStr).."....." --Truncate strings longer than iMaxStr
end
if sPkg ~= nil and string.find (";debug;package;string;coroutine;io;math;os;table;", ";"..sPkg..";") then
sHref = "<a href='"..sURLsearch .. string.sub(strName,6) .. "'>?</a>" --remove [f] from beginning
end
if nil ~= string.find (";string;number;userdata;boolean;", sType, 1, true) then
sVal = tostring(value)
if string.len(sVal) > iMaxStr then
sVal=string.sub(sVal,1 , iMaxStr).."....." --Truncate strings longer than iMaxStr
end
return "</tr><td colspan='"..iCols.."'>".. sHref ..strName.." : "..sVal.."</td><tr>"
else
return "<td><a>"..strName.."</a>".. sHref .. "</td>"
end
end
local function fPageAnchor(sId, strTitle)
local sHref = ""
local sAddr = ""
local sModload = tQuery.modload
if not sModload then sModload = "" end
local sStyle = "'style='display:block;text-decoration: none"
if os.getenv("SERVER_NAME") and os.getenv("SCRIPT_NAME") then
sAddr = "http://"..os.getenv("SERVER_NAME") .."/".. os.getenv("SCRIPT_NAME") .."?modload=".. sModload
sHref="<a href='"..sAddr.."&module="..strTitle..sStyle.."'>" .."Module: " .. strTitle.. "</a>"
else
sHref = "Module: " .. strTitle
end
return "<div id='"..sId.."'style='color:#0000FF'><h3>"..sHref.."</h3></div>\r\n"
end
local function fPageFooter(strName)
return "<p><a href='#toc'>^</a></p><BR /><BR />"
end
----END FUNCTIONS for Funct Html--------------------------------------------------
for key, val in pairsByPairs(tBase, tkSortTbase) do
strName=tostring(key)
tkSorted = {}
tFuncs = a2m_m2a(val)
sortbyKeys(tFuncs, tkSorted)
iCt = iCt + html_Table(tFuncs,tkSorted, strName, fPageAnchor, strName, iCols, fCellTrue, fTableCell, fPageFooter, fOut)
end
return iCt
end
local function html_toc_tables(tBase, tkSortTbase, fOut, iCols)
local iCt = 0
----FUNCTIONS for TOC Html-----------------------------------------------------
local function fTableCell(strName)
return "<td><a href='#" .. strName .. "'style='display:block;text-decoration: none'>" .. strName.. "</a></td>"
end
local function fCellTrue()
return true
end
local function fFooter()
return "<BR /><b>" .. dtTag("?") .. "</b><BR /><BR /><BR /><BR /><BR /><BR />"
end
local function fPageAnchor(sId, strTitle)
return "<div id='"..sId.."'><p></p></div>\r\n"
end
----END FUNCTIONS for TOC Html--------------------------------------------------
iCt = html_Table(tBase, tkSortTbase, "toc", fPageAnchor, "* Modules Found * Lua Ver. ".._VERSION, iCols, fCellTrue, fTableCell, fFooter, fOut)
return iCt
end
local function main (sPackage)
local tSeen= {}
local tcBase = {}
local tkSortCbase = {}
local tMods= {}
local tkSortMods = {}
local iCtF = 0
if not sPackage then sPackage = "_G" end
putOutput( { --header for html document
[1] = "<!DOCTYPE html>\r\n<html><head>\r\n<style>\r\n",
[2] = "\ttable, th, td {border: 1px solid black;}\r\n",
[3] = "\ttable tr:nth-child(even) {background-color: #C4C4C4;}\r\n",
[4] = "\ttable tr:nth-child(odd) {background-color:#EFEFEF;}\r\n",
[5] = "</style>\r\n</head><body>\r\n"
} )
PrRes("Dump Tables: ")
xpcall( function()dump_Tables(tableByName({["val"] = sPackage}),"", tSeen, tMods) end , errorHandler )
tSeen = nil
PrRes("ok, ")
PrRes("Dump Functions: ")
xpcall( function()dump_Functions(tMods)end , errorHandler )
PrRes("ok, ")
PrRes("Common Branches: ")
get_common_branches(tMods, tcBase)
PrRes("ok, ")
PrRes("Sorting Branches: ")
sortbyKeys(tcBase, tkSortCbase)
sortbyKeys(tMods, tkSortMods)
PrRes("ok, ")
PrRes("Print TOC: ")
iCtF = html_toc_tables(tcBase, tkSortCbase, putOutput, 3)
tcBase= nil tkSortCbase= nil
PrRes(iCtF .." ok, ")
PrRes("Print Functions: ")
iCtF = html_function_tables(tMods, tkSortMods, putOutput, 6)
PrRes(iCtF .." ok, ")
end
----------------------------FUNCTIONS END--------------------------------------------------
if os.getenv("SERVER_NAME") == nil then
sEnv="other"
else --sEnv == web
--Send response header as soon as we load
io.write ("Status: 200 OK\r\nKeep-Alive: timeout=60\r\nContent-Type:text/html\r\nLast-Modified:Sun, 11 Jan 2099 01:01:99 GMT\r\n\r\n") -- end of response)
end
if sQuery == "" then --load arguments from query string if web; or arg[] if not
if sEnv == "web" then
sQuery = os.getenv("QUERY_STRING")
else --Load arguments from arg[] list arg[1]=arg[2]&arg[3]=arg[4]&..
for k,v in pairs({...}) do
sQuery = sQuery .. v
if math.fmod (k, 2) == 0 then
sQuery = sQuery .. "&"
else
sQuery = sQuery .. "="
end
end
end
end
tQuery = parse_url(sQuery)
--[[print(sQuery)
for k,v in pairs(tQuery) do
print ("[", k ,"]=", v)
end]]
if sQuery ~= "modloadno" and tQuery.modload ~= "no" then
PrRes("Load Modules: ")
xpcall( function()load_modules(sPkgPath,sWpkgPath)end, errorHandler )
--load_modules(sPkgPath)
PrRes("ok, ")
end
PrRes("Main; ")
if sEnv ~= "web" then
print("Fileout: " .. sFileOut)
io.output(sFileOut)
end
local ok, res = pcall(main,tQuery.module)
if not ok then
if sEnv ~= "web" then
print("Status: 500 Internal Server Error\r\nContent-Type: text/plain\r\n\r\n" .. res .. "\r\n")
else
print("Error: " .. res)
end
end
PrRes("DONE")
io.write("<p> Query: " .. sQuery .. ";; " .. sResults .."</p>")
Sample Output