290 likes | 300 Views
Explore Lua scripting with insights on its uses, features, and CGILua for web development. Learn about Lua's birthplace and how to implement dynamic sites.
E N D
Lua and the Web Roberto Ierusalimschy PUC-Rio, Brazil Lua and the Web
-- a Lua script color = RED b = button { label = ‘OK’, x = 10, y = 20} Host Program Lua Interpreter What is Lua? • Yet Another Scripting Language • an “extension” language • implemented as a library in ANSI C Lua and the Web
Why Lua? • Simple and flexible • “Simple things simple, complex things possible” • Small • Efficient • Portable • Whole library written in ANSI C, compiles the same source code in all platforms • Typical uses: MS-DOS, Windows (3.1, 95, NT), Unix (Linux, Solaris, IRIX, AIX, ULTRIX), Next, OS/2, Mac Lua and the Web
What is CGILua? • a Web development tool for creating dynamic sites • Supports both templates and scripts • templates can embed scripts • scripts can “call” templates • based on Lua for • its scripts • expanding templates • its own configuration Lua and the Web
Why CGILua? • Small • whole distribution (source+binaries) fits in one floppy disk • Simple • smooth learning curve • Portable • runs on Unix and Windows 95-NT • scripts run on any platform without changes • Easily extended with dynamic libraries written in Lua and C Lua and the Web
Where is Lua? • TeCGraf • Lua’s birthplace • partnership between PUC-Rio and Petrobras (the Brazilian Oil Company) • dozens of products developed with Lua, since 1994 • PUC-Rio • many academic projects • used by hundreds of programmers • Intranet developed with CGILua Lua and the Web
Where is Lua? • Inside Brazil • Petrobras, the Brazilian Oil Company • Embratel (the main telecommunication company in Brazil) • many other companies • Outside Brazil • Lua is used in hundreds of projects, both commercial and academic • CGILua still in restricted use • until recently all documentation was in Portuguese Lua and the Web
How is Lua? function fat (n) if n == 0 then return 1 else return n*fat(n-1) end end • Pascal-like Syntax. • Interpreter executes sequence of statements. • function definitions are also statements (see later) • Six types: • numbers, tables, functions, strings, userdata, nil Lua and the Web
Tables • Implement associative arrays: • any value (including functions and other tables) can be used both for indices and values t = {} -- creates an empty table t[1] = "hello" t.x = print -- t.x is sugar for t[‘x’] t.x(t[1]) -- prints ‘hello’ t.next = t -- circular list Lua and the Web
Constructors • Expressions to create and initialize tables • Record style • point={x=10,y=20} • print(point.y) --> 20 • List style • days={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"} • print(days[3]) --> Tue • Mixed style • points={{x=0,y=0}, point; n=2} • print(points[points.n].y) --> 20 Lua and the Web
Constructors calls function “article” • Data description uses: article{ author="F.P.Brooks", title="The Mythical Man-Month", year=1975, } news = { {text = "New version 2.0", date = "21/05/1997"}, {text = "New example", date = "21/05/1997"}, {text = "New version: 2.1",date = "17/06/1997"}, } Lua and the Web
list = {value=v, next=list} value - v next - Tables x Objects • Tables are dynamically created objects. • in the sense of Hoare list old list ... Lua and the Web
function inc (x) return x+1 end inc = function (x) return x+1 end sugar Functions in Lua • First class values • Example: cloning a table t clone = {} foreach(t, function (i,e) clone[i]=e end) Lua and the Web
Upvalues • Mechanism to allow functions to access non-local variables • An upvalue is a variable expression whose value is computed when the enclosing function is instantiated (and not when the function is executed) function add (x) return function (y) return y+%x end end add1 = add(1) print(add1(10)) --> 11 upvalue Lua and the Web
Example: Security • User scripts need a “secure” Lua environment • Security can be set in Lua itself, through redefinition of “dangerous” functions • functions are first-class values!! • With upvalues, the new function still can use the old, unsecure, version to implement its core functionality • Because the old version is kept in the closure of the new version, it is no longer accessible by the script Lua and the Web
Example: Security -- redefines "openfile", to restrict files that -- can be open by a script openfile = function (filename) if is_ok(filename) then %openfile(filename) else error("cannot open "..filename) end end -- at this point, only the new "openfile" is -- visible, but the old function is still -- available inside the new to do the real job Lua and the Web
function a:foo (x) ... end a.foo = function (self,x) ... end sugar sugar a:foo(x) a.foo(a,x) Objects • First class functions + tables = almost OO. • tables can have functions as field values (methods) • Syntactic sugar for defining and calling methods • handles hidden parameter self Lua and the Web
Strings • No size limits, good performance for long strings • common practice to read a whole text file in a single string before processing • Strings can store arbitrary binary data • not ‘\0’ terminated • Usual pattern matching facilities, implemented through a standard library • Pattern substitution can be called with a function to compute the replacement string Lua and the Web
Example: Decoding a URL encoding string • This function is used by CGILua to decode a URL encoding string: • “lua%3Dis+great” “lua=is great” function unescape (str) str = gsub(str, "+", " ") return gsub(str, "%%(%x%x)", function (x) return strchar(tonumber(x, 16)) end) end Lua and the Web
Example: Decoding URL data • This function collects all pairs <key,value> from a submission into the table cgi: function decode (string) cgi={} gsub(string, "([^&=]*)=([^&=]*)&?", function (key, value) key=unescape(key) value=unescape(value) cgi[key]=value end) end Lua and the Web
CGILua Pages • a page can be created by a script: write("Content-type: text/html\n\n") write("<html>") write("<head><title>Simple page</title></head>") write("<body>") write("<h1>Today's date is: ", date(), "</h1>") write("</body>") write("</html>") Lua and the Web
or it can be a template: <html> <head><title>Simple page</title></head> <body> <h1>Today's date is: $|date()|$ </h1> </body> </html> Lua expression Lua and the Web
Example: echoing • the following script can be used for debugging, to show all data posted by a form: write("Content-type: text/html\n\n") write("<html>") write("<head><title>Your data</title></head>") write("<body><h1>Your data</h1>") write("<table border=1 width=100%>") foreach(cgi, function(key,value) write("<tr><td>", key, "</td>") write("<td>", value, "</td></tr>") end) write("</table></body></html>") Lua and the Web
Example: echoing • The same page can be generated by a template: <html> <head><title>Your data</title></head> <body><h1>Your data</h1> <table border=1 width=100%> <!--$$ LOOP start="key,value=next(cgi,nil)", test="key", action="key,value=next(cgi,key)" $$--> <tr><td> $|key|$ </td> <td> $|value|$ </td></tr> <!--$$ ENDLOOP $$--> </table></body></html> Lua and the Web
Template Preprocessing • Three kinds of marks: • expressions • statements • control fields: loops and conditionals • All marks has a sensible appearance when not preprocessed • statements and control fields handled as comments • expressions appear literally (place-holder) • Templates can be edited like a static page with conventional tools Lua and the Web
Template before preprocessing Template Example <h1>Club member list</h1> <table border=1 width=100%> <tr align=center> <td><strong>First Name</strong></td> <td><strong>Last Name</strong></td> </tr> <!--$$ LOOP start=‘i=1’, test=‘i<=field.n’, action=‘i=i+1’ $$-> <tr><td>$| m[i].firstname |$</td> <td>$| m[i].lastname |$</td> </tr> <!--$$ ENDLOOP $$--> </table> Lua and the Web
Template afterpreprocessing Template Example • Now, suppose table m defined as m = { {firstname='George', lastname='Harrison'}, {firstname='John', lastname='Lennon'}, {firstname='Paul', lastname='McCartney'}, {firstname='Ringo', lastname='Starr'} } Lua and the Web
Extensions • CGILua can include libraries written both in Lua and in C/C++ • e.g. database access, cryptography • Libraries can be loaded dynamically • no need of recompilations/relinks • Loading function can be erased after configuration • enhance security Lua and the Web
Conclusions • Lua and CGILua are smart choices • Small and simple • Flexible • Portable Lua and the Web