Jump to content




{Solved} Recursive Readonlytable


2 replies to this topic

#1 cyanisaac

  • Members
  • 369 posts
  • LocationSan Diego, CA

Posted 31 January 2016 - 07:54 PM

EDIT: This is solved. Working function:
local function readonlytable(table)
   return setmetatable({}, {
	 __index = table,
	 __newindex = function(table, key, value)
					error("Attempt to modify read-only table")
				  end,
	 __metatable = false
   });
end

function packagePrivateTable(tbl)
  for key, value in pairs(tbl) do
	if type(value) == 'table' then
	  tbl[key] = packagePrivateTable(tbl[key])
	end
  end
  return readonlytable(tbl)
end


Original Post

Edited by cyanisaac, 31 January 2016 - 08:24 PM.


#2 MKlegoman357

  • Members
  • 1,170 posts
  • LocationKaunas, Lithuania

Posted 31 January 2016 - 08:14 PM

That's because in your for loop you only add tables to your 'workingTable'. Also, you can use 'value' instead of 'argTable[key]' in the loop. And I don't really see the point of 'argTable' variable, you could just use 'tbl'.

Edited by MKlegoman357, 31 January 2016 - 08:16 PM.


#3 cyanisaac

  • Members
  • 369 posts
  • LocationSan Diego, CA

Posted 31 January 2016 - 08:23 PM

Thank you for the help MKlegoman357. This is my final function (along with the readonlytable function, which I grabbed off of a lua wiki somewhere, that this function requires:
local function readonlytable(table)
   return setmetatable({}, {
     __index = table,
     __newindex = function(table, key, value)
                    error("Attempt to modify read-only table")
                  end,
     __metatable = false
   });
end

function packagePrivateTable(tbl)
  for key, value in pairs(tbl) do
    if type(value) == 'table' then
      tbl[key] = packagePrivateTable(tbl[key])
    end
  end
  return readonlytable(tbl)
end

Hopefully others find this useful.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users