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

Tables inside tables - automatically

Started by Floedekage, 30 October 2012 - 01:41 PM
Floedekage #1
Posted 30 October 2012 - 02:41 PM
I'm trying to get better with Lua and therefore I am making an INI-file reader API, and I was trying to figure out how to insert tables inside tables using a function.
Here's where I am at:

The file: something.ini:

[Name]
1 = Kenny
2 = Liam
3 = Chill
[Age]
1 = 22
2 = 43
3 = 19
[Color]
1 = Blue
2 = Red
2 = Lime

A part of the ini API

local iniFileTable = {}

function load(filePath)
-- ####### Just the context: #######
  if filePath == nil then
    return "File is nil"
  elseif filePath == "" then
    return "No file specified"
  elseif string.upper(string.sub(filePath,-4)) ~= ".INI" then
    return "The file isn't an INI-file"
  else
    local fileContent = io.open(filePath,"r")
    repeat
      fileLine = fileContent:read()
-- ####### Here is my problem #######
        if string.sub(fileLine,0,1) == "[" and string.sub(fileLine,-1) == "]" then
          -- ### I want to make a sub-table in the iniFileTable named: string.sub(fileLine,1,-1)
        elseif string.sub(fileLine,0,1) ~= ";" then     -- ignore comments
          for i = 1, string.len(fileLine) do
            if string.sub(fileLine,i-1,i) == "=" then
              -- ### Here I would like to make a variable named string.sub(fileLine,0,i-1) and...
              -- ### the value string.sub(fileLine,i)
            end
          end
        end
    until fileLine = nil
  end
end

Does anyone know how to automatically make sub-tables named after a sub-string, and is it even possible to retrieve values faster from a table, or should I read through the whole file whenever I want a value?
KaoS #2
Posted 30 October 2012 - 02:56 PM
here is how I would do it


local iniFileTable = {}
function load(filePath)
  local currentT=nil
  if filePath == nil then
   return "File is nil"
  elseif filePath == "" then
   return "No file specified"
  elseif string.upper(string.sub(filePath,-4)) ~= ".INI" then
   return "The file isn't an INI-file"
  else
   local fileContent = io.open(filePath,"r")
   repeat
	fileLine = fileContent:read()
	if string.sub(fileLine,1,1) == "[" and string.sub(fileLine,-1) == "]" then
	 iniFileTable[string.sub(fileLine,1,-1)]={}
	 currentT=string.sub(fileLine,1,-1)
	elseif string.sub(fileLine,1,1) ~= ";" then	 -- ignore comments
	 for i = 1, string.len(fileLine) do
	  if string.sub(fileLine,i,i) == "=" then
	   iniFileTable[currentT][string.sub(fileLine,1,i-1)]=string.sub(fileLine,i+1)
	  end
	 end
	end
   until fileLine == nil
  end
end
Floedekage #3
Posted 30 October 2012 - 04:39 PM
Thank you so much! Spend too much time trying to figure this out and inally I can continue extending the API. :P/>/>