2

im trying to create a simple 2 functions text-file "database" with LUA. All i need is 2 Functions.

my db should look like that:

    varName;varValue 
    JohnAge;18 
    JohnCity;Munich 
    LarissaAge;21
    LarissaCity;Berlin

In fact im not stuck to any format! I just don't have a way to save data longterm in my lua enviroment and i need to find a workaround. So if you already have a similiar solution at hand, please feel free to throw it at me. Thank you very much

Function WriteToDB(varName, varValue) 
If database.text contains a line that starts with varName 
replace whatever comes after seperator ";" with varValue (but dont go into the next line)


Function ReadFromDB(varName)
If database.text contains a line that starts with varName 
take whatever comes after the seperator ";" and return that (but dont go into the next line)
elseif not found print("error")
Sinfox
  • 21
  • 1
  • I suggest you use Lua code as your format so that you can load it with a simple dofile. – lhf Nov 20 '16 at 10:10
  • hello Ihf, thanks for the quick answer. I researched a bit and i don't really see how to apply this on my problem. Do you have a small example? thank you! – Sinfox Nov 20 '16 at 10:50

1 Answers1

1

Save the data as Lua code that builds a table:

return {
JohnAge = 18,
JohnCity = "Munich",
LarissaAge = 21,
LarissaCity = "Berlin",
}

Or better yet

return {
["John"] = {Age = 18, City = "Munich"},
["Larissa"] = {Age = 21, City = "Berlin"},
}

Load the data with

db = dofile"db.lua"

Access the data with

print(db["Larissa"].Age)

or

print(db[name].Age)
lhf
  • 70,581
  • 9
  • 108
  • 149
  • Thanks for the clean solution! I already upvoted you yet its not shown before i reach a certain reputation threshold! Sadly it seems that my enviroment has dofile blocked to prevent abuse, yet this still seems to be the cleanest way to handle a small database. Thank you – Sinfox Nov 20 '16 at 12:51