Created
October 21, 2012 00:31
-
-
Save severak/3925335 to your computer and use it in GitHub Desktop.
TableFS - a table filesystem implemented in lua tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
---- | |
-- Table FS | |
---- | |
-- an unix-like filesystem simulation on lua tables | |
-- by Severak 2012 | |
-- license: WTFPL | |
---- | |
-- documentation will come later.... | |
function tDir(t) | |
for k,v in pairs(t) do | |
if type(v)=="table" then | |
v[".."]=t | |
end | |
end | |
t["."]=t | |
return t | |
end | |
function TableFS(tree, startPath) | |
startPath = startPath or "/" | |
local state={} | |
local tfs={} | |
function walk(d, path) | |
local current=d | |
for name in path:gmatch("([^/]+)") do | |
if type(current[name])=="table" then | |
current=current[name] | |
elseif current[name] then | |
return current[name] | |
else | |
return nil | |
end | |
end | |
return current | |
end | |
state.root=tree | |
state.wd=walk(state.root,startPath) | |
tfs.load=function(path) | |
if string.sub(path,1,1)=="/" then | |
return walk(state.root, string.sub(path,2)) | |
else | |
return walk(state.wd,path) | |
end | |
end | |
tfs.save=function(path,data) | |
local a,b=string.match(path,"(.+)/([^/]+)") | |
local dir=nil | |
local name=nil | |
if a and b then | |
dir=tfs.load(a) | |
name=b | |
else | |
dir=state.wd | |
name=path | |
end | |
dir[name]=data | |
end | |
tfs.dir=function(path) | |
path=path or "." | |
local cd=tfs.load(path) | |
if not (type(cd)=="table") then | |
error(string.format("%s is not dir"),path) | |
end | |
local listing={} | |
for k,v in pairs(cd) do | |
listing[#listing+1]=k | |
end | |
table.sort(listing) | |
local i=0 | |
local n=#listing | |
return function() | |
i=i+1 | |
if i <= n then return listing[i] end | |
end | |
end | |
tfs.chdir=function(path) | |
local newDir=tfs.load(path) | |
if newDir then | |
if type(newDir)=="table" then | |
state.wd=newDir | |
return true | |
end | |
return nil, "This isn't dir." | |
end | |
return nil, "Path goes to nowhere" | |
end | |
tfs.mkdir=function(name) | |
if state.wd[name] then | |
return nil, "Directory already exists." | |
else | |
state.wd[name]={} | |
state.wd[name][".."]=state.wd | |
state.wd[name]["."]=state.wd[name] | |
end | |
end | |
tfs.pwd=function() | |
curr=state.wd | |
local names={} | |
while curr[".."] do | |
prev=curr | |
curr=curr[".."] | |
for k,v in pairs(curr) do | |
if v==prev then | |
table.insert(names,1,k) | |
end | |
end | |
end | |
return "/" .. table.concat(names,"/") | |
end | |
return tfs | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment