我尝试运行以下代码:
#!/usr/bin/env wsapi.cgi
require("lib/request") -- wsapi lib
require("lib/response")
require("io")
module("loadHtml", package.seeall)
---This function generates a response for the WSAPI calls that need to GET a file
function run(wsapi_env)
--check the request
local req = wsapi.request.new(wsapi_env or {})
--generate response
res = wsapi.response.new()
---a couple of utility functions that will be used to write something to response
function print(str) res:write(str) end
function println(str) res:write(str) res:write('<br/>') end
println("running...")
ff=dofile("index.html.lua")
println("done!")
return res:finish()
end
return _M"index.html.lua“看起来像这样:
print([[<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
Hello world!
</html>]])它运行时没有错误,但我在客户端得到的结果是:
running...<br/>done!<br/>换句话说,run()函数中的println()可以工作,但它不能在"index.html.lua“中工作。我尝试了loadfile()而不是dofile(),结果是一样的。有趣的是,我写了一个测试代码,它可以工作:
--tryDoFileRun.lua:
function e()
function p(str)
print(str)
end
dofile("tryDoFile.lua")
end
e()它运行下面的代码:
--tryDoFile.lua
print("in tryDoFile.lua")
p("calling p")输出结果为:
in tryDoFile.lua
calling p就像它应该做的那样。然而,同样的想法在上面的第一段代码中不起作用。如何获得让index.html.lua使用我的print()函数的代码?
系统规格: WSAPI、Lighttpd服务器、Lua5.1、ARM9、Linux2.6
发布于 2011-08-19 05:13:49
问题出在module调用中。它会替换当前块的环境,但dofile不会继承修改后的环境。解决方案要么直接写入全局环境:
_G.print = function(str) res:write(str) end或者修改加载的代码块的环境:
function print(str) res:write(str) end
ff = loadfile("index.html.lua")
getfenv(ff).print = print
ff()后者可以封装在一个方便的HTML模板加载函数中。
https://stackoverflow.com/questions/7104045
复制相似问题