Lua loadfile()和dostring()don';t从内部运行(wsapi_环境)进行工作

Lua loadfile()和dostring()don';t从内部运行(wsapi_环境)进行工作,lua,Lua,我尝试运行以下代码: #!/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_e

我尝试运行以下代码:

#!/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
其中运行以下命令:

--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

问题出在
模块调用中。它将替换当前块的环境,但是
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模板加载函数中

in tryDoFile.lua
calling p
_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()