Reading a variable from a file using filesystem

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
Bransonn
Prole
Posts: 8
Joined: Wed Apr 24, 2013 6:13 pm

Reading a variable from a file using filesystem

Post by Bransonn »

Hey guys,

I'm currently trying to make a program that will write '12' to 'test.lua', then print a variable that equals the number in the file. For instance,

Code: Select all

function love.load()
number = {}
local file = love.filesystem.newFile("testing.lua")

love.filesystem.write("testing.lua", "12")

number.y = love.filesystem.load('testing.lua')()
end

function love.draw()
love.graphics.print(number.y, 200, 200)
end
But every time I run it, I get the error "testing lua1, unexpected symbol near '12'.
I've opened the file to check it out, the file says '12'. That's it. Just 12.

I've checked the forums for this problem, and other parts of the internet, but have not found a solution.

Thank you.
Attachments
testingReadWrite.love
(264 Bytes) Downloaded 97 times
User avatar
raidho36
Party member
Posts: 2063
Joined: Mon Jun 17, 2013 12:00 pm

Re: Reading a variable from a file using filesystem

Post by raidho36 »

Well what did you expected, you've ran the .lua file that only contains "12" in it, naturally it fails - you can't write in Lua like that. But, the whole .lua acts like a function, so something like this:

Code: Select all

return 12
would be valid.
Bransonn
Prole
Posts: 8
Joined: Wed Apr 24, 2013 6:13 pm

Re: Reading a variable from a file using filesystem

Post by Bransonn »

I tried that last night and got the same error.

I tried it right now, and it works like a charm.

Thanks man.
User avatar
raidho36
Party member
Posts: 2063
Joined: Mon Jun 17, 2013 12:00 pm

Re: Reading a variable from a file using filesystem

Post by raidho36 »

If you're trying to implement save&load feature, I suggest using objects serialization instead.
User avatar
Roland_Yonaba
Inner party member
Posts: 1563
Joined: Tue Jun 21, 2011 6:08 pm
Location: Ouagadougou (Burkina Faso)
Contact:

Re: Reading a variable from a file using filesystem

Post by Roland_Yonaba »

Use setIdentity, to set your game's save folder.
And take a look at the example provided here.

Your code, corrected would look like:

Code: Select all

function love.load()
  love.filesystem.setIdentity('Test')
  number = {}
  local success = love.filesystem.write("testing.lua", "return 12")
  if not success then
    -- throw an error here, as the file could not be written
  end  
  --get data back
  number.y = love.filesystem.load('testing.lua')()
end

function love.draw()
  love.graphics.print(number.y, 200, 200)
end
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot], Semrush [Bot] and 4 guests