How to use table.concat in Lua tables containing functions

Viewed 2234

I'm using Lua tables to store data to create web pages. The body content is stored in a single table, there is some static text and some generated by Lua functions.

Web.HTML={
"<h1>Hello World</h1><br>",
"<br><h2>Current Directory</h2><br>",
io.popen("cd"):read('*l'),
"<br><h2>Current Lua Interpreter</h2><br>",
arg[-1] or arg[0],
"<br><h2>Current Package Path</h2><br>",
package.path:gsub(";",";<br>\n"),
"<br><h2>Current Package CPath</h2><br>",
package.cpath:gsub(";",";<br>\n"),
"<br><h2>Current Environment Table:</h2><br>",
io.popen("set"):read('*a'):gsub("\n","<br>\n").." ",
"<br><h2>Current Date:</h2><br>",
os.date(),
"<br><h2>Math calculation</h2><br>",
math.pi/180
}

This table is then "printed" using table.concat function, adding some newlines to aid readability:

print(table.concat(Web.HTML,"<br>\n"))

The example above works as expected in Lua 5.1 or equivalent and the server successfully passes this as part of my web page.

I would like to to place arbitrary Lua code in my HTML table which returns a string to be concatenated, but I can't find the correct syntax. The concat function complains invalid value (function) at index in table for 'concat'.

I have tried:

Web.HTML = {
"Classic text example:",
function() print "Hello World"; end,
}

and

Web.HTML = {
"Classic text example:",
function() return "Hello World"; end,
}

A more useful example would be to list all the tables in the Lua global environment:

Web.HTML = {
    "<br><h2>Current Lua Libraries</h2><br>",
    function()
        local text = ''
        for i,v in pairs(_G) do
            if type(v)=="table" then
               text = text..i.."<br>\n"
            end
        end
        return text
    end
    ,
    "Success!"
}

I have also tried using loadstring(code ;return text )() as an entry in my table without success. Any pointers welcome.

Thanks in advance.

Gavin

4 Answers
Related