local mt = { __tostring = function(t) local parts = {} for k, v inpairs(t) do table.insert(parts, k .. "=" .. tostring(v)) end return"{" .. table.concat(parts, ", ") .. "}" end }
local t = setmetatable({name = "Lua", version = 5.4, year = 2026}, mt) print(t) --> {name=Lua, version=5.4, year=2026} print(tostring(t)) --> 同上
localfunctionsorted_pairs(t) local keys = {} for k inpairs(t) do table.insert(keys, k) end table.sort(keys) local i = 0 returnfunction() i = i + 1 local k = keys[i] if k then return k, t[k] end returnnil end end
local mt = { __pairs = function(t) return sorted_pairs(t) end }
local t = setmetatable({z = 1, a = 2, m = 3}, mt)
for k, v inpairs(t) do print(k, v) --> a 2 / m 3 / z 1(按字母序) end
localfunctioncreate_flexible_table(data) -- 合并 __index、__newindex、__tostring、__call local mt = { __index = function(t, key) if key == "type"thenreturn"flexible_table"end if key == "keys"then local ks = {} for k inpairs(t) dotable.insert(ks, k) end return ks end returnrawget(t, key) end, __newindex = function(t, key, value) if key == "locked"then rawset(t, key, value) return end if t.locked then error("表已锁定,不能修改") end rawset(t, key, value or"nil") end, __tostring = function(t) local parts = {} for k, v inpairs(t) do if k ~= "locked"then table.insert(parts, k .. "=" .. tostring(v)) end end return"[" .. table.concat(parts, ", ") .. "]" end, __call = function(t, action) if action == "clear"then for k inpairs(t) do if k ~= "locked"then rawset(t, k, nil) end end elseif action == "count"then local n = 0 for k inpairs(t) do if k ~= "locked"then n = n + 1end end return n end end } returnsetmetatable(data or {}, mt) end
local ft = create_flexible_table({a = 1, b = 2}) print(ft.type) --> flexible_table print(ft("count")) --> 2 ft.locked = true print(ft.keys) --> a, b, locked