元表与元方法 简介 正文 元表 元方法 表相关常用的元方法 __index __newindex __len __call 算术及关系运算 元方法 __add __eq __len __unm 综合案例 库定义元方法 __tostring __pairs 简介 在Lua中,元表(metatable)是一种特殊的表,用于控制其他表的行为。每个表可以关联一个元表,通过设置元表和元方法,可以修改表的一些默认行为。 元方法(metamethod)是一种特殊的函数,用于定义表的一些特殊操作。 元方法通过在元表中定义特定的字段来实现。例如,当表进行加法操作时,Lua会检查表的元表中是否定义了__add字段。如果定义了__add字段,Lua会调用该字段对应的函数来执行加法操作。 正文 元表 只有字符串才有默认的元表,其他类型需要手动添加 任何表都可以作为其他表的元表 登录后复制 ---------1.初体验,设置元表,获取元表 t={} t1={} --元表 print(getmetatable(t)) setmetatable(t,t1) --设置元表 print(getmetatable(t)) print(getmetatable("nihao")) print(getmetatable("hello")) print(getmetatable(10)) --输出 nil table: 00000000006e9df0 table: 00000000006e9ef0 table: 00000000006e9ef0 nil -----2.获取字符串默认的元表以及里面的元方法 tab = getmetatable("hello") for index, value in pairs(tab) do print(index,value) --元表 for key, value in pairs(value) do print(key,value) --所有元方法 end end --输出 __index table: 0000000000ea9f30 rep function: 000000006849d270 format function: 000000006849eb30 char function: 000000006849d730 gsub function: 000000006849fe90 upper function: 000000006849d150 match function: 000000006849fe70 unpack function: 000000006849ddf0 reverse function: 000000006849d1e0 lower function: 000000006849d3d0 byte fu