Lua - Readonly Lists



It is very useful to create a readonly list like week days, month names etc. In Lua, we can use metamethod __newindex() to do the same.

Syntax

__newindex(table, key, value)

where

  • table represents the current table whose behavior is to be modified.

  • key represents key either assigned or non-assigned.

  • value represents value to be associated with the key.

__newindex() method is called when we try to assign a new key to the table or try to assign a new value to an existing key. We can utilize this behavior to do the following −

  • Create a readonly list.

  • Perform validations on the values before being assigned.

  • Implement custom storage or perform side effects.

Example - Creating a readonly list

main.lua

-- create a list
local WEEKDAYS = {"SUN", "MON", "TUE", "WED","THU","FRI","SAT"}

-- create a metatable to make above list readonly
local metatableReadonly = {
   __newindex = function(table, key, value)
      error("No modification possible. List is readonly", 2)
      return
   end
}

-- set the metatable
setmetatable(WEEKDAYS, metatableReadonly)

-- try to add new entry, throws error
WEEKDAYS[8] = "NONE"

Output

When the above code is built and executed, it produces the following result −

lua: main.lua:19: No modification possible. List is readonly
stack traceback:
   [C]: in function 'error'
   main.lua:9: in metamethod 'newindex'
   main.lua:19: in main chunk
   [C]: in ?
lua_metatables_with_lists.htm
Advertisements