Page 1 of 1

Reading a variable from a file using filesystem

Posted: Thu Sep 05, 2013 8:07 pm
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.

Re: Reading a variable from a file using filesystem

Posted: Thu Sep 05, 2013 8:28 pm
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.

Re: Reading a variable from a file using filesystem

Posted: Thu Sep 05, 2013 8:36 pm
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.

Re: Reading a variable from a file using filesystem

Posted: Thu Sep 05, 2013 8:55 pm
by raidho36
If you're trying to implement save&load feature, I suggest using objects serialization instead.

Re: Reading a variable from a file using filesystem

Posted: Thu Sep 05, 2013 10:26 pm
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