Lua - Controlling metatable access



When we set a metatable to a target table using setmetatable, the assigned metatable is discoverable using getmetatable as shown below −

Example - Getting metatable details.

In this example, we're setting and getting metatable details. Lua is returning a default string representation of the metatable. −

main.lua

-- define a table
local person = { name = "Julie", age = 30 }

-- define a meta table
local meta = { __tostring = function(t) return "[Name: "..t.name .. ", Age: " .. t.age.."]" end }

-- set the metatable to target table
setmetatable(person, meta)

-- gets and prints the metatable
print(getmetatable(person))

Output

When we run the above program, we will get the following output−

table: 0x55b3aa2aade0

Example - Implementing __metatable metamethod

In below example, we're restricting user to get metatable details by returning a message instead of metatable as shown below −

main.lua

-- define a table
local person = { name = "Julie", age = 30 }

-- define a meta table
local meta = { 
   __tostring = function(t) return "[Name: "..t.name .. ", Age: " .. t.age.."]" end,
   __metatable = "Access Denied!"
   }

-- set the metatable to target table
setmetatable(person, meta)

-- now prints message - "Access Denied!"
print(getmetatable(person))

Output

When we run the above program, we will get the following output−

Access Denied!
Advertisements