使用 Lua 将 textarea 保存到文件中。

我拥有一个使用 CGI 和 LUA 的 Web 服务器(uhttpd)。 我制作了一个带有文本框的表单。 我需要的是将文本框的内容保存到位于 /etc/list.txt 中的文件中。 我认为 LUA 脚本需要读取 POST 变量,然后将它们保存到本地文件 /etc/list.txt 中。

我已经有了读取文件的脚本:

function file_exists(file)
  local f = io.open(file, "rb")
  if f then f:close() end
  return f ~= nil
end

function lines_from(file)
  if not file_exists(file) then return {} end
  lines = {}
  for line in io.lines(file) do
    lines[#lines + 1] = line
  end
  return lines
end

local file = '/etc/list.txt'
local lines = lines_from(file)

print ('<textarea name="mensaje" cols="40" rows="40">')

for k,v in pairs(lines) do
  print(v)
end

print ("</textarea>")

这个脚本将文件.txt 的内容显示在文本框中。 现在我需要一个“保存”按钮,将文本框再次提交到文件中。

谢谢你的帮助,祝你有愉快的一天。

点赞
用户501459
用户501459

小建议:lines_from 函数每次被调用都会覆盖一个全局变量 lines。应该把它变成局部变量。另外,在读取文件之前打开和关闭文件来查看它是否存在是浪费的。这个操作可以合并到 lines_from 中:

function lines_from(filename)
  local lines = {}
  local file = io.open(filename)
  if file then
      for line in file:lines(file) do
        lines[#lines + 1] = line
      end
      file:close();
  end
  return lines
end

在你的情况下,甚至没有必要将文本读取为行。只需读取该文件的所有文本:

function text_from(filename)
  local text = ''
  local file = io.open(filename)
  if file then
      text = file:read('*a')
      file:close();
  end
  return text
end

local file = 'test.lua'
local text = text_from(file)

print ('<textarea name="mensaje" cols="40" rows="40">')
print(text)
print ("</textarea>")

要将文本写回文件中,只需反转过程,以 "w+" 模式打开文件(替换现有数据):

function save_text_to(filename, text)
  local file = io.open(filename, 'w+')
  if file then
      text = file:write(text);
      file:close();
  end
end

save_text_to('foo', text)
2014-03-13 22:06:16