lua-users home
lua-l archive

Re: Lua Cookbook

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great Marc Balmer once stated:
> Guys, we are talking about licenses and stuff. But we should write recipes.
> 
> What the fuck is wrong with us? IANAL, GPL, MIT, CC3A, WHATEVER.
> 
> I write a piece of text. I am the author. I own the copyright for the
> next 70 years. I allow the "Lua Cookbook" project to use my text for
> inclusion in an electronic or paper version of the Cookbook.
> 
> Do we want to continue talking fucking legalese stuff none of us
> understands really or do we start to do the job and write that cookbook?
 So, a sample "recipie" for the Cookbook:
Recipie #1
Pretty Print The Contents Of A Table (non-recursive)
	Author: Sean Conner	
	Website: http://example.net/lua/table/show.lua
	License: LGPL
The following function takes a table and prints out the contents of each
entry, formatted for a terminal width of 80 characters. Given a nil, it
will print out the contents of _G (the global environment). Possibly more
verbiage here and what not ... 
function show(l)
 local l = l or _G
 local maxkeylen = 0
 local maxvallen = 0
 
 local function conv_cntl(s)
 if s == "\n" then
 return "\\n"
 else
 return "\\?"
 end
 end
 
 for k,v in pairs(l)
 do
 maxkeylen = math.max(maxkeylen,string.len(tostring(k)))
 maxvallen = math.max(maxvallen,string.len(string.format("%q",tostring(v))))
 end
 
 ----------------------------------------------------
 -- clip the value portion to both the key and the
 -- value will display without wrapping in an 80
 -- column screen. Also, the Lua runtime does not
 -- support formats longer than 99 characters wide.
 -----------------------------------------------------
 
 maxkeylen = math.min(30,maxkeylen)
 maxvallen = math.min(77 - maxkeylen,maxvallen)
 
 local format = string.format("%%-%ds %%-%ds",maxkeylen + 1,maxvallen + 1)
 
 for k,v in pairs(l)
 do
 local vt
 
 if type(v) == "string" then
 vt = string.format("%q",v)
 else
 vt = tostring(v)
 end
 
 vt = string.gsub(vt,"%c",conv_cntl)
 vt = string.sub(vt,1,maxvallen)
 print(string.format(format,tostring(k),vt))
 end
end
Sequences of recipies can be grouped by topic (say, manipulating tables,
processing strings, etc).
 -spc

AltStyle によって変換されたページ (->オリジナル) /