欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Lua读取和写入文件处理例子

程序员文章站 2022-04-09 20:27:33
一、文件读存: 复制代码 代码如下: -- 似乎不支持大文件(不能超过9k?) function filesaveload()   &n...

一、文件读存:

复制代码 代码如下:

-- 似乎不支持大文件(不能超过9k?)
function filesaveload()
      local file = io.open("c:\\in.lua", "r");
      assert(file);
      local data = file:read("*a"); -- 读取所有内容
      file:close();
      file = io.open("c:\\out.lua", "w");
      assert(file);
      file:write(data);
      file:close();
end
filesaveload();

二、非循环表格处理:

复制代码 代码如下:

hero = 1;
monster = 2;
building = 3;
sumunit = 4;
cha = {};
cha[1] =
{
      basic =
      {
      name = "农民",    --npc名字
      cha_type = hero,  --npc模型
      },
      combat =
      {
       acquire = 600.00,  --主动攻击范围
       basic_def = 10,   --基础防御
      },
};

function savetablecontent(file, obj)
      local sztype = type(obj);
      print(sztype);
      if sztype == "number" then
            file:write(obj);
      elseif sztype == "string" then
            file:write(string.format("%q", obj));
      elseif sztype == "table" then
            --把table的内容格式化写入文件
            file:write("{\n");
            for i, v in pairs(obj) do
                  file:write("[");
                  savetablecontent(file, i);
                  file:write("]=\n");
                  savetablecontent(file, v);
                  file:write(", \n");
             end
            file:write("}\n");
      else
      error("can't serialize a "..sztype);
      end
end

function savetable()
      local file = io.open("e:\\00_00_00_海外组_学习\\写入.txt", "w");
      assert(file);
      file:write("cha = {}\n");
      file:write("cha[1] = \n");
      savetablecontent(file, cha[1]);
      file:write("}\n");
      file:close();
end

savetable();