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

Read-only tables/prevent changing tables

Started by InputUsername, 29 June 2014 - 05:43 PM
InputUsername #1
Posted 29 June 2014 - 07:43 PM
Hey all. I was wondering if there was a way to turn tables read-only, ie allow people to access table entries but don't allow changing the value of the entry. Example:

local t = {}
t["hello"] = "hi"

make_table_read_only(t)

print(t["hello"]) --# should print "hi"
t["hello"] = "bye" --# should not work

A quick internet search gave me a few results, all similar to this:

function readonlytable(table)
   return setmetatable({}, {
	 __index = table,
	 __newindex = function(table, key, value)
					error("Attempt to modify read-only table")
				  end,
	 __metatable = false
   });
end
(found on http://lua-users.org.../ReadOnlyTables)

but as far as I know, this would only prevent adding new values, not changing existing ones.
So how would I do this?

EDIT: to be more specific, I would like to prevent people from changing the fs API. In a computer's startup file, the fs API is modified to prevent accessing the startup file, so I'd like to protect the table in case someone does want to harm the startup file.
Edited on 29 June 2014 - 05:49 PM
KingofGamesYami #2
Posted 29 June 2014 - 08:32 PM
After giving that page a read, I have deduced that it does prevent changing existing values. However, it does not prevent changing values of values, eg

areadonlytable = { hello = {"hi", "meh"} }
areadonlytable.newKey = "stuff" --#fail
areadonlytable.hello = { "derp" } --#fail
areadonlytable.hello[1] = "death" --#will work
This does not affect the fs api, since there are 0 tables within it.
MKlegoman357 #3
Posted 29 June 2014 - 08:33 PM
I would recommend you to localize the real FS API table and replace _G.fs with a sandboxed FS API. That way there would be no way to access the real FS API (IIRC).


local _fs = _G.fs

_G.fs = sandboxedFS