Read-only tables in Lua programming


While working with tables, we can easily access and modify the values present in the tables provided we know the key. But there are cases where we would like our tables to be in read-only format so that the values present inside the table cannot be modified.

There are many benefits for this particular approach as we can make use of such read only tables in storing information that we don’t want anyone to mutate, like storing data of employees.

In order to make any table a read only table we make use of the setmetatable() function along with __index and __newindex metamethods.

Let’s first write the function that will take a table as an argument and then will convert that table into a read only table.

Example

Consider the function shown below −

function readOnly (t)
   local proxy = {}
   local mt = {-- create metatable
   __index = t,
   __newindex = function (t,k,v)
   error("attempt to update a read-only table", 2)
   end
   }
   setmetatable(proxy, mt)
   return proxy
end

Now let’s make use of the above function where we will pass a table into the above function and then will try to modify the value present in the table.

days = readOnly{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
print(days[2])--> Monday
days[2] = "Noday"

Output

stdin:1: attempt to update a read-only table

Updated on: 19-Jul-2021

490 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements