Quick Links: Download Gideros Studio | Gideros Documentation | Gideros Development Center | Gideros community chat | DONATE
problem with file:read — Gideros Forum

problem with file:read

nat12nat12 Member
edited January 2012 in General questions
Hello,
I have started coding the save/load functions of our game, but i encountered a problem, probably i am doing something wrong (first time i do binary IO in lua), here follow a simplified version of my code to better illustrate the problem:
curLevel = 2
hp = 10
 
function save()
    local file = io.open("|D|save.bin", "w+b")
    file:write(curLevel)
    file:write(hp)
    file:close()
end
 
function load()
    local file = io.open("|D|save.bin", "rb")
    curLevel = file:read("*n")
    hp = file:read("*n")
    file:close()
end
 
 
The problem is when reading i obtain curLevel==210, hp==nil instead of expected curLevel==2, hp==10
i also examined the resulting file (on Windows) and discovered it is saved as text instead of binary as i specified, i suppose the first problem is caused by the second one, any suggestion about how to fix it?

Comments

  • atilimatilim Maintainer
    edited January 2012
    In fact, there is little difference between binary and text files except the handling of the newline. I don't know if there is direct support of writing numbers as binary data (as IEEE 754 format)

    Instead, I can suggest implementing your save/load of your game as Lua tables:

    1. Download table.save-0.94.lua from http://lua-users.org/wiki/SaveTableToFile and add it your project.
    2. Create a table about your progress and save it:
    save = {
      curLevel = 2,
      hp = 10,
    }
    table.save(save, "|D|save.tbl")
    3. Then you can load your table as:
    save = table.load("|D|save.tbl")
  • Thank You,
    I tried table.save, work fine, for now i will use it.
    for the future, if needed, i consider to implement a more compact text mode save.
    (now that i understand why my attempt not worked i am confident to be capable of doing it right)

    Just for information: table.load function miss a "local tables,err" at begin, to be usable with strict.lua
  • atilimatilim Maintainer
    edited January 2012
    good tip. thank you.

    Edit: I've committed table.save to https://github.com/gideros/table.save and make variables local at table.load after your suggestion.
Sign In or Register to comment.