我正在使用 Lua 表来存储数据以创建网页。正文内容存储在一个表中,有一些静态文本和一些由 Lua 函数生成的文本。
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
}
然后使用 table.concat 函数“打印”此表,添加一些换行符以提高可读性:
print(table.concat(Web.HTML,"<br>\n"))
上面的示例在 Lua 5.1 或同等版本中按预期工作,服务器成功地将其作为我网页的一部分传递。
我想在我的 HTML 表中放置任意 Lua 代码,它返回一个要连接的字符串,但我找不到正确的语法。 concat 函数提示 “concat”表中索引处的无效值(函数)。
我试过:
Web.HTML = {
"Classic text example:",
function() print "Hello World"; end,
}
和
Web.HTML = {
"Classic text example:",
function() return "Hello World"; end,
}
一个更有用的例子是列出 Lua 全局环境中的所有表:
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!"
}
我也曾尝试使用 loadstring(code ;return text )() 作为我表中的条目,但没有成功。欢迎任何指点。
提前致谢。
加文
最佳答案
function
显然返回一个函数。只需使用 ()
立即调用它。另外不要忘记将 print
更改为 return
- 您的函数需要返回表的值,而不是将其打印出来!
Web.HTML = {
"Classic text example:",
(function() return "Hello World"; end)(),
}
print(table.concat(Web.HTML,"<br>\n"))
-- Classic text example:<br>
-- Hello World
关于lua - 如何在包含函数的 Lua 表中使用 table.concat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36133040/