Here’s a small sample that processes files with lua code, like php. You can use this in your own app/webserver to server lua pages.
What is a Lua Server Page
A Lua server page is an HTML document that has embedded Lua code. It can have a similar structure like an ASP Page or a PHP Page. The embedding of the executable code is within the tags and is identified with the language tags as <?lua ?> with the executable code within the tag as
My custom page
For our processor, we shall first load the file which is achieved as
-- The filename is passed in fname
local tf = io.open( fname, "r" )
if tf then
if ftype == "php" or ftype == "lua" then
local fdata = tf:read("*a")
if ftype == "lua" then
respdata = decode(fdata)
else
respdata = fdata:gsub("<%?lua(.-)%?>", decode)
end
else
respdata = tf:read("*a")
end
tf:close()
else
-- Error reading the file
end
-- the file data is returned as processed string
return respdata
Decoding the data
In the function above, we are calling the decode function which processes the string data or runs the Lua code by running the Lua code and returns the resulting text.
function decode(theCode)
local strbuf = {}
local oldprint, newprint = print,
function(...)
local total, idx = select('#', ...)
for idx = 1, total do
strbuf[#strbuf+1] = tostring(select(idx, ...)) .. (idx == total and '\n' or '\t')
end
end
print = newprint
local f = loadstring(theCode)
if f then
f()
else
print ">>> Invalid Lua Code <<<<"
end
print = oldprint
collectgarbage('collect')
return table.concat(strbuf)
end
Closing notes
This can be extended to include the HTML header data so that when it is returned from a web server, it has the headers, etc.
The standard HTML 1.1 headers look something like
HTTP/1.1 200 OK
Connection: close
Server: myLua webserver
Content-Type: "" .. extmap[ftype or "txt"]
And when the file/data is not found (404 error code), the header to return could look like
HTTP/1.1 404 Not Found
Connection: close
Server: myLua webserver
Content-Type:text/html
Page not found
This code can be used in your own applications and also if you were to write a webserver that serves simple web pages. The bit for that would be simple as setting up a socket layer and listening on port 80 and returning data. Maybe a follow-up article could help run a Lua server.