Lua study notes use meta table to make a read-only table

table of Contents

1. Blog introduction

2. Content

3. Push

4. Conclusion


1. Blog introduction

This blog serves as a study note for Lua. Record the use of metatables and metamethods to make a read-only table. This blog requires a certain understanding of metatable related knowledge. If you don’t understand metatables, you can jump to it first. The blogger’s previous blog post about the meta table has a transfer door at the bottom of the article.


2. Content

First of all, we understand that there is an empty table in Lua, we can perform almost any operation on it, from which we can get the corresponding value according to the corresponding key, or append the corresponding value according to the corresponding key, as shown below:

local testTable = {}

testTable.width = 10

print(testTable.name)     --------nil

How do we create a read-only table? After understanding the meta table through the meta table, we can know that when we access a table with a meta table, the first thing to do is to access the meta method __index of the meta table. When assigning a table with a meta table, we will first access the meta method __newindex of the meta table, then the result is obvious, we can set a proxy empty table for the table, the empty table sets the meta table, and the meta table __index Return the proxied table, __newindex throws an exception, so that a read-only table can be realized, the following example:

----------------------------------------首先我们准备一个需要被设置为只读的表
local testTable = {}
testTable.width = 10
testTable.print = function()
	print("Sun")
end

----------------------------------------该方法将表设置为只读
function setOnlyRead(t)
	--代理的空表
	local proxy = {}
	--空表的元表
	local meta = {
		--被访问的时候就返回被代理的表
		__index = t,
		--赋值的时候直接抛出异常
		__newindex = function(t,k,v)
			error("this table is a read-only table")
		end
	}
	--设置元表
	setmetatable(proxy,meta)
	--将代理返回
	return proxy
end

local readOnlyTable = setOnlyRead(testTable)

print(readOnlyTable.width)				------10
readOnlyTable.print()              		        ------Sun
readOnlyTable.hhh = 100					------报错


3. Push

Github:https://github.com/KingSun5

Meta table: https://blog.csdn.net/Mr_Sun88/article/details/105205942


4. Conclusion


        The principle is very simple, and the writing method is also very simple. If you feel that the blogger’s article is well written, you may wish to pay attention to the blogger and like the blog post. In addition, the blogger’s ability is limited. If there is any error in the article, please comment and criticize.

       QQ exchange group: 806091680 (Chinar)

       This group was created by CSDN blogger Chinar, recommend it! I am also in the group!
 

Guess you like

Origin blog.csdn.net/Mr_Sun88/article/details/105648580