Corona 写入文件
2014-9-2 0:19:11
收藏:0
阅读:80
评论:3
我正在创建一个游戏,需要将游戏数据写入文件。如果文件不存在,我已经让游戏去创建文件,可以读取文件的内容(我手动放入的),但我无法将游戏数据写入文件。
local path = system.pathForFile("gameData.gameData", system.DocumentsDirectory)
local myFile
defaultGameData = "It Worked"
if (path) then
myFile = io.open(path, "r")
end
if(myFile) then
print('file')
else
myFile:close()
--io.close(myFile)
myFile = io.open(path, 'w')
myFile:write( "My Test" )
io.close(myFile)
end
myFile = nil
这部分代码是有效的。然后我进入下一个场景,尝试写入新内容:
local saveData = "My app state data"
local path = system.pathForFile("gameData.gameData", system.DocumentsDirectory)
local myfile = io.open( path, "w" )
myfile:write( saveData )
io.close( myfile )
但是却得到错误:
mainMenu.lua:43: attempt to index local 'myfile' (a nil value)
我知道这个文件在沙盒中,而且这段代码是从 coronadoc 中复制的。我做错了什么?
点赞
用户1979583
错误发生在代码行中的错误:
myFile:close()
因此,要么将该行注释掉:
- myFile:close()
要么按照以下步骤执行(仅在需要时):
myFile = io.open(路径,'w')
myFile:close()
继续编码........... :)
2014-09-02 08:47:58
用户2338463
我找到了解决方案。我打开文件进行阅读以查看文件是否存在。我忘记在 if 语句中重新打开它时再次关闭它,如果文件存在的话。如果文件不存在,我只关闭了它。
2014-09-02 11:43:36
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
这里有两个我正在使用的函数:
function SaveTable(t, filename) local path = system.pathForFile( filename, system.DocumentsDirectory) local file = io.open(path, "w") if file then local contents = JSON.encode(t) file:write( contents ) io.close( file ) return true else return false end end function LoadTable(filename, dir) if (dir == nil) then dir = system.DocumentsDirectory; end local path = system.pathForFile( filename, dir) local contents = "" local myTable = {} local file = io.open( path, "r" ) if file then -- 读取文件中的所有内容到一个字符串中 local contents = file:read( "*a" ) myTable = JSON.decode(contents); io.close( file ) return myTable end return nil end用法:
local t = { text = "一些文本", v = 23 }; SaveTable(t, "文件名.json"); local u = LoadTable("文件名.json"); print(u.text); print(u.v);享受吧!