Lua grammar knowledge point simulation class

I’m often asked about this during interviews, so just do it casually

First post the code and explain it in detail. I will go to someone else to pick it up when I am free someday.

local aaa = {}
aaa.__index = aaa
local AAA = setmetatable({}, aaa)
if nil ~= AAA then
    _G.AAA = AAA
end

1. Define a variable as an empty table
2. The metamethod of this variable points to itself
3. Assign this variable to an empty table through setmetatable
4. If the returned value is not empty, the simulation class is successful

Simple explanation:
what needs to be set is the __index metamethod, and the others can not be set, which is realized by using the mechanism of Lua lookup table elements.
_G is a lua table that stores global scalars, and the things in this table can be called directly. Such as tonumber (), type () and so on.

Guess you like

Origin blog.csdn.net/qql7267/article/details/93749076