Trouble reading txt file in Love2D

huangapple go评论74阅读模式
英文:

Trouble reading txt file in Love2D

问题

我正在尝试在Lua中从txt文件中读取内容,如下所示(main.lua):

local function read_file(filename)
	contents = io.open(filename, "r")
	if contents == nil then
		return false
	else
		io.close(contents)
		return true
	end
end

if read_file("myfile.txt") then
	print("Yes")
else
	print("Not found")
end

然而,尽管myfile.txt与main.lua位于同一目录中,但它一直返回“Not found”。我目前在Lua中使用Love2D引擎。

英文:

I am trying to read from a txt file in Lua, as shown below (main.lua):

local function read_file(filename)
	contents = io.open(filename, "r")
	if contents == nil then
		return false
	else
		io.close(contents)
		return true
	end
end

if read_file("myfile.txt") then
	print("Yes")
else
	print("Not found")
end

However, it keeps returning "Not found" even though myfile.txt is in the same directory as main.lua. I am currently using Lua with Love2D engine.

答案1

得分: 4

在LÖVE中,尽管你可能会被诱导使用Lua的io,但我建议不要这样做。

LÖVE拥有自己的love.filesystem。考虑以下内容:

if love.filesystem.getInfo("myfile.txt") then
   print("Yes")
   print(love.filesystem.read("myfile.txt"))
else
   print("Not found")
end

love.filesystem的行为在LÖVE支持的不同平台之间保持一致,简而言之,对于所选操作,它的行为如下:

  • 写入/追加 - 文件的路径是相对于_保存目录_的。
  • 读取 - 路径首先相对于_保存目录_解析。如果找不到任何内容,然后路径会相对于_love_存档或(如果适用)源目录解析。

_保存目录_是你的应用程序专用的特殊目录。如果有疑问,请参考LÖVE的维基

至于为什么问题中的示例可能不起作用,请参考Egor的评论。

英文:

While you might be tempted to use Lua's io in LÖVE I would suggest against it.

LÖVE has it's own love.filesystem. Consider:

if love.filesystem.getInfo("myfile.txt") then
   print("Yes")
   print(love.filesystem.read("myfile.txt"))
else
   print("Not found")
end

Behaviour of the love.filesystem is consistent between platforms supported by LÖVE and, in short, for selected operations it is:

  • Write/append - path of the file is relative to the save directory.
  • Read - path is first resolved against the save directory. If nothing is found then path is resolved against the content of the love archive or (if applicable) the source directory.

Save directory is a special directory for use of your application. In case of doubts, please refer to LÖVE's wiki.

As for why the example from the question might not be working - please see Egor's comment.

huangapple
  • 本文由 发表于 2020年1月3日 15:47:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574929.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定