{"id":32985683,"url":"https://github.com/kurapica/PLoop","last_synced_at":"2025-11-18T02:02:12.607Z","repository":{"id":10034142,"uuid":"12077540","full_name":"kurapica/PLoop","owner":"kurapica","description":"Prototype Lua object-oriented program system and frameworks. ","archived":false,"fork":false,"pushed_at":"2025-08-31T02:32:07.000Z","size":5191,"stargazers_count":239,"open_issues_count":0,"forks_count":34,"subscribers_count":16,"default_branch":"master","last_synced_at":"2025-08-31T04:19:07.980Z","etag":null,"topics":["collection","dependency-injection","lua","mqtt","oop","reactivex","serialization","type-validation","watch-reactive","web-framework"],"latest_commit_sha":null,"homepage":"https://discord.gg/6hD4sdUtgp","language":"Lua","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kurapica.png","metadata":{"files":{"readme":"README-zh.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2013-08-13T08:58:15.000Z","updated_at":"2025-08-31T02:32:10.000Z","dependencies_parsed_at":"2024-02-01T11:36:10.947Z","dependency_job_id":"5538eda0-b1f3-4b5c-b91c-ce0809303198","html_url":"https://github.com/kurapica/PLoop","commit_stats":null,"previous_names":[],"tags_count":38,"template":false,"template_full_name":null,"purl":"pkg:github/kurapica/PLoop","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kurapica%2FPLoop","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kurapica%2FPLoop/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kurapica%2FPLoop/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kurapica%2FPLoop/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kurapica","download_url":"https://codeload.github.com/kurapica/PLoop/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kurapica%2FPLoop/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":284988465,"owners_count":27095952,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-11-18T02:00:05.759Z","response_time":61,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["collection","dependency-injection","lua","mqtt","oop","reactivex","serialization","type-validation","watch-reactive","web-framework"],"created_at":"2025-11-13T08:00:33.766Z","updated_at":"2025-11-18T02:02:12.597Z","avatar_url":"https://github.com/kurapica.png","language":"Lua","funding_links":[],"categories":["Resources","Lua"],"sub_categories":["Programming Paradigms"],"readme":"# 基于原型的Lua面向对象系统\n\n**PLoop**是纯Lua的面向对象系统，它提供的语法规则类似于C#，支持Lua 5.1及以上版本，也支持luajit。也可以用于类似[OpenResty](https://github.com/openresty/lua-nginx-module)这样的多线程平台。\n\n**PLoop**本身也提供了类似协程池，集合，序列化等通用功能。除了提供类型定义和通用类型外，**PLoop**也针对项目开发提供了诸如代码管理，类型验证等常用功能。\n\n**更详细的文档请阅读[Docs](https://github.com/kurapica/PLoop/tree/master/Docs)**\n\n## 目录\n\n* [安装](#安装)\n* [从使用集合开始](#从使用集合开始)\n\t* [List的创建](#list的创建)\n\t* [List的方法](#list的方法)\n\t* [动态列表](#动态列表)\n\t* [List的遍历](#list的遍历)\n\t* [List的排序](#list的排序)\n\t* [Dictionary的创建](#dictionary的创建)\n\t* [Dictionary的方法](#dictionary的方法)\n\t* [Dictionary的遍历](#dictionary的遍历)\n\t* [动态字典](#动态字典)\n* [特性(Attribute)和协程池(Thread Pool)](#特性attribute和协程池thread-pool)\n* [拼写错误检查](#拼写错误检查)\n\t* [读取不存在的全局变量](#读取不存在的全局变量)\n\t* [写非法全局变量](#写非法全局变量)\n\t* [访问不存在的对象字段](#访问不存在的对象字段)\n* [类型验证](#类型验证)\n* [enum 枚举类型](#enum-枚举类型)\n\t* [System.Enum](#systemenum)\n* [struct 结构体](#struct-结构体)\n\t* [Custom 自定义结构体](#custom-自定义结构体)\n\t* [Member 成员结构体类型](#member-成员结构体类型)\n\t* [Array 数组结构体](#array-数组结构体)\n\t* [Hash 键值对结构体](#hash-键值对结构体)\n\t* [使用table来定义结构体](#使用table来定义结构体)\n\t* [减少验证消耗](#减少验证消耗)\n\t* [联合类型](#联合类型)\n\t* [子类型](#子类型)\n\t* [System.Struct](#systemstruct)\n\t* [System.Member](#systemmember)\n* [Class 类](#class-类)\n\t* [类方法和对象方法](#类方法和对象方法)\n\t* [元数据和对象构造](#元数据和对象构造)\n\t* [超类和继承](#超类和继承)\n\t* [System.Class](#systemclass)\n\t* [类的多重版本](#类的多重版本)\n\t* [扩展方法](#扩展方法)\n* [Interface 接口](#interface-接口)\n\t* [System.Interface](#systeminterface)\n\t* [Interface的匿名类](#interface的匿名类)\n\t* [接口的所需类](#接口的所需类)\n* [Event 事件](#event-事件)\n\t* [事件处理方法变更的处理](#事件处理方法变更的处理)\n\t* [静态事件](#静态事件)\n\t* [超类事件](#超类事件)\n\t* [System.Event](#systemevent)\n* [Property 属性](#property-属性)\n\t* [get/set](#getset)\n\t* [getmethod/setmethod](#getmethodsetmethod)\n\t* [property-throw](#property-throw)\n\t* [field \u0026 default](#field--default)\n\t* [default factory](#default-factory)\n\t* [property-event](#property-event)\n\t* [property-handler](#property-handler)\n\t* [static property](#static-property)\n\t* [自动绑定](#自动绑定)\n\t* [超类属性](#超类属性)\n\t* [索引属性](#索引属性)\n\t* [Get/Set行为修饰](#getset行为修饰)\n\t* [System.Property](#systemproperty)\n* [继承和优先级](#继承和优先级)\n* [使用其他定义形式](#使用其他定义形式)\n\t* [使用字符串作为定义体](#使用字符串作为定义体)\n\t* [使用table作为定义体](#使用table作为定义体)\n* [命名空间和匿名类型](#命名空间和匿名类型)\n\t* [System.Namespace](#systemnamespace)\n* [环境](#环境)\n\t* [隔离代码](#隔离代码)\n\t* [分享类型](#分享类型)\n\t* [特性和全局函数](#特性和全局函数)\n\t* [使用命名空间作为调用者](#使用命名空间作为调用者)\n\t* [全局变量的读取](#全局变量的读取)\n\t* [自动缓存机制](#自动缓存机制)\n* [重载](#重载)\n\t* [this和构造体方法](#this和构造体方法)\n\t* [使用超类方法处理未处理的参数样式](#使用超类方法处理未处理的参数样式)\n\t* [System.Variable](#systemvariable)\n\t* [申明变量的简易版本](#申明变量的简易版本)\n* [Throw Exception 异常处理](#throw-exception-异常处理)\n* [模板类](#模板类)\n* [System.Module](#systemmodule)\n\t* [child-modules 子模组](#child-modules-子模组)\n* [Attribute 特性系统](#attribute-特性系统)\n\t* [System.IAttribute](#systemiattribute)\n\t* [System.IInitAttribute 初始化特性](#systemiinitattribute-初始化特性)\n\t* [System.IApplyAttribute 应用特性](#systemiapplyattribute-应用特性)\n\t* [System.IAttachAttribute 附着特性](#systemiattachattribute-附着特性)\n\t* [System特性](#system-attributes)\n\t\t* [`__Abstract__`](#__abstract__)\n\t\t* [`__AutoCache__`](#__autocache__)\n\t\t* [`__AnonymousClass__`](#__anonymousclass__)\n\t\t* [`__AutoIndex__`](#__autoindex__)\n\t\t* [`__Arguments__`](#__arguments__)\n\t\t* [`__Async__`](#__async__)\n\t\t* [`__Base__`](#__base__)\n\t\t* [`__Default__`](#__default__)\n\t\t* [`__Delegate__`](#__delegate__)\n\t\t* [`__EventChangeHandler__`](#__eventchangehandler__)\n\t\t* [`__Final__`](#__final__)\n\t\t* [`__Flags__`](#__flags__)\n\t\t* [`__Get__`](#__get__)\n\t\t* [`__Indexer__`](#__indexer__)\n\t\t* [`__Iterator__`](#__iterator__)\n\t\t* [`__Namespace__`](#__namespace__)\n\t\t* [`__NoNilValue__`](#__nonilvalue__)\n\t\t* [`__NoRawSet__`](#__norawset__)\n\t\t* [`__ObjectAttr__`](#__objectattr__)\n\t\t* [`__ObjFuncAttr__`](#__objfuncattr__)\n\t\t* [`__ObjectSource__`](#__objectsource__)\n\t\t* [`__Require__`](#__require__)\n\t\t* [`__Return__`](#__return__)\n\t\t* [`__Sealed__`](#__sealed__)\n\t\t* [`__Set__`](#__set__)\n\t\t* [`__SingleVer__`](#__singlever__)\n\t\t* [`__Static__`](#__static__)\n\t\t* [`__Super__`](#__super__)\n\t\t* [`__SuperObject__`](#__superobject__)\n\t\t* [`__Throwable__`](#__throwable__)\n* [keyword 关键字](#keyword-关键字)\n\t* [全局关键字](#全局关键字)\n\t\t* [export 关键字](#export-关键字)\n\t\t* [with 关键字](#with-关键字)\n\t* [上下文相关的关键字](#上下文相关的关键字)\n\t* [`_G`中可用的资源](#_g中可用的资源)\n* [Serialization 序列化](#serialization序列化)\n\t* [从JSON开始](#从json开始)\n\t* [可序列化类型](#可序列化类型)\n\t* [自定义序列化和反序列化](#自定义序列化和反序列化)\n* [System.Collections 集合](#systemcollections-集合)\n\t* [System.Collections.Iterable](#systemcollectionsiterable)\n\t* [System.Collections.IList](#systemcollectionsilist)\n\t\t* [System.Collections.ICountable](#systemcollectionsicountable)\n\t\t* [System.Collections.IIndexedList](#systemcollectionsiindexedlist)\n\t\t* [System.Collections.List](#systemcollectionslist)\n\t* [System.Collections.IDictionary](#systemcollectionsidictionary)\n\t\t* [System.Collections.Dictionary](#systemcollectionsdictionary)\n\t* [List, Dictionary和序列化](#list-dictionary和序列化)\n* [Reactive \u0026 Watch](#reactive--watch)\n\n## 安装\n\n安装Lua后，下载**PLoop**或者使用git clone复制本项目到**LUA_PATH**所在目录，如果不清楚位置，可以使用 `print(package.path)`打印出来，一般以`\\?\\init.lua`结尾的路径都可以。之后就可以使用`require \"PLoop\"`加载本系统。\n\n也可以将**PLoop**保存到项目目录下，使用如下方式加载\n\n```lua\npackage.path = package.path .. \";项目所在路径/?/init.lua;项目所在路径/?.lua\"\n\nrequire \"PLoop\"\n````\n\n如果你需要按需加载，或者有独立的Lua文件加载系统，可以查看**PLoop/init.lua**了解文件的加载顺序。\n\n\n## 从使用集合开始\n\n在开始介绍面向对象系统之前，我们先介绍基于**PLoop**的部分应用, 首先以常用的集合处理开始。\n\n在Lua中，通常使用table保存数据有两种形式：\n\n* 数组，这里面我们通常只需要有序值\n* 哈希表，键和值都是我们需要的数据\n\n在**PLoop**中，我们通常使用**System.Collections.List**操作数组，**System.Collections.Dictionary**操作哈希表。\n\n### List的创建\n\nList对象有多种构造方式:\n\n构造体                           |结果\n:--------------------------------|:--------------------------------\nList(table)                      |将传入的table直接封装为List对象，无需构建新对象，也没有赋值处理\nList(listobject)                 |复制其他List对象的元素\nList(iterator, object, index)    |使用类似List(ipairs{1, 2, 3})，使用迭代器返回的元素构建列表\nList(count, func)                |循环count次，调用func(i)将返回值作为元素来构建列表\nList(count[, init])              |构建一个有count个元素，值全是init或者索引值(init不存在)的列表\nList(...)                        |使用输入的元素构建一个列表，不过上面的构造体优先级高，如果冲突或者无法确保的话（参数数目和类型），可以使用List{...}来构建，效果一样\n\n下面是一些创建用例:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t-- List(table)\n\to = {1, 2, 3}\n\tprint(o == List(o))  -- true\n\n\t-- List(count)\n\tv = List(10)         -- {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n\n\t-- List(count, func)\n\tv = List(10, function(i) return math.random(100) end) -- {46, 41, 85, 80, 62, 37, 29, 91, 62, 37}\n\n\t-- List(...)\n\tv = List(1, 5, 4)    -- {1, 5, 4}\nend)\n\nprint(v) -- nil\nprint(List) -- nil\n\nimport \"System.Collections\"\n\nprint(List) -- System.Collections.List\n```\n\n这是我们的第一个PLoop用例，**PLoop**有很多和通常Lua开发不同的设计，首先这里使用了 `PLoop(function(_ENV) end)`来封装和调用处理代码，这种设计是为了解决Lua开发的常见难点(以下关于环境的讨论，如果无法理解可以先行跳过，不影响阅读）:\n\n* Lua的每个文件都可以视为一个函数被执行，而Lua的每个函数都有一个环境与之关联，环境就是Lua的普通table，这个函数中访问的全局变量就是这个环境中的字段。而默认情况下，这个环境就是`_G`。\n\n\t协作开发时，所有程序创建和读取的全局变量都会保存在`_G`中，这很容易引起冲突，为了避免重名冲突，一般需要强制使用local变量，这种开发方式并不自由，也过多的创建了闭包。\n\n* 如**System.Collections.List**所示，通常为了避免同名类型冲突，一般使用命名空间来管理各种类型，为了在`_G`中使用**List**，我们需要使用`import \"System.Collections\"`来将这个命名空间的类型导入`_G`中，这点在上面的例子中最后几行可以看到。\n\n\t如果，我们有一个界面库提供**System.Form.List**类型，这是一个界面类，如果也同样被导入到`_G`中，这两个类型就会因为重名导致程序出错。\n\n究其根源就在于，所有代码的默认执行环境都是`_G`，那么只要每个处理代码运行在各自的私有环境中，就可以完全避免重名问题，也无需特意使用local来申明函数和共用数据（函数内该用local的自然该用local，效率不同）。\n\n在之前的例子中，封装代码的函数被传给**PLoop**后，将被绑定一个私有且特殊的**PLoop**环境，然后被执行。至于为什么采用这种形式，原因在于Lua的环境控制在5.1到5.2两个版本间有重大的变化，为了通用性，**PLoop**使用`PLoop(function(_ENV) end)`的形式来封装和调用代码，之后也会看到其他类似的处理，比如定义类`class \"A\" (function(_ENV) end)`。（如果你不了解`_ENV`，可以参考Lua5.2的更新说明）\n\n这么处理的好处我们将在以后的例子中逐步了解，这个例子中使用到的点是:\n\n* 申明的全局变量属于该私有环境，在`_G`中无法访问到被创建的变量v等。\n\n* 可以随意使用例如math.random这样的保存在`_G`中的公共库或者变量，这样不会造成性能问题，私有环境会在第一次访问后自动缓存这些变量。\n\n* 可以直接访问**List**类，**PLoop**中有公共命名空间这个概念，公共命名空间不需要被**import**即可被所有的**PLoop**环境访问，默认的公共命名空间是**System**, **System.Collections**和**System.Threading**，后面都会接触到。\n\n\t公共命名空间的访问优先级低于被import的命名空间，所以，如果使用了`import \"System.Form\"`，那么访问List访问到的是**System.Form.List**。\n\n* 我们可以使用关键字**import**为私有环境或者`_G`引入命名空间，之后可以使用里面保存的类型。不同点在于，向`_G`中导入，是全部拷贝到`_G`中，而私有环境仅记录下自己导入的命名空间，当需要时，才取出要用的类型（同样会被自动缓存）。\n\n回到List对象的创建，我们可以使用List这个类作为对象构建器，它会根据输入的参数来生成对象。\n\n通常来说，这些对象就是带有指定元表的普通table，我们可以直接使用**ipairs**对它进行遍历，也可以使用`obj[1]`这样的方式访问其中的元素。不过更进一步，我们可以使用**List**类提供的强大的对象方法来进行处理。\n\n\n### List的方法\n\n**List**类提供了基础的方法来完成对list对象的操作:\n\n方法                                     |描述\n:----------------------------------------|:--------------------------------\nClear(self)                              |清空list对象的元素\nContains(self, item)                     |检查list中是否存在item元素\nGetIterator(self)                        |返回用于元素遍历的迭代器\nIndexOf(self, item)                      |返回指定元素的索引\nInsert(self[, index], item)              |插入元素，即table.insert\nRemove(self, item)                       |移除元素\nRemoveByIndex(self[, index])             |按索引移除元素，即table.remove\nExtend(self, table)                      |将table的元素添加到list对象的末尾\nExtend(self, listobject)                 |将其他IList对象的元素添加到list对象的末尾\nExtend(self, iterator[, object[, index]])|将迭代器的返回元素添加到list对象的末尾\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tobj = List(10)\n\n\tprint(obj:RemoveByIndex()) -- 10\nend)\n```\n\n```lua\nrequire \"PLoop\"\n\nPLoop (function(_ENV)\n\t-- 1,2,3,4,5,6,7,8,9\n\tprint(table.concat(List{1, 2, 3, 4}:Extend(XList(5, 9)), \",\"))\nend)\n```\n\n### 动态列表\n\n在上面例子中，使用了XList这一个动态列表来避免构造完整的元素列表，XList仅保留开始，结束和步长，利用迭代器来返回对应的索引值：\n\n```lua\nrequire \"PLoop\"\n\nPLoop (function(_ENV)\n\t-- 开始, 结束[, 步长]\n\tXList(5, 10, 2):Each(print)\n\n\t-- 步长可以是负数\n\tXList(4, 1, -1):Each(print)\n\n\t-- 结束\n\t-- 开始和步长默认1\n\tXList(10):Map(\"x=\u003ex^2\"):Each(print)\n\n\t-- 迭代函数[，列表[，索引]]\n\tXList(ipairs{1, 2, 3, 4}):Each(print)\n\n\t-- 列表\n\tXList{1, 2, 3, 4}:Each(print)\n\tXList(List(10):Range(5, 8)):Each(print)\nend)\n```\n\n这种方式可以极大的节省内存占用和赋值操作，XList也扩展了**System.Collections.IList**, 我们可以使用Map方法来得到实际值，以及使用其他的链式处理。\n\n\n### List的遍历\n\n**List**和**Dictionary**都扩展了**System.Collections.Iterable**接口，这个接口要求集合类都需要提供**GetIterator**方法来提供遍历用的迭代器:\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tobj = List(10)\n\n\tfor _, v in obj:GetIterator() do print(v) end\nend)\n```\n\n**List**对象是数组，所以，实际来说，它的**GetIterator**方法就是**ipairs**，从这个意义上看，**List**还没有实际使用价值，下面我们看的是它的进阶遍历:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tobj = List(10)\n\n\t-- 按顺序打印list中的每个元素\n\tobj:Each(print)\n\n\t-- 按顺序打印所有的偶数\n\tobj:Filter(function(x) return x%2 == 0 end):Each(print)\n\n\t-- 按顺序打印最后三个数字\n\tobj:Range(-3, -1):Each(print)\n\n\t-- 打印所有的奇数\n\tobj:Range(1, -1, 2):Each(print)\n\n\t-- 按顺序打印所有数字的2^x\n\tobj:Map(function(x) return 2^x end):Each(print)\n\n\t-- 计算合计\n\tprint(obj:Reduce(function(x,y) return x+y end))\n\tprint(obj:Sum())\n\n\t-- 打印合并的字符串\n    -- 1,4,9,16\n    print(XList(1, 4):Map(\"x=\u003ex^2\"):Join(\",\"))\nend)\n```\n\n这里有两种类型的方法：队列方法类似**Range**, **Filter**和**Map**，终止方法类似**Each**, **Reduce**等。\n\n队列方法会记录操作和操作的参数，但并不执行，直到某个终止方法被调用，队列的操作会最终转换为一个新的迭代器供终止方法使用。实际处理来说，List对象调用某个队列方法后，一个流处理工作对象会被返回，所有的队列操作信息都保存在它里面，它本身也是一个特殊的列表对象（它的类不是List)，我们可以继续添加队列操作，直到最后调用终止方法，如果将上面的操作分开看，就是:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tobj = List(10)\n\n\t-- 我们将解析下面的操作\n\t-- obj:Range(1, -1, 2):Map(function(x) return 2^x end):Each(print)\n\n\t-- 队列操作会返回一个流处理工作对象\n\tlocal worker = obj:Range(1, -1, 2)\n\n\t-- 虽然使用了赋值，但实际继续队列操作，依然是同一个\n\tworker = worker:Map(function(x) return 2^x end)\n\n\t-- 调用Each终止方法的实际处理\n\tfor _, v in worker:GetIterator() do\n\t\tprint(v)\n\tend\nend)\n\n```\n\n* 流处理工作对象是系统内部用的对象，它完全被系统控制，在处理完成后，它会被系统回收以备下一个集合操作使用，所以，不会因为你多次使用这类集合操作导致对象不断被创建，造成过多的GC回收，同样，作为使用者不应自己获取流处理工作对象，进行操作，避免和系统处理冲突（比如记录下，终止操作后，继续使用）。\n\n* 和其他的Lua集合库不同，在上面的各种操作中，并不会有缓存table或者匿名函数被创建，所以，即便进行上万次的操作，也不会因为内存增长导致过多的gc开销。它的实现细节我们会在**协程**相关部分再了解。\n\n下面是队列方法的清单:\n\n方法                                     |描述\n:----------------------------------------|:--------------------------------\nFilter(self, func)                       |将元素传入这个函数，如果返回非false值，那么元素将继续用于之后的操作\nFilter(self, name, value)                |如果`element[name] == value`，那么元素将被继续用于之后的操作\nMap(self, func)                          |将元素传入函数，返回值将作为替代元素用于之后的操作\nMap(self, name)                          |使用 `element[name]`作为替代元素用于之后的操作\nRange(self[, start[, stop[, step]]])     |只使用返回内的符合步数的元素用于之后的操作，start默认1，stop默认-1，step默认1\n\n下面是终止方法的清单:\n\n方法                                     |描述\n:----------------------------------------|:--------------------------------\nAll(self, func, ...)                     |将元素和...参数传入函数，如果所有元素的处理结果都是非false，那么返回true，否则false\nAny(self, func, ...)                     |将元素和...参数传入函数，如果有一个元素的处理结果非false，返回true，否则false\nEach(self, func, ...)                    |将所有元素附带...参数传入函数执行\nEach(self, name, ...)                    |如果`element[name]`是方法（函数）, 它将被调用，...参数也会被传入，否则`element[name] = ...` 将被使用\nFirst(self, func, ...)                   |返回第一个使`func(element, ...)`返回非false值的元素\nFirst(self)                              |返回列表的第一个元素\nLast(self, func, ...) \t\t\t\t\t |返回最后一个使`func(element, ...)`返回非false值的元素\nLast(self)            \t\t\t\t\t |返回列表的最后一个元素\nReduce(self, func[, init])               |用于合并元素，参考上面计算总值的例子\nToList(self[, listtype])                 |使用迭代返回的元素创建一个新的列表对象，默认列表类型是**List**\nSum(self)                                |返回列表所有元素的和值\nJoin(self[, sep])                        |使用分隔符合并列表中的所有字符串\n\n\n### List的排序\n\n**List**的对象都是顺序列表，我们可以根据对比规则来对它的元素进行排序，系统为顺序列表提供了很多排序算法:\n\n排序方法                                        |描述\n:-----------------------------------------------|:--------------------------------\nReverse(self[, start[, stop]])                  |反转列表，因为它会修改列表对象本身，也算作排序之一，start默认1，stop默认-1\nBubbleSort(self, [compare[, start[, stop]]])    |使用冒泡排序，compare默认值是`function(x, y) return x \u003c y end`\nCombSort(self, [compare[, start[, stop]]])      |使用梳排序\nHeapSort(self, [compare[, start[, stop]]])      |使用堆排序\nInsertionSort(self, [compare[, start[, stop]]]) |使用插入排序\nMergeSort(self, [compare[, start[, stop]]])     |使用归并排序\nQuickSort(self, [compare[, start[, stop]]])     |使用快速排序\nSelectionSort(self, [compare[, start[, stop]]]) |使用选择排序\nSort(self, [compare[, start[, stop]]])          |Lua的自带排序，也就是table.sort\nTimSort(self, [compare[, start[, stop]]])       |使用timsort排序\n\n下面是一段测试代码:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tlocal random = math.random\n\tlocal function val() return random(500000) end\n\n\tfunction test(cnt, sortMethod)\n\t\tcollectgarbage()\n\n\t\tlocal st = os.clock()\n\n\t\tfor i = 1, cnt do\n\t\t\tlocal lst = List(1000, val)\n\t\t\tlst[sortMethod](lst)\n\t\tend\n\n\t\tprint(sortMethod, \"Cost\", os.clock() - st)\n\tend\n\n\ttest(100, \"BubbleSort\")\n\ttest(100, \"CombSort\")\n\ttest(100, \"HeapSort\")\n\ttest(100, \"InsertionSort\")\n\ttest(100, \"MergeSort\")\n\ttest(100, \"QuickSort\")\n\ttest(100, \"SelectionSort\")\n\ttest(100, \"Sort\")\n\ttest(100, \"TimSort\")\nend)\n```\n\nLua5.1下的结果是\n\n```\nBubbleSort      Cost    13.916\nCombSort        Cost    0.422\nHeapSort        Cost    0.484\nInsertionSort   Cost    4.772\nMergeSort       Cost    0.535\nQuickSort       Cost    0.281\nSelectionSort   Cost    6.417\nSort            Cost    0.109\nTimSort         Cost    0.547\n```\n\n通常，Lua自带的排序是最佳选择（虽然它不稳定），不过如果在luajit下面:\n\n```\nBubbleSort      Cost    0.269\nCombSort        Cost    0.033\nHeapSort        Cost    0.038\nInsertionSort   Cost    0.125\nMergeSort       Cost    0.046\nQuickSort       Cost    0.018\nSelectionSort   Cost    0.075\nSort            Cost    0.084\nTimSort         Cost    0.036\n```\n\nLuajit的确很擅长这类重复性工作。\n\n\n### Dictionary的创建\n\n类似**List**，我们同样有多种创建Dictionary对象的方式:\n\n构造方法                               |结果\n:-------------------------------------|:--------------------------------\nDictionary()                          |创建一个空dictionary对象\nDictionary(table)                     |将输入的table转换成一个dictionary对象\nDictionary(table:IList, table:IList)  |接受两个数组或列表对象，第一个数组的元素作为键，第二个数组的元素作为值，构建一个新的dictionary对象\nDictionary(dictionary)                |复制dictionary对象的键值对，创建新的对象\nDictionary(iter, obj, index)          |使用迭代器产生的键值对创建新的dictionary对象\n\n下面是一些例子:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tDictionary(_G) -- Convert the _G to a dictionary\n\n\t-- key map to key^2\n\tlst = List(10)\n\tDictionary(lst, lst:Map(function(x)return x^2 end))\nend)\n```\n\n\n### Dictionary的方法\n\n这些dictionary对象实际就是普通的哈希表，所以我们可以使用**pairs**来遍历它们，也可以直接使用`obj[key] = value`去修改它们，这些操作和普通table是一样的，所以**Dictionary**的**GetIterator**方法实际就是**pairs**.\n\n字典类仅定义一个方法用于更新自己\n\n方法                                     |描述\n:----------------------------------------|:--------------------------------\nUpdate(self, table)                      |使用table的键值对更新自己\nUpdate(self, IDictionary)                |使用自他IDictionary对象的键值对更新自己\nUpdate(self, iter[, obj[, idx])          |使用迭代器返回的键值对更新自己\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tv = Dictionary(List(5), List(5))\n\tv:Update{ [3] = 9, [4] = 16 }\n\n\t-- 1   1\n\t-- 2   2\n\t-- 3   9\n\t-- 4   16\n\t-- 5   5\n\tv:Each(print)\nend)\n```\n\n\n### Dictionary的遍历\n\n类似于**List**，**Dictionary**同样可以使用队列方法和终止方法。\n\n队列方法清单:\n\n方法                                     |描述\n:----------------------------------------|:--------------------------------\nFilter(self, func)                       |将键值对传入函数，如果返回非false值，键值对将用于之后的操作\nMap(self, func)                          |将键值对传入函数，返回的值将作为替代值和键一起用于之后的操作\n\n终止方法:\n\n方法                                     |描述\n:----------------------------------------|:--------------------------------\nEach(self, func, ...)                    |将所有的键值对传入函数\nGetKeys(self)                            |返回一个迭代器，使用类似`for index, key in dict:GetKeys() do print(key) end`\nGetValues(self)                          |返回一个迭代器，使用类似`for index, value in deict:GetValues() do print(value) end\nReduce(self, func, init)                 |合并所有键值对，详见后面的例子\n\n另外**Dictionary**也可以使用一种终止属性:\n\n属性                                     |描述\n:----------------------------------------|:--------------------------------\nKeys                                     |返回一个列表的流处理工作对象，代表所有键\nValues                                   |返回一个列表的流处理工作对象，代表所有值\n\n通过这两个终止属性，我们可以将dictionary操作转换成list操作。\n\n下面是一些例子:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t-- 获取_G的所有键，转换为List后，排序，再打印\n\tDictionary(_G).Keys:ToList():Sort():Each(print)\n\n\t-- 计算所有值的总和\n\tprint(Dictionary{ A = 1, B = 2, C = 3}:Reduce(function(k, v, init) return init + v end, 0))\nend)\n\n```\n\n**List**和**Dictionary**的队列和终止，以及排序方法并非定义在它们内部，而是由接口提供，等了解类和接口后，我们可以创建新的集合类型扩展这些接口，然后直接享受这些方法带来的便利。\n\n\n### 动态字典\n\n类似动态列表的处理，我们也可以基于字典对象，哈希表，键值对列表来构建动态字典，动态字典不会实际生成字典键值对，在很多场合可以优化处理:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t-- 键值对列表\n\tXDictionary(List(4), {\"1st\", \"2nd\", \"3rd\", \"4th\"}):Each(print)\n\n\t-- 字典对象或哈希表\n\tXDictionary(_G):Each(print)\n\n\t-- 迭代器\n\tXDictionary(pairs(_G)):Each(print)\nend)\n```\n\n\n## 特性(Attribute)和协程池(Thread Pool)\n\n**List**和**Dictionary**展示了对象的构建和使用，接下来，我们可以来看关于**PLoop**私有环境的一些特殊用法。首先是特性和协程的合用：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Iterator__()\n\tfunction iter(i, j)\n\t\tfor k = i, j do\n\t\t\tcoroutine.yield(k)\n\t\tend\n\tend\n\n\t-- print 1-10 for each line\n\tfor i in iter(1, 10) do\n\t\tprint(i)\n\tend\nend)\n```\n\n和`_G`不同，**PLoop**的私有环境，会监视新全局变量的定义(通过__newindex），当函数iter被定义时，系统会检测是否有注册的特性需要被使用在这个函数上，而之前我们使用了`__Iterator__()`。\n\n`__Iterator__`是定义在**System.Threading**命名空间的一个特性类，当我们使用它创建对象时，这个对象就会被注册到系统中，等待下一个被定义的特性目标（比如函数，类等）。特性被用来对特性目标进行修改或者附着数据。\n\n`__Iterator__`这个特性是用于封装目标函数，使调用它时，它会作为一个迭代器并被运行在一个协程中，然后我们可以使用**coroutine.yield**来依次返回值:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t-- 计算斐波那契数列\n\t__Iterator__()\n\tfunction Fibonacci(maxn)\n\t\tlocal n0, n1 = 1, 1\n\n\t\tcoroutine.yield(0, n0)\n\t\tcoroutine.yield(1, n1)\n\n\t\tlocal n = 2\n\n\t\twhile n \u003c= maxn  do\n\t\t\tn0, n1 = n1, n0 + n1\n\t\t\tcoroutine.yield(n, n1)\n\t\t\tn = n + 1\n\t\tend\n\tend\n\n\t-- 1, 1, 2, 3, 5, 8\n\tfor i, v in Fibonacci(5) do print(v) end\n\n\t-- 我们也可以依照迭代器的习惯，将参数在之后传入\n\t-- 这个迭代器会自动合并所有参数\n\t-- 1, 1, 2, 3, 5, 8\n\tfor i, v in Fibonacci(), 5 do print(v) end\nend)\n```\n\n之前列表的流处理工作对象的**GetIterator**方法就是使用这个机制实现的，所以，它不需要生成任何缓存表或者构建匿名函数来完成它的工作。\n\n你同样可以直接使用**coroutine.wrap**来达成同样效果，但区别在于，**PLoop**内置了协程池(因为Lua的协程打印出来名字是thread，也可以当作线程池理解，这也是为什么命名空间的名字是Threading而不是Coroutine)。\n\n使用`__Iterator__`封装的函数，被调用时将从协程池中获取一个协程来执行操作，当这个函数的操作执行完成后，这个协程会被协程池回收备用，这样可以有效的避免协程的生成和GC处理。\n\n`__Iterator__`仅用于创建迭代器，我们看一个协程更普遍的用法:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t-- 以协程运行函数\n\t__Async__()\n\tfunction printco(i, j)\n\t\tprint(coroutine.running())\n\tend\n\n\t-- 运行结果相同，系统会一直复用这些协程\n\tfor i = 1, 10 do\n\t\tprintco()\n\tend\nend)\n```\n\n**PLoop**很推荐使用这种方式来进行异步处理，通过协程池和这两个特性，可以使开发者更集中在异步逻辑处理上。\n\n\n## 拼写错误检查\n\nLua调试上有很多麻烦，如果出错的情况还比较好处理，但会有隐藏的问题点，比如`if a == ture` 这样的处理，ture是不存在的变量，Lua默认作为nil处理了，这样if判定依然可以继续进行，但结果不可能正确。\n\n我们来看如何在**PLoop**中解决它。\n\n### 读取不存在的全局变量\n\n在使用require加载**PLoop**之前，我们可以定义一个名为**PLOOP_PLATFORM_SETTINGS**的table，用来调整**PLoop**的内部设定:\n\n```lua\nPLOOP_PLATFORM_SETTINGS = { ENV_ALLOW_GLOBAL_VAR_BE_NIL = false }\n\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tlocal a = ture  -- Error: The global variable \"ture\" can't be nil.\n\n\tif a then\n\t\tprint(\"ok\")\n\tend\nend)\n```\n\n关闭**ENV_ALLOW_GLOBAL_VAR_BE_NIL**后，**PLoop**的所有私有环境会使用强制模式，禁止访问任何不存在的变量(未定义也无法从命名空间和基础环境中获取到的)，这样就可以快速的定位这类错误。\n\n### 写非法全局变量\n\n如果我们漏写了`local`，会导致原本的局部变量被保存成全局，不过系统本身无法区分期望的全局变量和不期望的全局变量，所以，系统需要在平台设置里面指定一个过滤函数：\n\n\n```lua\nPLOOP_PLATFORM_SETTINGS = {\n\tGLOBAL_VARIABLE_FILTER = function(key, value)\n\t\t-- 不允许首字母是小写并且值是非函数的全局变量\n\t\tif type(key) == \"string\" and key:match(\"^%l\") and type(value) ~= \"function\" then\n\t\t\treturn true\n\t\tend\n\tend,\n}\n\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tTest = 1\n\n\tclass \"A\" (function(_ENV)\n\t\tfunction Test(self)\n\t\t\tch = 2 -- error: There is an illegal assignment for \"ch\"\n\t\tend\n\tend)\n\n\tA():Test()\nend)\n```\n\n当过滤函数返回true时，这个赋值会引发error，代码将停止运行，如果期望只得到警告，但不终止代码的话，可以添加一个设置：\n\n\n```lua\nPLOOP_PLATFORM_SETTINGS = {\n\tGLOBAL_VARIABLE_FILTER = function(key, value)\n\t\t-- Don't allow the lowercase key with non-function value\n\t\tif type(key) == \"string\" and key:match(\"^%l\") and type(value) ~= \"function\" then\n\t\t\treturn true\n\t\tend\n\tend,\n\tGLOBAL_VARIABLE_FILTER_USE_WARN = true,\n}\n\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tTest = 1\n\n\tclass \"A\" (function(_ENV)\n\t\tfunction Test(self)\n\t\t\tch = 2 -- [PLoop: Warn]There is an illegal assignment for \"ch\"@path_to_file\\file.lua:18\n\t\tend\n\tend)\n\n\tA():Test()\nend)\n```\n\n可以看到，如果可能，系统会提供出赋值的调用位置。如果需要，也可以将这个过滤函数作为记录器使用，只需要增加一个设置，调用位置就会作为第三个参数传入：\n\n```lua\nPLOOP_PLATFORM_SETTINGS = {\n\tGLOBAL_VARIABLE_FILTER = function(key, value, path)\n\t\tprint(\"Assign '\" .. key .. \"'\" .. path )\n\tend,\n\tGLOBAL_VARIABLE_FILTER_GET_CALLLINE = true,\n}\n\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tTest = 1  -- Assign 'Test'@path_to_file\\file.lua:11\n\n\tclass \"A\" (function(_ENV)\n\t\tfunction Test(self)\n\t\t\tch = 2 -- Assign 'ch'@path_to_file\\file.lua:15\n\t\tend\n\tend)\n\n\tA():Test()\nend)\n```\n\n如果要获取调用位置，`debug.getinfo`函数必须存在。\n\n### 访问不存在的对象字段\n\n我们也可以禁止访问不存在的对象字段：\n\n```lua\nPLOOP_PLATFORM_SETTINGS = { OBJECT_NO_RAWSEST = true, OBJECT_NO_NIL_ACCESS = true }\n\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t-- 定义一个具有Name和Age属性的类\n\tclass \"Person\" (function(_ENV)\n\t\tproperty \"Name\" { type = String }\n\t\tproperty \"Age\"  { type = Number }\n\tend)\n\n\to = Person()\n\n\to.Name = \"King\" -- Ok\n\n\to.name = \"Ann\"  -- Error: The object can't accept field that named \"name\"\n\n\tprint(o.name)   -- Error: The object don't have any field that named \"name\"\nend)\n```\n\n开启**OBJECT_NO_RAWSEST**和**OBJECT_NO_NIL_ACCESS**会禁止向对象中写入或者读取不存在的属性或者字段，配合上面的设置，可以有效的避免开发过程中的拼写错误。当运行在工作环境时，最好不要使用这些配置，去掉可以轻微优化访问速度。\n\n\n## 类型验证\n\n**PLoop**使Lua成为一门强类型语言，它提供了多种类型验证方式来避免错误传递的过远导致很难回溯。\n\n为了确保函数调用正确并避免错误发生的堆栈位置过深，通常我们需要在函数逻辑开始前写上大量的判定处理（也包括对应不同的参数处理），然而工作环境中，因为测试完毕，我们往往并不需要这些检查。\n\n在**PLoop**中，这将不成为问题:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Arguments__{ String, Number }\n\tfunction SetInfo(name, age)\n\tend\n\n\t-- Error: Usage: SetInfo(System.String, System.Number) - the 2nd argument must be number, got boolean\n\tSetInfo(\"Ann\", true)\nend)\n```\n\n`__Arguments__`是定义在**System**中的特性类，它用于将函数参数的名字，类型，默认值等信息和参数绑定，并且封装这个函数，补上参数验证。\n\n**String**和**Number**是结构体类型，用于值验证，我们会在结构体部分具体了解。\n\n当我们需要发布项目时，我们无需再进行类型验证，这时可以在平台配置表关闭类型验证(并非所有类型验证都会关闭，不过细节留给系统即可):\n\n```lua\nPLOOP_PLATFORM_SETTINGS = { TYPE_VALIDATION_DISABLED = true }\n\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Arguments__{ String, Number }\n\tfunction SetInfo(name, age)\n\tend\n\n\t-- No error now\n\tSetInfo(\"Ann\", true)\nend)\n```\n\n为了提供一整套类型验证系统，我们需要更多的类型来描述数据。在**PLoop**中，默认提供四种类型: enum, struct, interface 和 class\n\n\n## enum 枚举类型\n\n枚举是一种数据类型，由一组由键值组成的元素组成，枚举值的名称通常用来作为常量使用。\n\n定义枚举类型的格式是\n\n\n```lua\nenum \"name\" { -- key-value pairs }\n```\n\n在定义表中，对于每个键值对，如果键是字符串，则键将用作元素的名称，值是元素的值。 如果该键是一个数字并且该值是字符串，则该值将用作该元素的名称和值，否则该键值对将被忽略。\n\n定义完成后，我们可以使用`enumeration[elementname]`来通过元素名获取值，或者使用`enumeration(value)`来通过值获取元素名。\n\n在定义了这个枚举类型的环境中，或者import了它的环境中，我们也可以直接使用枚举值名称来直接访问它们。\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tnamespace \"TestNS\"\n\n\tenum \"Direction\" { North = 1, East = 2, South = 3, West = 4 }\n\n\tprint(Direction.South) -- 3\n\tprint(Direction.NoDir) -- nil\n\tprint(Direction(3))    -- South\n\n\tprint(East)            -- 2\nend)\n\nPLoop(function(_ENV)\n\timport \"TestNS.Direction\"\n\n\tprint(South)           -- 3\nend)\n```\n\n除了自行指定键值对外，系统也提供了其他特性来自动生成元素：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__AutoIndex__{ North = 1, South = 5 }\n\tenum \"Direction\" {\n\t\t\"North\",\n\t\t\"East\",\n\t\t\"South\",\n\t\t\"West\",\n\t}\n\n\tprint(East) -- 2\n\tprint(West) -- 6\nend)\n```\n\n`__AutoIndex__`特性用于转换一个字符串数组表，将内部的元素转换为键，按顺序赋予自增值，同时也可以在构造`__AutoIndex__`对象时，传入一个特定的表，用于指定某些元素的值。效果见上面的例子。\n\n另一种个特殊特性类是`__Flags__`，它用于标记枚举类型为位标志枚举类型，它的元素值为2^N（也可以用0值)，之后我们可以将这些枚举值进行叠加，也可以很方便的解析:\n\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Flags__()\n\tenum \"Days\" {\n\t\t\"SUNDAY\",\n\t\t\"MONDAY\",\n\t\t\"TUESDAY\",\n\t\t\"WEDNESDAY\",\n\t\t\"THURSDAY\",\n\t\t\"FRIDAY\",\n\t\t\"SATURDAY\",\n\t}\n\n\tv = SUNDAY + MONDAY + FRIDAY\n\n\t-- 和普通枚举类型不同，使用值返回枚举名得到的是一个迭代器\n\t-- SUNDAY  1\n\t-- MONDAY  2\n\t-- FRIDAY  32\n\tfor name, val in Days(v) do\n\t\tprint(name, val)\n\tend\n\n\t-- 或者也可以传入一个table来缓存结果\n\tlocal result = Days(v, {})\n\tfor name, val in pairs(result) do print(name, val) end\n\n\tprint(Enum.ValidateFlags(MONDAY, v)) -- true\n\tprint(Enum.ValidateFlags(SATURDAY, v)) -- false\nend)\n```\n\n### System.Enum\n\n**System.Enum**是一个反射类型，我们可以使用它来获取枚举类型的内部信息，下面是一个可用的方法清单（并非全部，其他都是仅能被系统使用的）:\n\n静态方法                        |描述\n:-------------------------------|:-----------------------------\nGetDefault(enum)                |获得枚举类型的默认值\nGetEnumValues(enum[, cache])    |如果cache存在，将枚举元素作为键值对保存在cache中并返回cache，如果不存在，返回一个迭代器供for循环使用\nIsFlagsEnum(enum)               |是否是位标志枚举类型\nIsImmutable(enum)               |永远返回true，表明所有枚举类型是不可变值，意思是，值通过枚举类型的校验时，不会发生改变\nIsSealed(enum)                  |枚举类型是否封闭，不可被重写\nParse(enum, value)              |和enum(value)功能一致\nValidateFlags(check, target)    |目标值是否含有检查值，用于位标志计算\nValidateValue(enum, value)      |如果value时枚举类型的值，那么返回value，否则返回nil\nValidate(target)                |如果目标是枚举类型，返回true，否则返回false\n\n在列表中，有两个未知的方法: **GetDefault**和**IsSealed**，需要使用两个相关的特性类：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Default__(\"North\") __AutoIndex__()\n\tenum \"Direction\" {\n\t\t\"North\",\n\t\t\"East\",\n\t\t\"South\",\n\t\t\"West\",\n\t}\n\n\tprint(Enum.GetDefault(Direction)) -- 1\n\n\t--如果没有封闭，新定义会覆盖原本的定义\n\t__Sealed__()\n\tenum \"Direction\" { North = \"N\", East = \"E\", South = \"S\", West = \"W\" }\n\n\tprint(Enum.GetDefault(Direction)) -- nil\n\n\t-- 封闭后，我们可以添加键值对\n\tenum \"Direction\" { Center = \"C\" }\n\n\t-- 但我们不能覆盖存在的键或者值\n\t-- Error: Usage: enum.AddElement(enumeration, key, value[, stack]) - The key already existed\n\tenum \"Direction\" { North = 1 }\n\n\t-- Error: Usage: enum.AddElement(enumeration, key, value[, stack]) - The value already existed\n\tenum \"Direction\" { C = \"N\" }\nend)\n```\n\n`System.__Default__`特性被用来设置枚举类型的默认值，这个默认值对枚举类型而言并没有什么用途，我们会在后面看到它的实际使用。\n\n`System.__Sealed__`特性用于封闭类型，避免它的定义被其他人覆盖，不过对于枚举类型来说，其他人依然可以扩展它。\n\n\n## struct 结构体\n\n结构体类型是**PLoop**中的主要数据类型，也用来作为数据契约提供类型验证等功能。基于它们的结构，**PLoop**提供四种结构体类型。\n\n\n### Custom 自定义结构体\n\n自定义结构体大多用来代表基本数据类型，例如number，string，更进一步的是例如自然数等特殊基本数据类型。\n\n从代表number的**System.Number**的定义开始：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t-- 环境 A\n\tstruct \"Number\" (function(_ENV)\n\t\t-- 环境 B\n\t\tfunction Number(value)\n\t\t\treturn type(value) ~= \"number\" and \"the %s must be number, got \" .. type(value)\n\t\tend\n\tend)\n\n\tv = Number(true)  -- Error : the value must be number, got boolean\nend)\n```\n\n类似于使用**PLoop**启用私有环境运行代码，在**PLoop**定义结构体同样使用这种调用方式，里面被调用函数体就是Number这个结构体的定义。\n\n这里的环境B是为了定义类型特殊设计的：\n\n* 环境B嵌套在环境A中，所以，环境A就是环境B的基础环境，环境B可以访问任何定义在或者被import在环境A中的变量。\n\n* 环境B是为了结构体定义特殊设计的，它会将一些特定赋值转换为类型的定义，比如这里的和类型同名的Number函数，会作为Number类型的**验证器**，也可以定义名为`__valid`的函数作为验证器（对应匿名结构体，类似`struct(function(_ENV) function __valid(val) end end)` )\n\n验证器被用来对输入的值进行校验，如果返回值是非false，那么意味着值并没有通过验证，通常来说，未通过验证需要返回一个错误信息，这个错误信息中的`%s`会被系统按照使用场所进行替换，如果仅返回true，那么系统会自动产生一个错误消息。\n\n在一些情况下，我们需要自动转换输入的值，这时就需要使用结构体的**初期化方法**:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tstruct \"AnyBool\" (function(_ENV)\n\t\tfunction __init(value)\n\t\t\treturn value and true or fale\n\t\tend\n\tend)\n\tprint(AnyBool(1))  -- true\nend)\n```\n\n名字为`__init`的函数会作为结构体的**初期化方法**，如果它的返回值不为nil，那么会作为新值替代掉原值。\n\n我们来看一个具体的使用例子:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Arguments__{ Callable, Number, Number }\n\tfunction Calc(func, a, b)\n\t\tprint(func(a, b))\n\tend\n\n\tCalc(\"x,y=\u003ex+y\", 1, 11) -- 12\n\tCalc(\"x,y=\u003ex*y\", 2, 11) -- 22\nend)\n```\n\n**System.Callable**是一个联合类型，它允许function，带有`__call`元表方法的对象，以及**System.Lambda**类型的数据。 **PLoop**中的lambda就是类似`\"x,y=\u003ex+y\"`这样的简单字符串，**System.Lambda**的**初期化方法**会将这个字符串转换为函数使用。所以，上面的例子中，Calc可以确认它拿到的func始终是可调用的值。\n\n**List**和**Dictionary**的方法（队列，终止，排序等）都使用**System.Callable**描述它的参数，所以，我们也可以使用类似的处理代码:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tList(10):Map(\"x=\u003ex^2\"):Each(print)\nend)\n```\n\n这就是**初期化方法**的工作方式。\n\n为了简化定义，结构体类型支持简单的继承机制，可以使用`__base`来指定一个基础结构体，基础结构体的验证器和初期化方法都会被继承，并在类型本身的验证器和初期化方法之前被调用，这个继承链可以一直添加下去，比如Number-\u003eInteger-\u003eNatureNumber-\u003e...\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tstruct \"Integer\" (function(_ENV)\n\t\t-- 指定Number为基础结构体\n\t\t__base = Number\n\n\t\tlocal floor = math.floor\n\n\t\tfunction Integer(value)\n\t\t\treturn floor(value) ~= value and \"the %s must be integer\"\n\t\tend\n\tend)\n\n\tv = Integer(true)  -- Error : the value must be number, got boolean\n\tv = Integer(1.23)  -- Error : the value must be integer\nend)\n```\n\n类似枚举类型，因为这些自定义结构体通常代表基础数据，我们可以为它指定默认值:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Default__(0)\n\tstruct \"Integer\" (function(_ENV)\n\t\t__base = Number\n\t\t__default = 0 -- 也可以向__default赋值替代__Default__特性\n\n\t\tlocal floor = math.floor\n\n\t\tfunction Integer(value)\n\t\t\treturn floor(value) ~= value and \"the %s must be integer\"\n\t\tend\n\tend)\n\n\tprint(Struct.GetDefault(Integer)) -- 0\nend)\n```\n\n同样，我们可以使用`__Sealed__`特性来封闭这个结构体类型，确保它不会被重定义:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Sealed__(0)\n\tstruct \"AnyBool\" (function(_ENV)\n\t\tfunction __init(value)\n\t\t\treturn value and true or fale\n\t\tend\n\tend)\n\n\t-- Error: Usage: struct.BeginDefinition(structure[, stack]) - The AnyBool is sealed, can't be re-defined\n\tstruct \"AnyBool\" (function(_ENV)\n\t\tfunction __init(value)\n\t\t\treturn value and true or fale\n\t\tend\n\tend)\nend)\n```\n\n**PLoop**系统提供了很多基本的自定义结构体:\n\n\n自定义结构体                  |描述\n:-----------------------------|:-----------------------------\n**System.Any**                |代表任意值\n**System.Boolean**            |代表布尔值\n**System.String**             |代表字符串\n**System.Number**             |代表数字\n**System.Function**           |代表函数\n**System.Table**              |代表table\n**System.Userdata**           |代表userdata\n**System.Thread**             |代表thread\n**System.AnyBool**            |转换任意值为布尔值\n**System.NEString**           |代表非空字符串\n**System.RawTable**           |代表没有元表的table\n**System.Integer**            |代表整型数字\n**System.NaturalNumber**      |代表自然数\n**System.NegativeInteger**    |代表负整数\n**System.NamespaceType**      |代表任意命名空间\n**System.EnumType**           |代表枚举类型，需要和System.Enum区分，System.Enum并非任何类型\n**System.StructType**         |代表任意结构体类型\n**System.InterfaceType**      |代表任意接口类型\n**System.ClassType**          |代表任意类类型\n**System.AnyType**            |代表任意可验证类型，默认包含枚举类型，结构体类型，接口类型或者类类型\n**System.Lambda**             |代表lambda值\n**System.Callable**           |代表callable值, 比如function, callable objecct, lambda\n**System.Guid**               |代表Guid\n\n\n### Member 成员结构体类型\n\n成员结构体代表具有特定字段的表结构，首先来看一个例子\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tstruct \"Location\" (function(_ENV)\n\t\tx = Number\n\t\ty = Number\n\tend)\n\n\tloc = Location{ x = \"x\" }    -- Error: Usage: Location(x, y) - x must be number\n\tloc = Location(100, 20)\n\tprint(loc.x, loc.y)          -- 100  20\nend)\n```\n\n在前面我们已经知道这个定义环境是特别为结构体设计的，所以，当它检查赋值的双方，键为字符串，值为**System.AnyType**时，它就可以将这次赋值转变为添加一个成员变量，这个成员的类型之后会被用来进行值的字段校验。\n\n从上面的例子也可以看到，成员结构体可以用来构造值，他会将参数按照成员的定义顺序依次保存在新值中。只有成员结构体可以作为这种用途。\n\n使用`x = Number`是最简单的成员申明方式，不过实际上还有更多的信息需要填充，下面是正规的定义方式:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tstruct \"Location\" (function(_ENV)\n\t\tmember \"x\" { type = Number, require = true }\n\t\tmember \"y\" { type = Number, default = 0    }\n\tend)\n\n\tloc = Location{}            -- Error: Usage: Location(x, y) - x can't be nil\n\tloc = Location(100)\n\tprint(loc.x, loc.y)         -- 100  0\nend)\n```\n\n**member**是只能在结构体定义中使用的关键字，它需要一个名字和定义表来定义新的成员。定义表的字段是(字段大小写无视，均非必需):\n\n字段              |描述\n:-----------------|:--------------\ntype              |成员的类型，符合**System.AnyType**的值\nrequire           |布尔值, 成员是否不能为nil\ndefault           |成员的默认值\n\n同样，成员结构体也支持验证器和初始化方法:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tstruct \"MinMax\" (function(_ENV)\n\t\tmember \"min\" { Type = Number, Require = true }\n\t\tmember \"max\" { Type = Number, Require = true }\n\n\t\tfunction MinMax(val)\n\t\t\treturn val.min \u003e val.max and \"%s.min can't be greater than %s.max\"\n\t\tend\n\tend)\n\n\tv = MinMax(100, 20) -- Error: Usage: MinMax(min, max) - min can't be greater than max\nend)\n```\n\n因为成员结构体的值都是table，所以，我们也可以定义些结构体方法，这些方法会被保存到验证或者创建的值里面以备使用:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tstruct \"Location\" (function(_ENV)\n\t\tmember \"x\" { Type = Number, Require = true }\n\t\tmember \"y\" { Type = Number, Default = 0    }\n\n\t\tfunction GetRange(val)\n\t\t\treturn math.sqrt(val.x^2 + val.y^2)\n\t\tend\n\tend)\n\n\tprint(Location(3, 4):GetRange()) -- 5\nend\n```\n\n非结构体类型名，也不是`__valid`等特殊名字的函数会作为结构体方法保存。我们也可以定义静态方法，仅供结构体自身使用（也可以给自定义结构体定义静态方法)。\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tstruct \"Location\" (function(_ENV)\n\t\tmember \"x\" { Type = Number, Require = true }\n\t\tmember \"y\" { Type = Number, Default = 0    }\n\n\t\t__Static__()\n\t\tfunction GetRange(val)\n\t\t\treturn math.sqrt(val.x^2 + val.y^2)\n\t\tend\n\tend)\n\n\tprint(Location.GetRange{x = 3, y = 4}) -- 5\nend)\n```\n\n`System.__Static__`用于指明下一个定义的方法是静态方法。\n\n之前自定义结构体我们可以指定默认值，那么现在可以看看默认值的用法:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tstruct \"Number\" (function(_ENV)\n\t\t__default = 0\n\n\t\tfunction Number(value)\n\t\t\treturn type(value) ~= \"number\" and \"the %s must be number\"\n\t\tend\n\tend)\n\n\tstruct \"Location\" (function(_ENV)\n\t\tx = Number\n\t\ty = Number\n\tend)\n\n\tloc = Location()\n\tprint(loc.x, loc.y)         -- 0    0\nend)\n```\n\n所以，成员会使用成员类型的默认值作为它的默认值来使用。\n\n成员结构体同样可以指定基础结构体，它会继承基础结构体的成员定义，非静态的方法，验证器和初始化方法，不过通常不推荐这么做。\n\n系统默认仅提供一个成员结构体:\n\n成员结构体                    |描述\n:-----------------------------|:-----------------------------\n**System.Variable**           |代表变量，在重载部分我们会具体看到它的用途\n\n\n### Array 数组结构体\n\n数组结构体代表含有一组同类型数据的数组table，这是一个比较简单的类型：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tstruct \"Location\" (function(_ENV)\n\t\tx = Number\n\t\ty = Number\n\tend)\n\n\tstruct \"Locations\" (function(_ENV)\n\t\t__array = Location\n\tend)\n\n\tv = Locations{ {x = true} } -- Usage: Locations(...) - the [1].x must be number\nend)\n```\n\n同样，数组结构体也支持结构体方法，静态方法，基础结构体，验证器和初始化方法，不过通常没有这类需求。\n\n题外话，使用**PLoop**的序列化机制序列化一个数组结构体数据时，因为系统明确知道它是数组类型，所以，不需要进行验证就可以按照数组的方式序列化它，这对一些数据量比较大的场合非常有效。\n\n系统默认只提供一个数组结构体:\n\n数组结构体                    |描述\n:-----------------------------|:-----------------------------\n**System.Variables**          |代表一组变量，我们会在重载系统中具体看它的用途\n\n\n### Hash 键值对结构体\n\n同样，我们可以定义对应确定键值类型的哈希table：\n\n```lua\nrequire \"PLoop\" (function(_ENV)\n    struct \"SNMap\" (function(_ENV)\n        __key = String\n        __value = Number\n    end)\n\n    v = SNMap{ key = true } -- the [value in value] must be number, got boolean\n    v = SNMap{ [1] = 23 } -- the [key in value] must be string, got number\nend)\n```\n\n\n### 使用table来定义结构体\n\n为了简化结构体的定义方式，我们也可以使用table来替代函数作为定义体:\n\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t-- 自定义结构体\n\t__Sealed__()\n\tstruct \"Number\" {\n\t\t__default = 0,  -- 指定默认值\n\n\t\t-- 数字索引的函数就是验证器\n\t\tfunction (val) return type(val) ~= \"number\" end,\n\n\t\t-- 也可以用特殊的键指定\n\t\t__valid = function (val) return type(val) ~= \"number\" end,\n\t}\n\n\tstruct \"AnyBool\" {\n\t\t-- 定义初始化方法\n\t\t__init = function(val) return val and true or false end,\n\t}\n\n\t-- 成员结构体\n\tstruct \"Location\" {\n\t\t-- 最好不用x = { type = Number }这类形式，因为无法确认成员定义的顺序\n\t\t{ name = \"x\", type = Number, require = true },\n\t\t{ name = \"y\", type = Number, require = true },\n\n\t\t-- 定义方法，不过无法定义静态方法\n\t\tGetRange = function(val) return math.sqrt(val.x^2 + val.y^2) end,\n\t}\n\n\t-- 数组结构体\n\t-- 数字索引的任意类型，会作为数组元素类型使用，也可以使用__array指定\n\tstruct \"Locations\" { Location }\n\n\t-- 哈希结构体\n\t-- 用类型作为键值即可\n\tstruct \"SNMap\" { [String] = Number }\nend)\n```\n\n### 减少验证消耗\n\n回到最开始的Number定义，因为错误消息是运行期动态创建的，但在**PLoop**的很多场合，都仅仅需要知道是否能验证通过，并不需要验证信息。\n\n验证器实际会接收到两个参数，第二个参数为true时，就表明系统不在意错误信息，仅在意是否验证失败，所以我们可以修改Number的定义为:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tstruct \"Number\" (function(_ENV)\n\t\tfunction Number(value, onlyvalid)\n\t\t\tif type(value) ~= \"number\" then return onlyvalid or \"the %s must be number, got \" .. type(value) end\n\t\tend\n\tend)\n\n\t-- The API to validate value with types (type, value, onlyvald)\n\tprint(Struct.ValidateValue(Number, \"test\", true))   -- nil, true\n\tprint(Struct.ValidateValue(Number, \"test\", false))  -- nil, the %s must be number, got string\nend)\n```\n\n当然，也可以直接返回true，让系统自己处理后面的部分。\n\n\n### 联合类型\n\n如果你的值可能是多种类型，你可以使用`+`号来创建联合验证类型，值只需要满足其中一个就可以通过验证:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t-- nil, the %s must be value of System.Number | System.String\n\tprint(Struct.ValidateValue(Number + String, {}, false))\nend)\n```\n\n可以联合任意的**System.AnyType**值，比如枚举类型，接口，结构体等。\n\n\n### 子类型\n\n如果我们需要的值一种类型，并且我们希望限定它必须是某个结构体的扩展结构体（用前者作为基础结构体），或者某个类的子类等，我们可以使用`-`来创建子类型验证结构体:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tstruct \"Integer\" { __base = Number, function(val) return math.floor(val) ~= val end }\n\tprint(Struct.ValidateValue( - Number, Integer, false))  -- Integer\nend)\n```\n\n### System.Struct\n\n类似**System.Enum**, **System.Struct**也是一个反射类型，我们可以用它获取结构体类型的内部信息:\n\n静态方法                                |描述\n:---------------------------------------|:-----------------------------\nGetArrayElement(target)                 |获得目标结构体的数组元素类型\nGetBaseStruct(target)                   |获得目标结构体的基础结构体\nGetDefault(target)                      |获得目标结构体的默认值，仅适用于自定义结构体\nGetMember(target, name)                 |获得目标结构体指定的成员\nGetMembers(target[, cache])             |如果cache存在，将成员按顺序保存并返回cache，否则返回一个用于for循环的迭代器\nGetMethod(target, name)                 |返回方法及一个表明是否静态方法的布尔值\nGetMethods(target[, cache])             |如果cache存在，将方法和名字保存在cache中，并返回cache，否则返回一个用于for循环的迭代器\nGetStructCategory(target)               |返回结构体的类型: CUSTOM, MEMBER, ARRAY, DICTIONARY\nIsImmutable(target)                     |目标结构体是否是不可变类型，即指通过校验不会被改变\nIsSubType(target, base)                 |目标结构体是否是base的扩展类型\nIsSealed(target)                        |目标结构体是否已经封闭，无法被重定义\nIsStaticMethod(taret, name)             |目标结构体的特定方法是否是静态方法\nValidateValue(target, value, onlyvalid) |使用目标结构体验证value，如果成功返回验证后的值，失败返回nil及一个错误消息\nValidate(target)                        |目标是否是一个结构体类型\n\n\n### System.Member\n\n在上面的**Struct.GetMemeber**和**Struct.GetMembers**两个API，我们会获得member对象，同样有一个**System.Member**作为反射类型可以帮助我们获得内部的信息:\n\n静态方法                                |描述\n:---------------------------------------|:-----------------------------\nGetType(member)                         |获得成员的类型\nIsRequire(member)                       |成员是否不可为nil\nGetName(member)                         |获得成员的名字\nGetDefault(member)                      |获得成员的默认值\n\n下面是一个例子:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tstruct \"Location\" (function(_ENV)\n\t\tx = Number\n\t\ty = Number\n\tend)\n\n\tfor index, member in Struct.GetMembers(Location) do\n\t\tprint(Member.GetName(member), Member.GetType(member))\n\tend\nend)\n```\n\n\n枚举类型和结构体类型都是值类型，通常用于类型验证。而接口和类系统将为我们提供完整的面向对象系统。\n\n\n## Class 类\n\n类是从一组行为，特征类似的对象中抽象出来的，类为对象提供了具体的实现，通过接口和继承等机制也确保了代码的高复用性和扩展性。\n\nLua中的对象就是带有特定元表的table。\n\n**PLoop**中，类定义主要由几部分组成:\n\n### 类方法和对象方法\n\n方法是供类或者其对象使用的函数，首先来看对象方法，对象方法是被对象使用的，它的第一个参数固定是self，代表对象本身:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\tfunction SetName(self, name)\n\t\t\tself.name = name\n\t\tend\n\n\t\tfunction GetName(self, name)\n\t\t\treturn self.name\n\t\tend\n\tend)\n\n\tAnn = Person()\n\tAnn:SetName(\"Ann\")\n\tprint(\"Hello \" .. Ann:GetName()) -- Hello Ann\nend)\n```\n\n和结构体的定义方式一样，我们使用函数作为类的定义体，在里面作为全局定义的函数会被注册为类的对象方法。之后，我们就可以构造对象，并调用这些方法。\n\n类似*Person*这样的类，它的对象的元表将被实现成\n\n```lua\n{\n\t__index = { SetName = function, GetName = function },\n\t__metatable = Person,\n}\n```\n\n**PLoop**的类会根据定义情况自行优化元表。\n\n*Person*类可以直接访问它的对象方法`Person.SetName(Ann, \"Ann\")` 和 `Ann:SetName(\"Ann\")`是一致的。\n\n类也可以有只能自己访问的静态方法，和结构体的静态方法一样，需要使用`System.__Static__`特性:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Color\" (function(_ENV)\n\t\t__Static__()\n\t\tfunction FromRGB(r, g, b)\n\t\t\t-- 对象的构建会在之后探讨\n\t\t\treturn Color {r = r, g = g, b = b}\n\t\tend\n\tend)\n\n\tc = Color.FromRGB(1, 0, 1)\n\tprint(c.r, c.g, c.b)\nend)\n```\n\n静态方法通常是辅助方法，所以，不需要第一个参数是self，因为它不一定是处理类对象的方法。\n\n\n### 元数据和对象构造\n\n**元数据**算是Lua元表方法的一个超集，除了通常的对象使用的元表方法外，还有些供类本身使用的元数据：\n\n\nKey            |Description\n:--------------|:--------------\n`__add`        |类对象的相加运算: a + b  -- a是类对象，下同\n`__sub`        |类对象的相减运算: a - b\n`__mul`        |类对象的相乘运算: a * b\n`__div`        |类对象的除法运算: a / b\n`__mod`        |类对象的取模运算: a % b\n`__pow`        |类对象的幂运算:   a ^ b\n`__unm`        |类对象的取负运算: - a\n`__idiv`       |类对象的整除运算: a // b\n`__band`       |类对象的与运算:   a \u0026 b\n`__bor`        |类对象的或运算:   a | b\n`__bxor`       |类对象的异或运算: a ~ b\n`__bnot`       |类对象的非运算:   ~a\n`__shl`        |类对象的左移运算: a \u003c\u003c b\n`__shr`        |类对象的右移运算: a \u003e\u003e b\n`__concat`     |类对象的连接运算: a .. b\n`__len`        |类对象的长度计算: #a\n`__eq`         |类对象的相等判定: a == b\n`__lt`         |类对象的小于判定: a \u003c b\n`__le`         |类对象不大于判定: a \u003c= b\n`__index`      |类对象的域查询:   return a[k]\n`__newindex`   |类对象的新值处理: a[k] = v\n`__call`       |类对象的调用:     a(...)\n`__gc`         |类对象的GC处理，暂时没什么用途\n`__tostring`   |类对象字符串转换: tostring(a)\n`__ipairs`     |占位，非可用，请用集合处理替代\n`__pairs`      |占位，非可用，请用集合处理替代\n`__exist`      |类构建对象时根据参数检查是否复用存在的对象\n`__field`      |对象的初始化字段和值\n`__new`        |类构建对象时，生成将被封装成对象的table的方法\n`__ctor`       |类对象构造体方法\n`__dtor`       |类对象析构方法\n\nLua自带的元表方法都很常用，下面具体看**PLoop**特殊的元数据处理:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t__ExistPerson = {}\n\n\t\t-- 对象存在检查，如果存在就无需创建新的了\n\t\t-- 它会接收到所有用于构建对象的参数\n\t\t-- 它的第一个参数是类本身，这样设计是为了处理子类的情况\n\t\tfunction __exist(cls, name)\n\t\t\tif __ExistPerson[name] then\n\t\t\t\tprint(\"对象已经存在:\" .. name)\n\t\t\t\treturn __ExistPerson[name]\n\t\t\tend\n\t\tend\n\n\t\t-- 构造体函数，使用传入的参数初始化对象\n\t\t-- 第一个参数就是新创建的对象\n\t\tfunction __ctor(self, name)\n\t\t\tprint(\"调用类的构造方法初始化:\" .. name)\n\t\t\t__ExistPerson[name] = self\n\t\t\tself.name = name\n\t\tend\n\n\t\t-- 析构方法，通常用于解除引用，之后交给GC即可\n\t\t-- 第一个参数是将被销毁的对象\n\t\tfunction __dtor(self)\n\t\t\tprint(\"销毁对象\" .. self.name)\n\t\t\t__ExistPerson[self.name] = nil\n\t\tend\n\tend)\n\n\to = Person(\"Ann\")           -- 调用类的构造方法初始化:Ann\n\n\t-- true\n\tprint(o == Person(\"Ann\"))   -- 对象已经存在:Ann\n\n\to:Dispose()                 -- 销毁对象Ann\n\n\t-- false\n\tprint(o == Person(\"Ann\"))   -- 调用类的构造方法初始化:Ann\nend)\n```\n\n在上面例子中，我们用到了构造体方法，析构方法和存在检查方法。我们也会发现一个没有没定义的方法**Dispose**，这是一个**PLoop**保留的方法名，所有有析构方法的对象，都需要使用**Dispose**来销毁自身。\n\n我们也可以直接使用**Dispose**替代`__dtor`来定义析构方法，使用类名替代`__ctor`来定义构造体方法。\n\n`__new`元方法用于创建将被封装为对象的table，它可以用于返回其他系统创建的table，也可以用于更快速的创建对象，例如List的一个实现:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"List\" (function(_ENV)\n\t\tfunction __new(cls, ...)\n\t\t\treturn { ... }, true\n\t\tend\n\tend)\n\n\tv = List(1, 2, 3, 4, 5, 6)\nend)\n```\n\n`__new`的调用方式和`__exist`一致，它会接收到class和所有的参数，系统会从它的结果读取两个值，第一个值如果是table，那么就将作为对象被封装，否则系统会自行创建一个新table作为对象。如果第二个值是true，那么，所有的参数将被抛弃，构造体方法只会接收到这个新对象。对于上面的List来说，因为一次性将数据都保存在对象中，就无需再依靠循环保存数据了。\n\n`__field`元数据的值需要是table，它内部保存的键值对将在对象被创建时复制到对象中，如果配合**OBJECT_NO_RAWSEST**，**OBJECT_NO_NIL_ACCESS**两个平台选项，对象将只能使用这些被初始化的字段，同时因为操作这些字段不会触发`__index`和`__newindex`元表方法，访问速度也是最快的。\n\n```lua\nPLOOP_PLATFORM_SETTINGS = { OBJECT_NO_RAWSEST = true, OBJECT_NO_NIL_ACCESS = true, }\n\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t__field     = {\n\t\t\tname    = \"noname\",\n\t\t}\n\n\t\t-- 也可以使用*field*关键字，因为`__field`可能拼写错误\n\t\tfield {\n\t\t\tage     = 0,\n\t\t}\n\tend)\n\n\to = Person()\n\to.name = \"Ann\"\n\to.age  = 12\n\n\to.nme = \"King\"  -- Error : The object can't accept field that named \"nme\"\n\tprint(o.gae)    -- Error : The object don't have any field that named \"gae\"\nend)\n```\n\n作为总结，下面是一段模拟对象构建的处理:\n\n```lua\n-- 检查对象是否存在，存在就返回该对象\nlocal object = __exist(cls, ...)\nif object then return object end\n\n-- 获得一个将被封装为对象的table\nobject = __new(cls, ...) or {}\n\n-- 复制字段\nfield:Copyto(object)\n\n-- 封装table为对象\nsetmetatable(object, objMeta)\n\n-- 调用构造体方法\n__ctor(object, ...)\n\n-- 返回对象\nreturn object\n```\n\n### 超类和继承\n\n一个类可以也仅可以有一个超类，它将从超类中继承对象方法（静态方法不会被继承），元数据和其他资源（之后的属性和事件部分会详谈）。\n\n类可以覆写超类的对象方法，元方法等，如果需要，可以使用**super**关键字来访问超类的对应方法:\n\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"A\" (function(_ENV)\n\t\t-- 对象方法\n\t\tfunction Test(self)\n\t\t\tprint(\"Call A's method\")\n\t\tend\n\n\t\t-- 构造体\n\t\tfunction A(self)\n\t\t\tprint(\"Call A's ctor\")\n\t\tend\n\n\t\t-- 析构方法\n\t\tfunction Dispose(self)\n\t\t\tprint(\"Dispose A\")\n\t\tend\n\n\t\t-- 元方法\n\t\tfunction __call(self)\n\t\t\tprint(\"Call A Object\")\n\t\tend\n\tend)\n\n\tclass \"B\" (function(_ENV)\n\t\tinherit \"A\"  -- 也可以使用inherit(A)\n\n\t\tfunction Test(self)\n\t\t\tprint(\"Call super's method ==\u003e\")\n\t\t\tsuper[self]:Test()\n\t\t\tsuper.Test(self)\n\t\t\tprint(\"Call super's method ==\u003c\")\n\t\tend\n\n\t\tfunction B(self)\n\t\t\tsuper(self)\n\t\t\tprint(\"Call B's ctor\")\n\t\tend\n\n\t\tfunction Dispose(self)\n\t\t\tprint(\"Dispose B\")\n\t\tend\n\n\t\tfunction __call(self)\n\t\t\tprint(\"Call B Object\")\n\t\t\tsuper[self]:__call()\n\t\t\tsuper.__call(self)\n\t\tend\n\tend)\n\n\t-- Call A's ctor\n\t-- Call B's ctor\n\to = B()\n\n\t-- Call super's method ==\u003e\n\t-- Call A's method\n\t-- Call A's method\n\t-- Call super's method ==\u003c\n\to:Test()\n\n\t-- Call B Object\n\t-- Call A Object\n\t-- Call A Object\n\to()\n\n\t-- Dispose B\n\t-- Dispose A\n\to:Dispose()\nend)\n```\n\n下面是一些细节解释:\n\n* `inherit \"A\"`是`inherit(A)`的语法糖。\n\n* 析构方法是由系统管理的，所以，类不需要自己调用超类的析构方法。\n\n* 构造体方法需要主动调用`super(self, ...)`来调用超类的构造体方法，因为只有子类知道需要使用哪些参数去调用超类构造体。\n\n* 对于对象方法和元表方法（包含`__new`和`__exist`），存在两种调用超类对应方法的方式:\n\n\t* `super.Test(self, ...)` 是一种简单方式，仅用于调用对象方法或者元方法\n\n\t* `super[self]:Test(...)`这是正规方式，因为super在访问Test之前先拿到self对象，它就可以获取到对象的类的版本，从而正确的调用超类方法。这一般用于多版本类（默认情况下，重定义类会形成两个版本，甚至多个），也用于访问对象资源，比如属性，事件等（后面会有详细的说明）。\n\n\n### System.Class\n\n**System.Class**是一个反射类型，用于提供关于class的内部信息:\n\nStatic Method                               |Description\n:-------------------------------------------|:-----------------------------\nGetExtends(target[, cache])                 |如果cache存在，将扩展的接口保存在cache中并返回，否则返回一个迭代器供for循环遍历\nGetFeature(target, name[, isobject])        |从目标中获取一个指定名字的类型特征（属性或事件等）。如果*isobject*不存在或为false，只获取在目标中定义的类型特征（包括静态）否则只获取对象特征（含继承获得。下同\nGetFeatures(target, [cache[, isobject]])    |如果cache存在，将类型特征保存在cache中并返回，否则返回一个迭代器供for循环遍历\nGetMethod(target, name[, isobject])         |从目标中获取一个指定名字的方法\nGetMethods(target[, cache[, isobject]])     |如果cache存在，将类型方法保存在cache中并返回，否则返回一个迭代器供for循环遍历\nGetMetaMethod(target, name[, isobject])     |从目标中获取一个指定名字的元方法\nGetMetaMethods(target[, cache[, isobject]]) |如果cache存在，将元方法保存在cache中并返回，否则返回一个迭代器供for循环遍历\nGetObjectClass(object)                      |获取对象的类型\nGetSuperClass(target)                       |获取目标的超类\nGetSuperMethod(target, name)                |获取目标的超类方法\nGetSuperMetaMethod(target, name)            |获取目标的超类元方法\nGetSuperFeature(target, name)               |获取目标的超类特征\nIsAbstract(target[, name])                  |检查目标是否是虚类，或者目标的指定名字的方法，元方法或特征是虚方法，虚元方法或虚特征\nIsFinal(target[, name])                     |检查目标是否最终类，最终类无法被继承，或者目标的指定名字的方法，元方法或特征是最终定义，无法被子类覆盖\nIsImmutable(target)                         |永远返回true，用类去验证对象，不会改变对象\nIsObjectType(object, type)                  |对象是否是对应类型的实体\nIsSealed(target)                            |检查目标是否封闭，无法被重定义\nIsStaticMethod(target, name)                |检查目标指定名字的方法是静态方法\nIsSubType(target, super)                    |检查目标是否是指定类或接口的子类型\nValidateValue(target, object)               |检查对象的类型是指定类型，或者是指定类型的子类型\nValidate(target)                            |检查目标是否是一个类\n\n\n### 类的多重版本\n\n如果我们不使用`__Sealed__`封装这些类，我们可以再次定义它们，和结构体不同，重定义类不会清空以前的定义，而是覆盖上去。\n\n首先看一个例子：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"A\" (function(_ENV)\n\t\tfunction test(self)\n\t\t\tprint(\"hi\")\n\t\tend\n\tend)\n\n\to = A()\n\n\tclass \"A\" (function(_ENV)\n\t\tfunction test(self)\n\t\t\tprint(\"hello\")\n\t\tend\n\tend)\n\n\to:test()   -- hi\n\tA():test() -- hello\nend)\n```\n\n这里旧对象不会使用新定义的方法，所以同时我们有这个类的多个版本存在，这样的设计是为了避免新定义破坏了旧对象的执行（使用字段不同等，特别对于web请求来说，后台文件修改时，不应该影响正在返回数据的处理对象）。\n\n如果我们需要某个类的对象保持更新，我们可以使用`System.__SingleVer__`特性来标记：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__SingleVer__()\n\tclass \"A\" (function(_ENV)\n\t\tfunction test(self)\n\t\t\tprint(\"hi\")\n\t\tend\n\tend)\n\n\to = A()\n\n\tclass \"A\" (function(_ENV)\n\t\tfunction test(self)\n\t\t\tprint(\"hello\")\n\t\tend\n\tend)\n\n\to:test()   -- hello\n\tA():test() -- hello\nend)\n```\n\n这样旧对象也会使用新方法，我们只会有一个版本类实现。如果希望这个是类的默认行为的话，可以修改平台设定：\n\n```lua\nPLOOP_PLATFORM_SETTINGS = { CLASS_NO_MULTI_VERSION_CLASS = true }\n\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"A\" (function(_ENV)\n\t\tfunction test(self)\n\t\t\tprint(\"hi\")\n\t\tend\n\tend)\n\n\to = A()\n\n\tclass \"A\" (function(_ENV)\n\t\tfunction test(self)\n\t\t\tprint(\"hello\")\n\t\tend\n\tend)\n\n\to:test()   -- hello\n\tA():test() -- hello\nend)\n```\n\n注意，这个设定对于多os-thread平台无效。\n\n### 扩展方法\n\n如果只是想追加处理的话，我们不需要进行完全的重定义：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Sealed__()\n\tclass \"A\" (function(_ENV)\n\t\tfunction test(self)\n\t\t\tprint(\"hi\")\n\t\tend\n\tend)\n\n\to = A()\n\n\tfunction A:test2()\n\t\tprint(\"hello\")\n\tend\n\n\to:test2()   -- hello\nend)\n```\n\n我们只需要将函数赋给类就可以为它扩展新的对象方法或者静态方法。旧的对象也会获得新定义的方法。\n\n这也可以用于扩展已经封闭了的类。也可以用于之后的接口。\n\n我们不能对结构体类型使用这方式，因为结构体方式是被拷贝到数据table中的，如果我们给一个不含方法的结构体添加新方法，那么这个结构体会由不可变类型变成可变类型，这对系统影响太大，是不允许的。\n\n\n## Interface 接口\n\n接口是对功能的抽象，对于class来说，它也是多继承的补充机制。和class一样，也可以在它里面定义对象方法，静态方法和元数据。\n\n类和接口都可以扩展任意数量的接口，使用**super**关键字时，它会根据继承的情况和优先级自行选择对应的方法（不限于超类的，也可以是接口提供的）。\n\n接口使用`__init`替代`__ctor`（接口名也是同样），对应函数将作为接口的初始化方法，接口的初始化方法只接收self也就是对象这一个参数，并且接口的初始化是在类对象构建完成后，由系统自动调用，无法使用**super**或者其他机制来主动调用。\n\n接口可以定义含有处理的方法，但也可以定义需要被扩展它的接口或者类实现的对象方法或元方法，或者其他资源（属性，事件等），只需要使用`System.__Abstract__`特性标记即可。特别的，被标记为`__Abstract__`的对象方法和元方法无法被**super**访问，因为它们应该是空处理方法，没有调用的价值。\n\n来看一个具体的例子：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tinterface \"IName\" (function(self)\n\t\t__Abstract__()\n\t\tfunction SetName(self) end\n\n\t\t__Abstract__()\n\t\tfunction GetName(self) end\n\n\t\t-- 初始化方法\n\t\tfunction IName(self) print(\"IName Init\") end\n\n\t\t-- 析构方法\n\t\tfunction Dispose(self) print(\"IName Dispose\") end\n\tend)\n\n\tinterface \"IAge\" (function(self)\n\t\t__Abstract__()\n\t\tfunction SetAge(self) end\n\n\t\t__Abstract__()\n\t\tfunction GetAge(self) end\n\n\t\t-- 初始化方法\n\t\tfunction IAge(self) print(\"IAge Init\") end\n\n\t\t-- 析构方法\n\t\tfunction Dispose(self) print(\"IAge Dispose\") end\n\tend)\n\n\tclass \"Person\" (function(_ENV)\n\t\textend \"IName\" \"IAge\"   -- 也可以使用`extend(IName)(IAge)`\n\n\t\t-- Error: attempt to index global 'super' (a nil value)\n\t\t-- 因为IName.SetName是abstract的，所以Person并没有超类方法可以调用\n\t\t-- 系统也不会创建super供Person类使用\n\t\tfunction SetName(self, name) super[self]:SetName(name) end\n\n\t\tfunction Person(self) print(\"Person Init\") end\n\n\t\tfunction Dispose(self) print(\"Person Dispose\") end\n\tend)\n\n\t-- Person Init\n\t-- IName Init\n\t-- IAge Init\n\to = Person()\n\n\t-- IAge Dispose\n\t-- IName Dispose\n\t-- Person Dispose\n\to:Dispose()\nend)\n```\n\n如前所述，接口的初始化方法是在对象被创建后再被调用的，一般可以用于注册，进行预处理等。销毁对象的调用步骤和构造时的初始化步骤是正好相反的。这些由系统管理，所以定义时不需要在意。\n\n### System.Interface\n\n**System.Interface** 是一个反射类型，用于获取接口的内部信息，它和Class的API基本一致:\n\nStatic Method                               |Description\n:-------------------------------------------|:-----------------------------\nGetExtends(target[, cache])                 |如果cache存在，将扩展的接口保存在cache中并返回，否则返回一个迭代器供for循环遍历\nGetFeature(target, name[, isobject])        |从目标中获取一个指定名字的类型特征（属性或事件等）。如果*isobject*不存在或为false，只获取在目标中定义的类型特征（包括静态）否则只获取对象特征（含继承获得。下同\nGetFeatures(target, [cache[, isobject]])    |如果cache存在，将类型特征保存在cache中并返回，否则返回一个迭代器供for循环遍历\nGetMethod(target, name[, isobject])         |从目标中获取一个指定名字的方法\nGetMethods(target[, cache[, isobject]])     |如果cache存在，将类型方法保存在cache中并返回，否则返回一个迭代器供for循环遍历\nGetMetaMethod(target, name[, isobject])     |从目标中获取一个指定名字的元方法\nGetMetaMethods(target[, cache[, isobject]]) |如果cache存在，将元方法保存在cache中并返回，否则返回一个迭代器供for循环遍历\nGetSuperMethod(target, name)                |获取目标的超类方法\nGetSuperMetaMethod(target, name)            |获取目标的超类元方法\nGetSuperFeature(target, name)               |获取目标的超类特征\nIsAbstract(target[, name])                  |检查目标的指定名字的方法，元方法或特征是虚方法，虚元方法或虚特征\nIsFinal(target[, name])                     |检查目标是否最终接口，最终接口无法被继承，通常用作函数库，或者目标的指定名字的方法，元方法或特征是最终定义，无法被子类型覆盖\nIsImmutable(target)                         |永远返回true\nIsSealed(target)                            |检查目标是否封闭，无法被重定义\nIsStaticMethod(target, name)                |检查目标指定名字的方法是静态方法\nIsSubType(target, super)                    |检查目标是否是指定接口的子类型\nValidateValue(target, object)               |检查对象的类型是否是指定类型的子类型\nValidate(target)                            |检查目标是否是一个接口\n\n\n### Interface的匿名类\n\n如果我们使用`System.__AnonymousClass__`特性在某个接口上，这个接口会自动创建一个扩展自己的匿名类，这个匿名类无法直接被访问，但我们可以使用接口来构建对象：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__AnonymousClass__()\n\tinterface \"ITask\" (function(_ENV)\n\t\t__Abstract__() function Process()\n\t\tend\n\tend)\n\n\to = ITask{ Process = function() print(\"Hello\") end }\n\n\to:Process()\nend)\n```\n\n接口只能接受一个table做为初始化表来创建这个对象，通常要提供虚方法的实现。\n\n但对于只有一个虚方法（含继承）的接口，我们可以使用更简单的形式：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__AnonymousClass__()\n\tinterface \"ITask\" (function(_ENV)\n\t\t__Abstract__() function Process()\n\t\tend\n\tend)\n\n\to = ITask(function() print(\"Hello\") end)\n\to:Process()\nend)\n```\n\n我们可以直接提供虚方法的实现来构建对象。如果你希望所有接口都提供这样的行为，那么也可以修改平台设定（不推荐）：\n\n```lua\nPLOOP_PLATFORM_SETTINGS = { INTERFACE_ALL_ANONYMOUS_CLASS = true }\n\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tinterface \"ITask\" (function(_ENV)\n\t\t__Abstract__() function Process()\n\t\tend\n\tend)\n\n\to = ITask(function() print(\"Hello\") end)\n\to:Process()\nend)\n```\n\n### 接口的所需类\n\n我们可以使用**require**关键字指定扩展接口的类必须是某个类的子类:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"A\" {}\n\n\tinterface \"IA\" (function(_ENV)\n\t\trequire \"A\"\n\tend)\n\n\tclass \"B\" (function(_ENV)\n\t\textend \"IA\" -- Error: interface.AddExtend(target, extendinterface[, stack]) - the class must be A's sub-class\n\tend)\nend)\n```\n\n\n## Event 事件\n\n**event**是类型特征的一种，用于通知外界对象的某些状态改变了：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t-- 为Person类申明一个事件\n\t\tevent \"OnNameChanged\"\n\n\t\tfield { name = \"anonymous\" }\n\n\t\tfunction SetName(self, name)\n\t\t\tif name ~= self.name then\n\t\t\t\t-- 发起事件通知外界\n\t\t\t\tOnNameChanged(self, name, self.name)\n\t\t\t\tself.name = name\n\t\t\tend\n\t\tend\n\tend)\n\n\to = Person()\n\n\t-- 绑定一个事件处理方法给对象\n\tfunction o:OnNameChanged(new, old)\n\t\tprint((\"%q -\u003e %q\"):format(old, new))\n\tend\n\n\t-- \"anonymous\" -\u003e \"Ann\"\n\to:SetName(\"Ann\")\nend)\n```\n\n事件处理方法有两种类型:\n\n* 最终处理方法 - 之前例子中的用法就是最终处理方法，最终处理方法同时只能设定一个。\n* 叠加处理方法 - 叠加处理方法通常使用在类的构造体方法或者接口的初始化方法中，用于绑定内部事件处理方法:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t-- 为Person类申明一个事件\n\t\tevent \"OnNameChanged\"\n\n\t\tfield { name = \"anonymous\" }\n\n\t\tfunction SetName(self, name)\n\t\t\tif name ~= self.name then\n\t\t\t\t-- 发起事件通知外界\n\t\t\t\tOnNameChanged(self, name, self.name)\n\t\t\t\tself.name = name\n\t\t\tend\n\t\tend\n\tend)\n\n\t-- 定义子类\n\tclass \"Student\" (function(_ENV)\n\t\tinherit \"Person\"\n\n\t\tlocal function onNameChanged(self, name, old)\n\t\t\tprint((\"Student %s renamed to %s\"):format(old, name))\n\t\tend\n\n\t\tfunction Student(self, name)\n\t\t\tself:SetName(name)\n\t\t\tself.OnNameChanged = self.OnNameChanged + onNameChanged\n\t\tend\n\tend)\n\n\to = Student(\"Ann\")\n\n\tfunction o:OnNameChanged(name)\n\t\tprint(\"My new name is \" .. name)\n\tend\n\n\t-- Student Ann renamed to Ammy\n\t-- My new name is Ammy\n\to:SetName(\"Ammy\")\nend)\n```\n\n使用对象访问事件名例如`self.OnNameChanged`，会得到一个创建自**System.Delegate**的对象，实际最终处理方法和叠加处理方法这两个机能就源于这个Delegate对象。\n\n我们可以使用下面的方法叠加处理方法\n\n```lua\nself.OnNameChanged = self.OnNameChanged + onNameChanged\n```\n\n也可以用下面的方式移除叠加的处理方法\n\n```lua\nself.OnNameChanged = self.OnNameChanged - onNameChanged\n```\n\n当事件发生时，如果这个对象有相应的Delegate对象（这个对象仅当被访问时被创建），那么这个Delegate对象会被调用来处理事件。\n\n叠加的处理方法是按顺序添加的，所以，最先被加入的处理方法会最先被使用，然后依次调用下去，直到最后调用最终处理方法。这个过程中，如果某个处理方法返回true，整个调用链终止。\n\n在某些场景中，我们需要禁止对象的事件处理，这可以利用Delegate的初始处理方法:\n\n```lua\nself.OnNameChanged:SetInitFunction(function() return true end)\n```\n\n初始方法如果存在，会最先被调用，只要它返回true就可以终止对象的事件处理了。\n\n\n### 事件处理方法变更的处理\n\n通常如果使用**PLoop**封装来自其他系统的对象，我们需要双向处理事件绑定:\n\n* 如果对象的Delegate中绑定的处理方法变更，比如清空了，增加了等情况，我们需要通知其他系统，比如增加事件监听，或者移除事件监听等。\n\n* 当其他系统的事件发生时，我们要触发对象的事件处理。\n\n使用魔兽世界中的*Frame*控件来做介绍，无视掉其他细节，我们来看看如何做双向事件绑定处理:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Frame\" (function(_ENV)\n\t\t__EventChangeHandler__(function(delegate, owner, eventname)\n\t\t\t-- delegate是绑定的处理方法发生改变的delegate对象\n\t\t\t-- owner是对象，也就是delegate对象的主人\n\t\t\t-- eventname是事件名字，这里就是OnEnter\n\t\t\tif delegate:IsEmpty() then\n\t\t\t\t-- 没有处理方法，无需监视，这里解除了注册\n\t\t\t\towner:SetScript(eventname, nil)\n\t\t\telse\n\t\t\t\t-- 存在处理方法，需要注册到游戏引擎中\n\t\t\t\tif owner:GetScript(eventname) == nil then\n\t\t\t\t\towner:SetScript(eventname, function(self, ...)\n\t\t\t\t\t\t-- 我们可以直接调用delegate对象，无需走event系统\n\t\t\t\t\t\tdelegate(owner, ...)\n\t\t\t\t\tend)\n\t\t\t\tend\n\t\t\tend\n\t\tend)\n\t\tevent \"OnEnter\"\n\tend)\nend)\n```\n\n`System.__EventChangeHandler__`特性专为事件绑定变更处理方法，这样所有这个类的对象相应事件的delegate变更时，这个变更处理函数就会被调用，我们可以统一的进行处理。更进一步，我们可以用一个函数处理所有的事件:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tlocal function changehandler (delegate, owner, eventname)\n\t\tif delegate:IsEmpty() then\n\t\t\towner:SetScript(eventname, nil)\n\t\telse\n\t\t\tif owner:GetScript(eventname) == nil then\n\t\t\t\towner:SetScript(eventname, function(self, ...)\n\t\t\t\t\t-- Call the delegate directly\n\t\t\t\t\tdelegate(owner, ...)\n\t\t\t\tend)\n\t\t\tend\n\t\tend\n\tend\n\n\tfunction __WidgetEvent__(self)\n\t\t__EventChangeHandler__(changehandler)\n\tend\n\n\tclass \"Frame\" (function(_ENV)\n\t\t__WidgetEvent__()\n\t\tevent \"OnEnter\"\n\n\t\t__WidgetEvent__()\n\t\tevent \"OnLeave\"\n\tend)\nend)\n```\n\n### 静态事件\n\n我们可以使用`__Static__`特性来标记某些事件为静态，这样它仅能被类或者接口使用:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t__Static__()\n\t\tevent \"OnPersonCreated\"\n\n\t\tfunction Person(self, name)\n\t\t\tOnPersonCreated(name)\n\t\tend\n\tend)\n\n\tfunction Person.OnPersonCreated(name)\n\t\tprint(\"Person created \" .. name)\n\tend\n\n\t-- Person created Ann\n\to = Person(\"Ann\")\nend)\n```\n\n### 超类事件\n\n如果超类或者接口的事件被覆写了，但我们有需要监听超类事件，我们可以使用**super[object].event**的方式来使用超类事件:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t-- declare an event for the class\n\t\tevent \"OnNameChanged\"\n\n\t\tfield { name = \"anonymous\" }\n\n\t\tfunction SetName(self, name)\n\t\t\tif name ~= self.name then\n\t\t\t\t-- Notify the outside\n\t\t\t\tOnNameChanged(self, name, self.name)\n\t\t\t\tself.name = name\n\t\t\tend\n\t\tend\n\tend)\n\n\n\tclass \"Student\" (function(_ENV)\n\t\tinherit \"Person\"\n\n\t\tevent \"OnNameChanged\"\n\n\t\tlocal function raiseEvent(self, ...)\n\t\t\tOnNameChanged(self, ...)\n\t\tend\n\n\t\tfunction Student(self)\n\t\t\tsuper(self)\n\n\t\t\t-- Use the super object access style\n\t\t\tsuper[self].OnNameChanged = raiseEvent\n\t\tend\n\tend)\n\n\to = Student()\n\n\tfunction o:OnNameChanged(name)\n\t\tprint(\"New name is \" .. name)\n\tend\n\n\t-- New name is Test\n\to:SetName(\"Test\")\nend)\n```\n\n如例子所示，子类可以监听超类的事件，并使用自己的事件传递下去。\n\n### System.Event\n\n**System.Event**是一个反射类型，可以用来获取事件的内部信息:\n\n静态方法                                    |描述\n:-------------------------------------------|:-----------------------------\nGet(target, object[, nocreation])           |从对象中获取事件的处理delegate对象，如果nocreation不为true，那么会创建这个delegate对象如果不存在\nGetEventChangeHandler(target)               |获取使用`__EventChangeHandler__`注册的函数\nIsStatic(target)                            |事件是否是静态\nValidate(target)                            |目标是否是一个事件\n\n一个简单的例子:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t__Static__()\n\t\tevent \"OnPersonCreated\"\n\tend)\n\n\tfor name, feature in Class.GetFeatures(Person) do\n\t\tif Event.Validate(feature) then\n\t\t\tprint(\"event\", name)\n\t\tend\n\tend\nend)\n```\n\n## Property 属性\n\n属性是对象的状态特征，我们也可以使用**field**指定的字段作为对象状态特征，但字段缺乏类型验证，我们也无法知道何时这些字段值被修改了。\n\n属性系统提供了很多机制，诸如get/set，值的类型验证，值修改的处理方法，值修改的处理事件，默认值，默认值工厂等。\n\n从一个简单的例子开始:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\tproperty \"Name\" { type = String }\n\t\tproperty \"Age\"  { type = Number }\n\tend)\n\n\t-- 如果类没有定义__ctor，我们可以使用这种初始化表机制\n\t-- 表中的所有键值会被赋给对象\n\to = Person{ Name = \"Ann\", Age = 10 }\n\n\tprint(o.Name)-- Ann\n\to.Name = 123 -- Error : the Name must be string, got number\nend)\n```\n\n类似于结构体的**member**关键字，**property**接收一个字符串作为属性名，一个table作为属性定义。table定义中的键是大小写无视的，下面是完整的设定清单:\n\n字段            |用途\n:---------------|:-------------\nauto            |是否使用自动绑定机制，详见下面的例子\nget             |用于获取对象属性值的方法，调用方式类似`return get(obj)`，也可以设置为**false**，表示该属性不可读\nset             |用于设置对象属性值的方法，调用方式类似`set(obj, value)`，也可以设置为**false**，表示该属性不可写\ngetmethod       |获取属性值的对象方法名，调用方式类似`return obj[getmethod](obj)`\nsetmethod       |设置属性值的对象方法名，调用方式类似`obj[setmethod](obj, value)`\nfield           |实际保存属性值的字段，如果get/set或者getmethod/setmethod设置就无效。如果定义中没有设置field，set/get, getmethod/setmethod，那么系统会自动指定一个field，比如上面例子中的用法，这也是推荐做法。\ntype            |属性值的类型，如果这个类型是immutable的，当平台设定里面关闭类型验证时，属性值也会停止验证\ndefault         |属性的默认值\nevent           |属性值变更时自动发起的事件，如果是字符串，会尝试用该字符串创建事件，仅用于使用field的属性\nhandler         |属性值变更时触发的处理方法，这是类或者接口内部自行处理对象属性变更的方法，仅用于使用field的属性\nstatic          |true，如果希望定义为静态属性\nindexer         |true，如果属性是索引属性\nthrowable       |true，如果属性的set方法会抛出错误\nrequire         |true, 如果希望属性值不能为nil\n\n我们依次来看一些使用例子:\n\n### get/set\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\tfield { __name = \"anonymous\" }\n\n\t\tproperty \"Name\" {\n\t\t\tget = function(self) return self.__name end,\n\t\t\tset = function(self, name)  self.__name = name end,\n\t\t}\n\tend)\n\n\tprint(Person().Name)\nend)\n```\n\n### getmethod/setmethod\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\tfield { __name = \"anonymous\" }\n\n\t\tfunction SetName(self, name)\n\t\t\tself.__name = name\n\t\tend\n\n\t\tfunction GetName(self)\n\t\t\treturn self.__name\n\t\tend\n\n\t\tproperty \"Name\" {\n\t\t\tget = \"GetName\", -- or getmethod = \"GetName\"\n\t\t\tset = \"SetName\", -- or setmethod = \"SetName\"\n\t\t}\n\tend)\n\n\tprint(Person().Name)\nend)\n```\n\n\n### property-throw\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\tfield { __name = \"anonymous\" }\n\n\t\tfunction SetName(self, name)\n\t\t\tif type(name) ~= \"string\" then\n\t\t\t\tthrow(\"The name must be string\")\n\t\t\tend\n\t\t\tself.__name = name\n\t\tend\n\n\t\tfunction GetName(self)\n\t\t\treturn self.__name\n\t\tend\n\n\t\tproperty \"Name\" {\n\t\t\tget = \"GetName\", -- or getmethod = \"GetName\"\n\t\t\tset = \"SetName\", -- or setmethod = \"SetName\"\n\t\t\tthrowable = true,\n\t\t}\n\tend)\n\n\tPerson().Name = 123 -- Error: The name must be string\nend)\n```\n\n\n### field \u0026 default\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\tproperty \"Name\" { field = \"__name\", default = \"anonymous\" }\n\tend)\n\n\tobj = Person()\n\tprint(obj.Name, obj.__name) -- anonymous   nil\n\n\tobj.Name = \"Ann\"\n\tprint(obj.Name, obj.__name) -- Ann         Ann\nend)\n```\n\n### default factory\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\tproperty \"Age\" { field = \"__age\", default = function(self) return math.random(100) end }\n\tend)\n\n\tobj = Person()\n\tprint(obj.Age, obj.__age) -- 81   81\n\tobj.Age = nil   -- 下次访问时，值会被重新产生\n\tprint(obj.Age, obj.__age) -- 88   88\nend)\n```\n\n### property-event\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\tproperty \"Name\" { type = String, event = \"OnNameChanged\" }\n\tend)\n\n\to = Person { Name = \"Ann\" }\n\n\tfunction o:OnNameChanged(new, old, prop)\n\t\tprint((\"[%s] %s -\u003e %s\"):format(prop, old, new))\n\tend\n\n\t-- [Name] Ann -\u003e Ammy\n\to.Name = \"Ammy\"\nend)\n```\n\n### property-handler\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\tproperty \"Name\" {\n\t\t\ttype = String, default = \"anonymous\",\n\n\t\t\thandler = function(self, new, old, prop)\n\t\t\t\tprint((\"[%s] %s -\u003e %s\"):format(prop, old, new))\n\t\t\tend\n\t\t}\n\tend)\n\n\t--[Name] anonymous -\u003e Ann\n\to = Person { Name = \"Ann\" }\n\n\t--[Name] Ann -\u003e Ammy\n\to.Name = \"Ammy\"\nend)\n```\n\n### static property\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t__Static__()\n\t\tproperty \"DefaultName\" { type = String }\n\n\t\tproperty \"Name\" {\n\t\t\ttype = String, default = function() return Person.DefaultName end,\n\t\t}\n\tend)\n\n\tPerson.DefaultName = \"noname\"\n\n\tprint(Person().Name) -- noname\nend)\n```\n\n### 自动绑定\n\n如果设置了*auto*启用自动绑定模式，并且属性本身没有定义get/set,getmethod/setmethod和field这些字段，那么系统会检查属性所属类型或者接口的方法（如果是静态属性查静态方法，非静态属性查对象方法（含继承）），以一个而名为\"name\"的属性为例:\n\n* *setname*, *Setname*, *SetName*, *setName*将会被扫描，如果存在，这个方法会被保存到set字段中，被属性使用\n\n* *getname*, *Getname*, *Isname*, *isname*, *getName*, *GetName*, *IsName*, *isname*将会被扫描，如果存在，这个方法会被保存到get字段中，被属性使用\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\tfunction SetName(self, name)\n\t\t\tprint(\"SetName\", name)\n\t\tend\n\n\t\tproperty \"Name\" { type = String, auto = true }\n\tend)\n\n\t-- SetName  Ann\n\to = Person { Name = \"Ann\"}\n\n\t-- SetName  Ammy\n\to.Name = \"Ammy\"\nend)\n```\n\n### 超类属性\n\n如果类或者接口覆盖了继承的属性，类似event我们可以使用**super**关键字来访问超类属性处理:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\tproperty \"Name\" { type = String }\n\tend)\n\n\tclass \"Student\" (function(_ENV)\n\t\tinherit \"Person\"\n\n\t\tproperty \"Name\" {\n\t\t\tSet = function(self, name)\n\t\t\t\t-- 保存到超类属性中\n\t\t\t\tsuper[self].Name = name\n\t\t\tend,\n\t\t\tGet = function(self)\n\t\t\t\t-- 读取超类属性值\n\t\t\t\treturn super[self].Name\n\t\t\tend,\n\t\t}\n\tend)\n\n\to = Student()\n\to.Name = \"Test\"\n\tprint(o.Name)   -- Test\nend)\n```\n\n### 索引属性\n\n我们还可以定义一种特殊的索引属性:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"A\" (function( _ENV )\n\t\t__Indexer__()\n\t\tproperty \"Items\" {\n\t\t\tset = function(self, idx, value)\n\t\t\t\tself[idx] = value\n\t\t\tend,\n\t\t\tget = function(self, idx)\n\t\t\t\treturn self[idx]\n\t\t\tend,\n\t\t\ttype = String,\n\t\t}\n\tend)\n\n\to = A()\n\n\to.Items[1] = \"Hello\"\n\n\tprint(o.Items[1])   -- Hello\nend)\n```\n\n索引属性的定义table仅接受set, get, getmethod, setmethod, type and static这些设定。\n\n也可以为索引属性的键指定类型:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"A\" (function( _ENV )\n\t\t__Indexer__(String)\n\t\tproperty \"Items\" {\n\t\t\tset = function(self, idx, value)\n\t\t\t\tself[idx] = value\n\t\t\tend,\n\t\t\tget = function(self, idx)\n\t\t\t\treturn self[idx]\n\t\t\tend,\n\t\t\ttype = String,\n\t\t}\n\tend)\n\n\to = A()\n\n\t-- Error: the Items's key must be string, got number\n\to.Items[1] = \"Hello\"\nend)\n```\n\n\n### Get/Set行为修饰\n\n除了上述定义外，我们还可以对属性的访问行为进行调整。\n\n对于属性的值设置，我们使用**System.PropertySet**来描述保存值时的处理:\n\n```lua\n__Flags__() __Default__(0)\nenum \"System.PropertySet\" {\n\tAssign      = 0,  -- 直接保存\n\tClone       = 1,  -- 保存值的拷贝\n\tDeepClone   = 2,  -- 保存值的深层拷贝\n\tRetain      = 4,  -- 旧值需要被Dispose处理\n\tWeak        = 8,  -- 值使用弱引用保存，可被回收\n}\n```\n\n对于属性的值读取，我们使用**System.PropertyGet**来描述读取值时的处理:\n\n```lua\n__Flags__() __Default__(0)\nenum \"System.PropertyGet\" {\n\tOrigin      = 0,  -- 直接返回值\n\tClone       = 1,  -- 返回值的拷贝\n\tDeepClone   = 2,  -- 返回值的深层拷贝\n}\n```\n\n为了给属性指定这些行为，我们需要使用`System.__Set__`和`System.__Get__`这两个特性:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Data\" (function(_ENV)\n\t\textend \"ICloneable\"  -- 可复制类必须扩展这个接口\n\n\t\tlocal _Cnt = 0\n\n\t\t-- 实现Clone方法\n\t\tfunction Clone(self)\n\t\t\treturn Data() -- for test, just return a new one\n\t\tend\n\n\t\tfunction Dispose(self)\n\t\t\tprint(\"Dispose Data \" .. self.Index)\n\t\tend\n\n\t\tfunction __ctor(self)\n\t\t\t_Cnt = _Cnt + 1\n\t\t\tself.Index = _Cnt\n\t\tend\n\tend)\n\n\tclass \"A\" (function(_ENV)\n\t\t__Set__(PropertySet.Clone + PropertySet.Retain)\n\t\t__Get__(PropertySet.Clone)\n\t\tproperty \"Data\" { type = Data }\n\tend)\n\n\to = A()\n\n\tdt = Data()\n\n\to.Data = dt\n\tprint(dt.Index, o.Data.Index)  -- 1  3\n\to.Data = nil   -- Dispose Data 2\nend)\n```\n\n### System.Property\n\n**System.Property**是一个反射类型，用于提供property的信息：\n\nStatic Method                |Description\n:----------------------------|:-----------------------------\nIsGetClone(target)           |该属性返回值的拷贝\nIsGetDeepClone(target)       |该属性返回值的深层拷贝\nIsIndexer(target)            |该属性是否是索引属性\nIsReadable(target)   \t\t |该属性是否可读\nIsSetClone(target)           |该属性是否保存输入值的拷贝\nIsSetDeepClone(target)       |该属性是否保存输入值的深层拷贝\nIsRetainObject(target)       |该属性是否会Dispose旧的值（对象）\nIsStatic(target)             |该属性是否是静态属性\nIsWeak(target)               |该属性是否将值作为弱引用保存\nIsWritable(target)           |该属性是否可写\nGetDefault(target)           |获取属性的默认值\nGetField(target)             |获取属性的保存字段\nGetType(target)              |获取属性的类型\nValidate(target)             |目标是否是一个属性\n\n下面是一个简单例子:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\tproperty \"Name\" { type = String }\n\t\tproperty \"Age\"  { type = Number }\n\tend)\n\n\tfor name, feature in Class.GetFeatures(Person) do\n\t\tif Property.Validate(feature) then\n\t\t\tprint(name, Property.GetType(feature))\n\t\tend\n\tend\nend)\n```\n\n上面已经完整介绍了**PLoop**提供的所有类型，不过我们还有很多细节需要补充。\n\n\n## 继承和优先级\n\n一个类可以扩展多个接口，可以继承一个超类，超类也会继承其他超类和扩展其他的接口。\n\n如果这些超类和接口中有同名的类型资源（方法，元方法，属性或者事件），那么系统在继承时，会选择最接近的：\n\n* 检查超类，如果没有，检查超类的超类，依次继续下去。\n\n* 检查接口，最后被扩展的接口会被优先检查。\n\n这些调用都是系统完成，我们并不需要管理它，但我们也可以通过使用`System.__Abstract__`和`System.__Final__`两个特性来影响这个过程：\n\n* 如果一个类型资源（方法，元方法，属性或者事件）被标记为`__Abstract__`，那么它的继承优先级最低。\n\n* 如果一个类型资源被标记为`__Final__`，那么它的继承优先�","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkurapica%2FPLoop","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkurapica%2FPLoop","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkurapica%2FPLoop/lists"}