Leviathan
Leviathan

Reputation: 83

Lua 5.2.1 - Edit and save variable in file

I have a file which is part of a game I'm making, and I am trying to manipulate it with code.

Here is the file:

tech = 
{
    weaponstech = 1.5,
    armortech = 1.8,
    shieldstech = 2 
}

I am trying to open the file like this

local file = io.open("tech")

and then try to change the value of the variable 'shieldstech' to 2.2.

I need this to happen automatically every time I run a function.

I usually use single variable files such as this:

v = 1

but that just gives me a clutter of files which is unmanageable.

so now I store variables the way I wrote my tech file.

This is how I used to edit these single-variable files:

local file = io.open("file", "w")
file:write("v = "..var)
file.close()

but it is just too much work to rewrite the whole file in a single line or code, so I want to just change and save the variable, something like this:

local file = io.open("tech", "w")
shieldstech = 2.2
file:close()

but it won't work like that, and I know why. I'm not telling the program to edit the file, I'm telling it to edit the variable in that instance of the program. All I'm doing to the file is opening it and then closing it.

Any of you guys know a way to do this?

Thx,

Upvotes: 1

Views: 3279

Answers (2)

Brad Peabody
Brad Peabody

Reputation: 11377

My suggestion would be to use something designed for that task already. Here is an example: https://github.com/2ion/ini.lua That will allow you to read in the data, make as many or as few changes to it as you want, and then write it back out.

EDIT: This has a dependency on this: https://github.com/stevedonovan/Penlight/blob/master/lua/pl/path.lua

Might want to try inih instead (although it's written C, so integration will require a bit more knowledge): http://luarocks.org/repositories/rocks/#lua-inih

Upvotes: 2

Stephan Roslen
Stephan Roslen

Reputation: 331

This will rewrite the whole file each time, which is not very performing, but it will work. Consider using a sqlite database.

local file = io.open("tech", "w")
file:write("tech = {")
for p,v in pairs(tech) do file:write(p .. " = " .. v .. "," ) end
file:write("}")
file:close()

Upvotes: 0

Related Questions