This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Jan's profile picture

FileMagic - demonstrating the power of metatables

Started by Jan, 27 October 2012 - 02:14 PM
Jan #1
Posted 27 October 2012 - 04:14 PM
So I was testing with metatables, and then I came up with this.
Instead of messing with io.open, you can just open a file by indexing a table!
for example:

print(files.test)
would print the contents of the file 'test'

files.test = "Some text"
Would write "some text" in the file 'test'

Just put this in front of your program:


local mt = {}
local function getMagicHandle()
local t = {}
setmetatable(t,mt)
return t
end
mt.__index = function (t,i)
 local handle = io.open(i,"r")
 if handle then
  local s =  handle:read("*a")
  handle:close()
  return s
 end
end
mt.__newindex = function(t,i,v)
 if type(v)=="nil" then
  fs.delete(i)
 elseif type(v)=="string" then
  local handle = io.open(i,"w")
  if handle then
   handle:write(v)
   handle:close()
  end
 end
end 
files = getMagicHandle()

You can also run the program once, and try it out in the 'lua' program.

EDIT:
You can now delete a file by setting it to nil
ChunLing #2
Posted 28 October 2012 - 01:08 AM
Nice.
PixelToast #3
Posted 28 October 2012 - 01:14 AM
nice program

i have a system with advanced metatables and can store variables on a remote server in real time
you can even edit tables within tables :D/>/>
Jazza_Hat #4
Posted 29 October 2012 - 08:12 AM
Theoretically if you serialized a table you could save tables too?
Jan #5
Posted 30 October 2012 - 09:26 PM
Theoretically if you serialized a table you could save tables too?
Yup

files.somefile = textutils.serialize(sometable)
nice program

i have a system with advanced metatables and can store variables on a remote server in real time
you can even edit tables within tables :P/>/>
Thanks :P/>/>
Yes, changing a table on another computer could be very handy!
gknova61 #6
Posted 09 November 2012 - 03:04 PM
Does this make them persistent across restarts?
Lyqyd #7
Posted 09 November 2012 - 04:04 PM
Does this make them persistent across restarts?

Files are persistent, variables are not.
Sebra #8
Posted 19 November 2012 - 04:17 AM
NIce, but…
As you unable to name a variable with "/" you tied to single directory.
And that give out a suggestion to change your code for this:

dir=magicHandler("some//dir//needed")
dir.filename = "Some text to store."
… or this:

dir.subdir.file = "content"
Both variants are interesting, second is more challenging.