{"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","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__`，那么它的继承优先级最高。\n\n下面是一个简单的例子：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tinterface \"IA\" (function(_ENV)\n\t\t__Final__()\n\t\tfunction Test(self)\n\t\t\tprint(\"Hello IA\")\n\t\tend\n\n\t\t__Abstract__()\n\t\tfunction Test2(self)\n\t\t\tprint(\"Hello2 IA\")\n\t\tend\n\tend)\n\n\tclass \"A\" (function(_ENV)\n\t\textend \"IA\"\n\n\t\tfunction Test(self)\n\t\t\tprint(\"Hello A\")\n\t\tend\n\n\t\tfunction Test2(self)\n\t\t\tprint(\"Hello2 A\")\n\t\tend\n\tend)\n\n\to = A()\n\to:Test()  -- Hello IA\n\to:Test2() -- Hello2 A\nend)\n```\n\n关于`__Final__` 特性还有一种特殊用法，我们可以在接口或者抽象类中定义`__Final__`的方法，然后在它的定义中使用对象的类来访问实际的方法：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tinterface \"IA\" (function(_ENV)\n\t\tlocal getObjectClass = Class.GetObjectClass\n\n\t\t__Final__() function Test(self)\n\t\t\tprint(\"Call Test of IA\")\n\n\t\t\t-- 获取对象的类，调用该类中定义的Test方法完成操作\n\t\t\tgetObjectClass(self).Test(self)\n\t\tend\n\tend)\n\n\tclass \"A\" { IA, Test = function(self) print(\"Call Test of A\") end }\n\n\to = A()\n\n\t-- Call Test of IA\n\t-- Call Test of A\n\to:Test()\nend)\n```\n\n对象会使用申明为最终的方法，但类会保留它自身定义的版本。\n\n\n## 使用其他定义形式\n\n### 使用字符串作为定义体\n\n对于结构体，接口和类，我们可以使用字符串作为定义体，以便于某些情况下自动生成定义：\n\n```lua\nPLoop(function(_ENV)\n\tclass \"A\" [[\n\t\tproperty \"Name\" { default = \"anonymous\" }\n\t]]\n\n\tprint(A().Name)\nend)\n```\n\n仅需要将`function(_ENV)`和`end)`替换成字符串的起始和结束即可。\n\n### 使用table作为定义体\n\n在[使用table来定义结构体](#使用table来定义结构体)中，我们已经看到如何用table定义结构体，同样，我们也可以使用table来定义接口和类：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Person\" {\n\t\t-- 定义静态事件\n\t\t-- 不过使用table定义并不能很好的使用事件\n\t\tOnPersonCreated = true,\n\n\t\t-- 定义对象事件\n\t\tOnNameChanged   = false,\n\n\t\t-- 定义属性，可以指定类型或者定义table\n\t\tName = String,\n\t\tAge  = { type = Number, default = 0 },\n\n\t\t-- 定义对象方法\n\t\tSetName = function(self, name)\n\t\t\tself:OnNameChanged(name, self.Name)\n\t\t\tself.Name = name\n\t\tend,\n\n\t\t-- 定义构造体方法，也可以使用`__ctor`作为键\n\t\tfunction (self, name)\n\t\t\tPerson.OnPersonCreated(name)\n\t\t\tself.Name = name\n\t\tend,\n\t}\n\n\tinterface \"IScore\" {\n\t\tPerson,      -- 如果是类，那么require它\n\t\tICloneable,  -- 如果是接口，那么extend它\n\t}\n\n\tclass \"Student\" {\n\t\tPerson, -- 如果是类，那么inherit它\n\t\tIScore, -- 如果是接口，那么extend它\n\t}\n\n\t-- 我们可以在之后，再定义对象或者静态方法\n\tfunction Student:SetScore(score)\n\tend\nend)\n```\n\n\n## 命名空间和匿名类型\n\n**PLoop**使用命名空间来管理类型，我们可以将类型保存在树状的命名空间中，这样每种类型都有唯一的访问路径，比如**System.Collections.List**。我们也可以使用**import**关键字在私有环境中引入这些命名空间，这样这些类型可以在任何地方被使用。\n\n通常类型在它们被定义时保存到命名空间中，下面的例子将为我们展示命名空间保存相关的所有场景：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t-- 我们可以使用**namespace**关键字来为当前环境\n\t-- 申明一个命名空间，之后这个环境中创建的类型\n\t-- 都会保存在这个命名空间\n\tnamespace \"Test\"\n\n\tclass \"A\" (function(_ENV)\n\t\t-- 类型的定义体的的环境的所属命名空间就是这个\n\t\t-- 类型本身，这里就是class A，任何定义在这个\n\t\t-- 环境的类型，都将成为A的子命名空间。\n\t\tenum \"Type\" { Data = 1, Object = 2 }\n\tend)\n\n\t-- 如果我们定义类型时，名字使用了全路径，那么\n\t-- 这个类型会按照路径保存，和当前环境所属的\n\t-- 命名空间无关\n\tclass \"Another.B\" (function(_ENV)\n\t\tenum \"Type\" { Data = 1, Object = 2 }\n\tend)\n\n\tprint(A)      -- Test.A\n\tprint(A.Type) -- Test.A.Type\n\n\tprint(B)      -- Another.B\n\tprint(B.Type) -- Another.B.Type\nend)\n```\n\n我们也可以将不希望分享给它人的类型定义为匿名类型，只需要在定义时不指定名字即可：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tnamespace \"Test\"\n\n\tclass \"A\" (function(_ENV)\n\t\tType = enum { Data = 1, Object = 2 }\n\n\t\tprint(Data)      -- 1\n\t\tprint(Type.Data) -- 1\n\tend)\n\n\t-- 没有任何方式访问到A.Type\n\tprint(A.Type)        -- nil\nend)\n```\n\n### System.Namespace\n\n**PLoop**同样提供一个反射类型**System.Namespace**用于获取namespace相关的信息:\n\n静态方法                             |描述\n:------------------------------------|:-----------------------------\nExportNamespace(env, ns[, override]) |将指定ns及其子命名空间保存到env环境中\nGetNamespace([root,] path)           |使用路径获取对应的命名空间实体\nGetNamespaces(root[, cache])         |获取所有子命名空间\nGetNamespaceName(ns, onlyname)       |获取命名空间实体的路径或者名字\nIsAnonymousNamespace(target)         |目标是否是一个匿名类型\nValidate(target)                     |目标是否是一个命名空间实体\n\n\n## 环境\n\n私有环境是**PLoop**的基础元素。\n\n### 隔离代码\n\n**PLoop**中代码都需要在各个私有环境下被执行，这样我们不会因为使用全局变量等情况造成冲突。\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tfunction Test()\n\tend\nend)\n\nprint(Test) -- nil\n\nPLoop(function(_ENV)\n\tprint(Test)  -- nil\nend)\n```\n\n如果需要共享资源的话，我们应当将它们保存在类型中进行分享。\n\n### 分享类型\n\n我们可以为私有环境使用**import**关键字来导入其他命名空间，这样我们就可以在各个私有环境之间分享类型。\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tnamespace \"Test\"\n\n\tclass \"A\" (function(_ENV)\n\t\tenum \"Type\" { Data = 1, Object = 2 }\n\tend)\nend)\n\nPLoop(function(_ENV)\n\tprint(A)      -- nil\n\n\t-- 我们可以直接访问根命名空间实体\n\tprint(Test.A) -- Test.A\n\n\t-- 使用import来导入命名空间\n\timport \"Test\"\n\n\t-- 现在我们可以直接访问A\n\tprint(A)      -- Test.A\n\n\tprint(Data)   -- nil\n\n\timport \"Test.A.Type\"\n\n\t-- 对于被导入的命名空间，环境将之间使用ns[name]的方法\n\t-- 获取结果，而不关心它具体是什么\n\tprint(Data)   -- 1\nend)\n```\n\n### 特性和全局函数\n\n在私有环境中定义全局函数时，我们可以使用各种特性来封装这些函数或者将这些函数注册到其他系统以备他用。\n\n使用来自[PLoop_Web](https://github.com/kurapica/PLoop_Web)的一个例子：\n\n```lua\nrequire \"PLoop_Web\"\n\nApplication \"WebApplication\"(function(_ENV)\n\t-- 这个例子是将函数绑定到类似下面的http请求地址\n\t-- /nginx?var=request_uri\n\t-- __Route__特性用于将请求处理方法绑定到url地址\n\t-- __text__特性用于标记这个函数的返回结果将作为\n\t-- \"text/plain\"类型发送给浏览器\n\t__Route__ \"/nginx\"\n\t__Text__()\n\tfunction GetVars(context)\n\t\treturn ngx.var[context.Request.QueryString[\"var\"] or \"nginx_version\"]\n\tend\nend)\n```\n\n### 使用命名空间作为调用者\n\n我们在上面的例子中大量使用了**PLoop**，那么它对于系统来说，具体是什么呢？\n\n它实际也是一个命名空间实体，所有的根命名空间都保存在它里面，不过它本身是匿名的，所以，无法通过路径访问它。\n\n```lua\nrequire \"PLoop\"\n\nprint(PLoop.System.Collections.List) -- System.Collections.List\n```\n\n类似于**PLoop**，我们可以将其他命名空间实体作为调用者来调用函数。\n\n```lua\nrequire \"PLoop\"\n\nnamespace \"Test\" (function(_ENV)\n\tenum \"A\" {}\n\n\tprint(A)  -- Test.A\nend)\n```\n\n如例子所见，如果我们用Test作为函数的调用者，那么这个函数的环境所属的命名空间就是调用者本身。\n\n不过这种方式并不推荐，因为**PLoop**库仅确保`_G`中的**PLoop**是来自自身，类似**class**, **namespace**等关键字可能会来自其他的Lua库。为了确保不会和其他Lua库冲突，使用**PLoop**作为调用者是最简单的方式。（当然如果你确保了没有冲突的可能，这种写法也没有任何问题）\n\n\n### 全局变量的读取\n\n当私有环境访问自身不存在的全局变量时，私有环境会根据自身配置按照顺序进行查找：\n\n* 查找这个环境所属的命名空间\n\n* 查找这个环境**import**的命名空间\n\n* 查找公共命名空间\n\n* 尝试匹配根命名空间，比如访问**System**\n\n* 查找基础环境，私有环境可以设置自己的基础环境，通常是`_G`\n\n在命名空间中查找变量名的规则是:\n\n* 对比命名空间的名字（路径最后部分，比如**System.Form**的名字是**Form**)，一致就返回该命名空间\n\n* 直接使用`命名空间[变量名]`获取，通常结果会是子命名空间比如`System[\"Form\"]`得到**System.Form**，也可能是类型，比如`System.Collections[\"List\"]`，也可能是类型本身提供的资源，比如类的静态方法，枚举类型的枚举值等。\n\n```lua\nrequire \"PLoop\"\n\nPLoop (function(_ENV)\n\tnamespace \"Test\"\n\n\tenum \"A\" {}\n\tenum \"Test2.B\" {}\n\n\tnamespace \"Another\"\nend)\n\nPLoop (function(_ENV)\n\tnamespace \"Test\"\n\n\t-- 访问同命名空间中的类型\n\tprint(A)     -- Test.A\n\n\timport \"Test2\"\n\n\t-- 访问import的命名空间中的类型\n\tprint(B)     -- Test2.B\n\n\t-- 访问公共命名空间中的类型\n\tprint(List)  -- System.Collections.List\n\n\t-- 访问根命名空间\n\tprint(Another) -- Another\n\n\t-- 访问基础环境\n\tprint(math)    -- table:xxxxxxx\nend)\n```\n\n### 自动缓存机制\n\n为了运行效率，私有环境访问到不存在自身的全局变量时，并且处于运行阶段时，私有环境会自动缓存这个值，不过在定义阶段时，环境不会自动缓存。\n\n```lua\nrequire \"PLoop\"\n\nPLoop (function(_ENV)\n\t-- System.Collections.List  nil\n\tprint(List, rawget(_ENV, \"List\"))\n\n\t_G.Dojob = function()\n\t\tprint(List, rawget(_ENV, \"List\"))\n\tend\nend)\n\n-- System.Collections.List  System.Collections.List\nDojob()\n```\n\n当使用**PLoop**调用函数体时，里面的代码处于定义期，定义期的代码只会运行一次，而被访问到的全局变量等几乎只会被访问这一次，所以，此时缓存是没有意义的。\n\n当我们调用`Dojob()`时，它的代码是运行阶段，我们可以反复的调用这个函数，那么这时我们需要缓存访问的变量，之后就不会再进行查询了。\n\n这个过程完全由系统自行控制，通常不需要在意这个细节。它也不会造成问题。（多OS-thread平台下有些区别，以后有专门文档讨论）\n\n\n## 重载\n\n在之前的例子中我们演示了函数参数的类型验证，不过`System.__Arguments__`的设计目的是为了实现方法重载。\n\n在List对象的创建中，我们有多种参数组合来进行构建，如果完全依赖手写判定来区分这些组合，将会非常困难，同时我们也经常需要处理同一个方法，不同输入的情况，每次都自行实现既难以维护，也不方便扩展。\n\n而借助`__Arguments__`，我们可以将选择权交给系统：\n\n```lua\nrequire \"PLoop\"\n\nPLoop (function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t__Arguments__{ String }\n\t\tfunction SetInfo(self, name)\n\t\t\tprint(\"The name is \" .. name)\n\t\tend\n\n\t\t__Arguments__{ NaturalNumber }\n\t\tfunction SetInfo(self, age)\n\t\t\tprint(\"The age is \" .. age)\n\t\tend\n\n\t\t__Arguments__{ String, NaturalNumber }\n\t\tfunction SetInfo(self, name, age)\n\t\t\tself:SetInfo(name)\n\t\t\tself:SetInfo(age)\n\t\tend\n\tend)\n\n\to = Person()\n\n\t-- The name is Ann\n\t-- The age is 24\n\to:SetInfo(\"Ann\", 24)\nend)\n```\n\n可见，我们可以将一组函数绑定成一个方法，也可以做成构造体函数，元方法等。\n\n如果我们需要调用同名的其他重载方法，我们只需要使用`obj:method(xxx)`的方式使用不同参数调用即可。\n\n### this和构造体方法\n\n调用对象构造体(`__exist`, `__new`, `__ctor`)有些特别，因为不存在类似`obj:method(xxx)`这样的方式直接使用。\n\n重载系统为此提供了**this**关键字（注意它并非class系统提供的，class系统本身没有重载功能），我们仅需要使用`this(...)`将所需参数传入即可:\n\n\n```lua\nrequire \"PLoop\"\n\nPLoop (function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t__Arguments__{ String }\n\t\tfunction __exist(self, name)\n\t\t\tprint(\"[exist]The name is \" .. name)\n\t\tend\n\n\t\t__Arguments__{ NaturalNumber }\n\t\tfunction __exist(self, age)\n\t\t\tprint(\"[exist]The age is \" .. age)\n\t\tend\n\n\t\t__Arguments__{ String, NaturalNumber }\n\t\tfunction __exist(self, name, age)\n\t\t\tthis(self, name)\n\t\t\tthis(self, age)\n\t\tend\n\n\t\t__Arguments__{ String }\n\t\tfunction __new(self, name)\n\t\t\tprint(\"[new]The name is \" .. name)\n\t\tend\n\n\t\t__Arguments__{ NaturalNumber }\n\t\tfunction __new(self, age)\n\t\t\tprint(\"[new]The age is \" .. age)\n\t\tend\n\n\t\t__Arguments__{ String, NaturalNumber }\n\t\tfunction __new(self, name, age)\n\t\t\tthis(self, name)\n\t\t\tthis(self, age)\n\t\tend\n\n\t\t__Arguments__{ String }\n\t\tfunction Person(self, name)\n\t\t\tprint(\"[ctor]The name is \" .. name)\n\t\tend\n\n\t\t__Arguments__{ NaturalNumber }\n\t\tfunction Person(self, age)\n\t\t\tprint(\"[ctor]The age is \" .. age)\n\t\tend\n\n\t\t__Arguments__{ String, NaturalNumber }\n\t\tfunction Person(self, name, age)\n\t\t\tthis(self, name)\n\t\t\tthis(self, age)\n\t\tend\n\tend)\n\n\t-- [exist]The name is Ann\n\t-- [exist]The age is 12\n\t-- [new]The name is Ann\n\t-- [new]The age is 12\n\t-- [ctor]The name is Ann\n\t-- [ctor]The age is 12\n\to = Person(\"Ann\", 12)\nend)\n```\n\n请不要在其他重载方法中使用**this**关键字，它仅用于这三种构造体方法。\n\n\n### 使用超类方法处理未处理的参数样式\n\n当我们重写了超类的方法或者构造体等，但我们有需要使用超类的方法来处理我们不希望自己处理的参数样式时，我们可以使用`__Arguments__.Rest()`特性修饰函数来传递给超类方法:\n\n```lua\nrequire \"PLoop\"\n\nPLoop (function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t__Arguments__{ String, NaturalNumber }\n\t\tfunction Person(self, name, age)\n\t\t\tprint(\"The name is \" .. name)\n\t\t\tprint(\"The age is \" .. age)\n\t\tend\n\tend)\n\n\tclass \"Student\" (function(_ENV)\n\t\tinherit \"Person\"\n\n\t\t__Arguments__{ String, NaturalNumber, Number }\n\t\tfunction Student(self, name, age, score)\n\t\t\tthis(self, name, age)\n\t\t\tself.score = score\n\t\t\tprint(\"The score is \" .. score)\n\t\tend\n\n\t\t-- Rest表示捕捉其他任何参数组合\n\t\t__Arguments__.Rest()\n\t\tfunction Student(self, ...)\n\t\t\tsuper(self, ...)\n\t\tend\n\tend)\n\n\t-- The name is Ann\n\t-- The age is 12\n\t-- The score is 80\n\to = Student(\"Ann\", 12, 80)\nend)\n```\n\n### System.Variable\n\n之前的例子中使用的参数都是指定类型，这些都是必须参数，如果需要定义可选参数，可变参数时，我们就需要提供额外的信息。\n\n`__Arguments__`只接受一个参数，这个参数的类型是**System.Variables**，它是一个数组结构体，它的元素类型是**System.Variable**，下面是它的结构演示:\n\n```lua\nstruct \"Variable\" (function(_ENV)\n\tname    = NEString      -- 变量的名字\n\ttype    = AnyType       -- 变量类型\n\toptional= Boolean       -- 是否可选变量\n\tdefault = Any           -- 可选变量的默认值\n\tvarargs = Boolean       -- 是否可变参数\n\tmincount= NaturalNumber -- 可变参数最小数目，默认0\n\n\t-- 返回一个指定类型和默认值的可选参数\n\tOptional= function(type, default) end\n\n\t-- 返回一个指定类型和最小数量的可变参数\n\tRest    = function(type, mincount) end\nend)\n```\n\n这是可选参数的例子：\n\n```lua\nrequire \"PLoop\"\n\nPLoop (function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t__Arguments__{ Variable.Optional(Number, 0) }\n\t\tfunction SetInfo(self, age)\n\t\t\tprint(\"The age is \" .. age)\n\t\tend\n\tend)\n\n\to = Person()\n\n\t-- The age is 0\n\to:SetInfo()\nend)\n```\n\n下面是可变参数的例子：\n\n```lua\nrequire \"PLoop\"\n\nPLoop (function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t__Arguments__{ Variable.Rest(String) }\n\t\tfunction AddChild(self, ...)\n\t\tend\n\tend)\n\n\to = Person()\n\n\t-- Usage: Person:AddChild([... as System.String]) - the 2nd argument must be string, got number\n\to:AddChild(\"Ann\", 1)\nend)\n```\n\n我们也可以提供更多的信息，这样产生的错误信息会更明确：\n\n```lua\nrequire \"PLoop\"\n\nPLoop (function(_ENV)\n\tclass \"Person\" (function(_ENV)\n\t\t__Arguments__{\n\t\t\tVariable(\"name\", String, true, \"anonymous\"),\n\t\t\tVariable(\"age\", NaturalNumber, true, 0)\n\t\t}\n\t\tfunction SetInfo(self, name, age)\n\t\t\tself:SetInfo(name)\n\t\t\tself:SetInfo(age)\n\t\tend\n\tend)\n\n\to = Person()\n\n\t-- Usage: Person:SetInfo([name as System.String = \"anonymous\"], [age as System.NaturalNumber = 0]) - the 1st argument must be string, got boolean\n\to:SetInfo(true)\nend)\n```\n\n### 申明变量的简易版本\n\n为了定义可选和可变参数不断的使用**Variable**是比较辛苦的用法，因为过于常用，**PLoop**为此提供了简便的处理方式：\n\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Arguments__{ String/\"anonymous\", Number * 0 }\n\tfunction Test(...)\n\t\tprint(...)\n\tend\n\n\t-- anonymous\n\tTest(nil)\n\n\t-- Usage: Test([System.String = \"anonymous\"], [... as System.Number]) - the 2nd argument must be number, got string\n\tTest(\"hi\", \"next\")\nend)\n```\n\n我们可以使用`type/default`（`type/nil`同样可以使用）来申明可选参数，使用`type * mincount`来申明可变参数。\n\n\n\n## Throw Exception 异常处理\n\n通常来说，错误有两种，一种是返回给调用者，说明调用错误的，一种是自身发生的。前者我们希望错误位置在调用处，后者我们希望错误就在原处，这样便于我们进行处理。\n\n这里涉及到两个问题，第一是，调用层次不明，例如使用类构造对象时，如果单纯使用`error(msg, 2)`那么，定位在**PLoop**核心文件，而不是实际调用处，加上子类调用超类的问题，函数自身是无法定位自己的调用层级的。\n\n解决第一个问题的方案是在最外层使用pcall捕获异常，然后处理后，将错误定位在调用处，但这就造成了第二个问题，如果是我们函数自身的错误，如果pcall将错误位置定位到调用处了，我们无法知道具体的错误地点。\n\n为了解决这个问题，**PLoop**引入了**throw**关键字和**System.Exception**组成异常处理系统。\n\nLua有个特别的设计，`error(msg)`只允许抛出字符串作为错误信息，但如果使用`pcall`来调用函数，函数内可以用`error(table)`的方式抛出table作为错误信息，对我们而言就是错误对象。\n\n如果我们抛出错误对象指明调用错误，而自身内部错误发生时，依然时抛出字符串，在pcall调用处根据错误类型，就可以很好的区分开调用错误和自身错误。\n\n下面看构造体调用错误的处理例子：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"A\" (function(_ENV)\n\t\tlocal function check(self)\n\t\t\tthrow(\"something wrong\")\n\t\tend\n\n\t\tfunction A(self)\n\t\t\tcheck(self)\n\t\tend\n\tend)\n\n\to = A() -- something wrong\nend)\n```\n\n在构造体方法及被其调用的函数中，我们可以使用**throw**关键字，将错误消息（也可以传入Exception对象，但没有必要自己构建）使用**throw**抛出，可以看到错误发生在对象构建的地方。\n\n另一种情况，是在使用重载系统时，函数自身也很难定位自己的被调用层级（因为还有其他的封装特性），同样可以使用throw来处理：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Arguments__{ String }:Throwable()\n\tfunction test(name)\n\t\tthrow(\"we have throwable exception here\")\n\tend\n\n\ttest(\"HI\") -- we have throwable exception here\nend)\n```\n\n注意，需要申明这个重载是`:Throwable()`的，重载方法才会使用pcall来调用实际函数，才能完成这个操作。\n\n注意**throw**在`_G`中是无法使用的，必须在某个**PLoop**的私有环境中（关键字有特殊的设计，它能获取调用自身的环境，但`_G`是无法处理的）。\n\n如果希望自己处理异常处理，那么可以参照下面的例子：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tfunction safecall(func, ...)\n\t\tlocal ok, ret = pcall(func, ...)\n\n\t\tif not ok then\n\t\t\tif type(ret) == \"string\" then\n\t\t\t\terror(ret, 0) -- 保留错误消息的调用层级\n\t\t\telse\n\t\t\t\terror(tostring(ret), 2) -- 异常对象可以直接转换为字符串\n\t\t\tend\n\t\tend\n\tend\n\n\tfunction test()\n\t\tthrow(\"some thing not right\")\n\tend\n\n\tsafecall(test) -- 定位在这里: some thing not right\nend)\n```\n\n你也可以将**throw**修改为**error**来看下定位的差别。\n\n\n## 模板类\n\n**PLoop**的类型定义是使用函数来完成的，函数的第一个参数是`_ENV`用于确保能正确运行于Lua 5.2以上版本。同时，我们也有可能使用它传入其他参数，来对定义进行调整，而这个结果就是模板类：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Arguments__ { AnyType }\n\tclass \"Array\" (function(_ENV, eletype)\n\t\t__Arguments__{ eletype * 0 }\n\t\tfunction __new(cls, ...)\n\t\t\treturn { ... }, true\n\t\tend\n\tend)\n\n\t--Error: Usage: Anonymous([... as System.Integer]) - the 4th argument must be number, got string\n\to = Array[Integer](1, 2, 3, \"hi\", 5)\nend)\n```\n\n首先我们需要使用`System.__Arguments__`特性来申明这个**Array**类是一个模板类，它的默认类型是**System.AnyType**也就是任意的其他类型都可以被使用。\n\n同时，**Array**的定义函数需要增加一个额外参数，用于传递模板类型。\n\n类型定义之后，我们可以使用`Array[Integer]`这种形式传入真实类型，然后使用被创建的新类型。\n\n我们也可以创建多类型的模板类：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Arguments__ { AnyType, AnyType }\n\tclass \"Dict\" (function(_ENV, ktype, vtype)\n\t\t__Arguments__{ ktype, vtype }\n\t\tfunction Add(self, key, value)\n\t\t\tself[key] = value\n\t\tend\n\tend)\n\n\to = Dict[{Integer, String}]()\n\n\t-- Error: Usage: Anonymous:Add(System.Integer, System.String) - the 2nd argument must be string, got boolean\n\to:Add(1, true)\nend)\n```\n\n因为定义形式一样，也可以为定义接口(interface)模板或者结构体(struct)模板类型。\n\n因为类型的定义实际是函数，那么我们也可以使用非类型参数来生成模板类型:\n\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Arguments__{ Number, Number }\n\tstruct \"FixString\" (function(_ENV, min, max)\n\t\t__base = String\n\n\t\tfunction __valid(val)\n\t\t\treturn (#val \u003e max or #val \u003c min) and \"the %s length must between [\" .. min .. \",\" .. max .. \"]\"\n\t\tend\n\tend)\n\n\tV1_3 = FixString[{1, 3}]\n\n\t-- true 同样参数的模板类型不会重复生成\n\tprint(V1_3 == FixString[{1, 3}])\n\n\t-- 我们可以获得模板类型的原型和参数\n\t-- FixString\t1\t3\n\tprint(Struct.GetTemplate(V1_3), Struct.GetTemplateParameters(V1_3))\n\n\t-- Error:  the value length must between [1,3]\n\ta = V1_3(\"Hello\")\nend)\n```\n\n上面定义的模板类型，必须传入实际类型后才能被正确使用，但如果希望模板类型可被使用的话，也可以在`__Arguments`特性申明后，增加一次调用来传入模板参数:\n\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Arguments__{ Number, Number }(1, 4)\n\tstruct \"FixString\" (function(_ENV, min, max)\n\t\t__base = String\n\n\t\tfunction __valid(val)\n\t\t\treturn (#val \u003e max or #val \u003c min) and \"the %s length must between [\" .. min .. \",\" .. max .. \"]\"\n\t\tend\n\tend)\n\n\t-- Error: the value length must between [1,4]\n\ta = FixString(\"Hello\")\nend)\n```\n\n\n## System.Module\n\n**PLoop**使用私有环境来隔离代码，但对于项目来说，我们依然需要它们之间能共享些资源。\n\n为了对项目进行管理，**PLoop**提供了**System.Module**类，它的对象基于**PLoop**的私有环境系统定义的。\n\n以一个例子开始：\n\n```lua\nrequire \"PLoop\"\n\n_ENV = Module \"TestMDL\" \"1.0.0\"\n\nnamespace \"Test\"\n\n__Async__()\nfunction dotask()\n\tprint(coroutine.running())\nend\n```\n\n`Module \"TestMDL\"`是`Module(\"TestMLD\")`的省略写法，它用来创建了一个Module对象，然后我们调用它，并传入一个版本号字符串（可以为空字符串），之后当前代码（仅限于这个文件）的执行环境会被修改为这个Module对象。使用`_ENV =`是为了确保在任何Lua5.1以上版本中都能使用。\n\n之后，我们就可以随意使用**PLoop**提供的各种功能。\n\n### child-modules 子模组\n\n一个Module对象可以有多个子模组：\n\n```lua\n_ENV = Module \"TestMDL.SubMDL\" \"1.0.0\"\n\nenum \"A\" {}\n\nprint(A) -- Test.A\n\ndotask() -- thread: 02E7F75C\tfalse\n\nfunction dosubtask()\nend\n```\n\n```lua\n_ENV = Module \"TestMDL.SubMDL2\" \"1.0.0\"\n\nprint(dosubtask) -- nil\n```\n\n一个模组可以用任意多的子模组，但仅能有一个父模组，所以存在一个根模组，它的全局变量将被所有子模组共享。\n\n子模组可以访问父模组的全局变量，而根模组可以访问`_G`中存有的全局变量，同样它们采用访问时缓存的模式来确保运行效率。\n\n子模组被创建时，会使用父模组中申明的命名空间，除非主动使用**namespace**关键字来覆盖它。\n\n子模组无法访问兄弟模组中定义全局变量，不过它们可以通过命名空间共享类型。\n\n你可以无限制的创建子模组类似：\n\n```lua\nModule \"TestMDL.SubMDL2.SSubMDL.XXXX\"\n```\n\n依照这个模式，整个项目会被保存在一个树状的模组系统中。命名空间用于保存类型，而模组则用来保存代码。\n\n\n## Attribute 特性系统\n\n在上面的处理中，我们接触到了很多的内置特性，都是用于修改目标的行为。\n\n### System.IAttribute\n\n我们需要扩展**System.IAttribute**接口或者它的扩展接口来定义特性类：\n\n* **System.IInitAttribute**     代表用于修改目标的定义的接口\n* **System.IApplyAttribute**    代表用于修改目标的接口，类似__Flags__\n* **System.IAttachAttribute**   代表用于附着数据给目标的接口，也可以用于将目标注册到某些系统等操作\n\n它提供了一些虚属性可被覆盖:\n\n* AttributeTarget   - 特性的目标类型，位标识枚举类型\n\t* System.AttributeTargets.All         (默认)\n\t* System.AttributeTargets.Function  - 普通Lua函数，事件处理方法\n\t* System.AttributeTargets.Namespace - 命名空间\n\t* System.AttributeTargets.Enum      - 枚举类型\n\t* System.AttributeTargets.Struct    - 结构体\n\t* System.AttributeTargets.Member    - 结构体成员\n\t* System.AttributeTargets.Method    - 结构体方法，对象方法，元方法等\n\t* System.AttributeTargets.Interface - 接口\n\t* System.AttributeTargets.Class     - 类\n\t* System.AttributeTargets.Object    - 对象\n\t* System.AttributeTargets.Event     - 事件\n\t* System.AttributeTargets.Property  - 属性\n\n* Inheritable       - 特性是否可继承, 默认 false\n\n* Overridable       - 特性附着的数据是否可覆盖, 默认 true\n\n* Priority          - 特性的优先级，越高越先被使用\n\t* System.AttributePriority.Highest\n\t* System.AttributePriority.Higher\n\t* System.AttributePriority.Normal  (默认)\n\t* System.AttributePriority.Lower\n\t* System.AttributePriority.Lowest\n\n* SubLevel          - 特性的优先级次级，数字，同样优先级的特性，SubLevel越高越先被使用, 默认 0\n\n共有三种类型的特性，初始化特性在目标定义前使用，应用特性在目标定义时使用，附着特性在目标定义后被使用：\n\n### System.IInitAttribute 初始化特性\n\n初始化特性用于修改目标的定义，通常用于枚举类型或者函数：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"__SafeCall__\" (function(_ENV)\n\t\textend \"IInitAttribute\"\n\n\t\tlocal function checkret(ok, ...)\n\t\t\tif ok then return ... end\n\t\tend\n\n\t\t--- modify the target's definition\n\t\t-- @param   target                      the target\n\t\t-- @param   targettype                  the target type\n\t\t-- @param   definition                  the target's definition\n\t\t-- @param   owner                       the target's owner\n\t\t-- @param   name                        the target's name in the owner\n\t\t-- @param   stack                       the stack level\n\t\t-- @return  definition                  the new definition\n\t\tfunction InitDefinition(self, target, targettype, definition, owner, name, stack)\n\t\t\treturn function(...)\n\t\t\t\treturn checkret(pcall(definition, ...))\n\t\t\tend\n\t\tend\n\n\t\tproperty \"AttributeTarget\" { default = AttributeTargets.Function + AttributeTargets.Method }\n\tend)\n\n\t__SafeCall__()\n\tfunction test1()\n\t\treturn 1, 2, 3\n\tend\n\n\t__SafeCall__()\n\tfunction test2(i, j)\n\t\treturn i/j\n\tend\n\n\tprint(test1()) -- 1, 2, 3\n\tprint(test2()) -- nothing\nend)\n```\n\n这种类型必须扩展**System.IInitAttribute**并且覆盖**InitDefinition**虚方法，这个方法中的definition就是目标的定义，对于枚举类型来说，就是含有枚举值的table，对于函数，就是它本身。如果这个方法返回了一个新的值，这个值将被作为新的定义被继续使用。\n\n### System.IApplyAttribute 应用特性\n\n这种特性用来对目标进行调整，通常是系统的内置特性使用，以`__Sealed__`为例:\n\n```lua\nclass \"__Sealed__\" (function(_ENV)\n\textend \"IApplyAttribute\"\n\n\t--- apply changes on the target\n\t-- @param   target                      the target\n\t-- @param   targettype                  the target type\n\t-- @param \tmanager \t\t\t\t\tthe definition manager of the target\n\t-- @param   owner                       the target's owner\n\t-- @param   name                        the target's name in the owner\n\t-- @param   stack                       the stack level\n\tfunction ApplyAttribute(self, target, targettype, owner, name, stack)\n\t\tif targettype == AttributeTargets.Enum then\n\t\t\tEnum.SetSealed(target)\n\t\telseif targettype == AttributeTargets.Struct then\n\t\t\tStruct.SetSealed(target)\n\t\telseif targettype == AttributeTargets.Interface then\n\t\t\tInterface.SetSealed(target)\n\t\telseif targettype == AttributeTargets.Class then\n\t\t\tClass.SetSealed(target)\n\t\tend\n\tend\n\n\tproperty \"AttributeTarget\" { default = AttributeTargets.Enum + AttributeTargets.Struct + AttributeTargets.Interface + AttributeTargets.Class }\nend)\n```\n\n这些类型需要扩展**System.IApplyAttribute**，并覆盖**ApplyAttribute**虚方法。这类基本只被系统定义和使用。\n\n对于**ApplyAttribute**方法，它有一个特别的参数*manager*，如果target是struct，interface或者class，那么manager就是它们的定义环境，通过它，我们可以实现一些危险但很有用的功能，比如定义一些通用的类型资源：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"__Name__\" (function(_ENV)\n\t\textend \"IApplyAttribute\"\n\n\t\t--- apply changes on the target\n\t\t-- @param   target                      the target\n\t\t-- @param   targettype                  the target type\n\t\t-- @param \tmanager \t\t\t\t\tthe definition manager of the target\n\t\t-- @param   owner                       the target's owner\n\t\t-- @param   name                        the target's name in the owner\n\t\t-- @param   stack                       the stack level\n\t\tfunction ApplyAttribute(self, target, targettype, manager, owner, name, stack)\n\t\t\tif manager then\n\t\t\t\tEnvironment.Apply(manager, function(_ENV)\n\t\t\t\t\tproperty \"Name\" { type = String }\n\t\t\t\tend)\n\t\t\tend\n\t\tend\n\n\t\tproperty \"AttributeTarget\" { default = AttributeTargets.Interface + AttributeTargets.Class }\n\tend)\n\n\t__Name__()\n\tclass \"A\" {}\n\n\tA().Name = 123 -- Error: the Name must be string, got number\nend)\n```\n\n这是一个比较危险的机能，请按需使用。\n\n\n### System.IAttachAttribute 附着特性\n\n这种特性在目标的定义完成后，被使用，通常用于附着数据或者将目标注册到其它系统（因为此时所有对它的修改都已经完成）。\n\n```lua\nPLoop(function(_ENV)\n\tclass \"__DataTable__\" (function(_ENV)\n\t\textend \"IAttachAttribute\"\n\n\t\t--- apply changes on the target\n\t\t-- @param   target                      the target\n\t\t-- @param   targettype                  the target type\n\t\t-- @param   owner                       the target's owner\n\t\t-- @param   name                        the target's name in the owner\n\t\t-- @param   stack                       the stack level\n\t\tfunction AttachAttribute(self, target, targettype, owner, name, stack)\n\t\t\treturn self.DataTable\n\t\tend\n\n\t\tproperty \"AttributeTarget\" { default = AttributeTargets.Class }\n\n\t\tproperty \"DataTable\" { type = String }\n\tend)\n\n\t__DataTable__{ DataTable = \"Persons\" }\n\tclass \"Person\" {}\n\n\t-- Persons\n\tprint(Attribute.GetAttachedData(__DataTable__, Person))\nend)\n```\n\n这种类型需要扩展**System.IAttachAttribute**接口并覆盖**AttachAttribute**虚方法，这个方法的返回值会被保存，便于之后查询。\n\n### System特性\n\n#### `__Abstract__`\n\n用于标记一个类为抽象类，抽象类无法构建对象。或者标记方法，事件，属性为虚方法，虚方法需要（但不是必须）被子类型实现。\n\n特性目标类型:\n* System.AttributeTargets.Class\n* System.AttributeTargets.Method\n* System.AttributeTargets.Event\n* System.AttributeTargets.Property\n\n\n#### `__AutoCache__`\n\n用于标记一个类，它的对象将缓存自身访问到的对象方法，以保证下次访问时无需通过元表进行访问。但如果类开启了超类对象访问并且它覆盖了超类的方法或者资源，那么自动缓存机制不会被加入。同时，因为方法被缓存，对象也无法使用类重定义后的新方法。\n\n特性目标类型:\n* System.AttributeTargets.Class\n\n用法：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function()\n\t__AutoCache__()\n\tclass \"A\" { Test = function() end}\n\n\to = A()\n\tprint(\"GET\", rawget(o, \"Test\")) -- GET\tnil\n\to:Test()\n\tprint(\"GET\", rawget(o, \"Test\")) -- GET\tfunction: 0x015be630\nend)\n```\n\n\n#### `__AnonymousClass__`\n\n详细信息见[Interface的匿名类](#interface的匿名类)\n\n特性目标类型:\n* System.AttributeTargets.Interface\n\n#### `__AutoIndex__`\n\n详细信息见[enum 枚举类型](#enum-枚举类型)\n\n特性目标类型:\n* System.AttributeTargets.Enum\n\n#### `__Arguments__`\n\n详细信息见[重载](#重载)以及[模板类](#模板类)\n\n特性目标类型:\n* System.AttributeTargets.Struct\n* System.AttributeTargets.Interface\n* System.AttributeTargets.Class\n* System.AttributeTargets.Function\n* System.AttributeTargets.Method\n\n\n#### `__Async__`\n\n详细信息见[特性(Attribute)和协程池(Thread Pool)](#特性attribute和协程池thread-pool)\n\nAttribute Targets:\n* System.AttributeTargets.Function\n* System.AttributeTargets.Method\n\n#### `__Base__`\n\n详细信息见[struct 结构体](#struct-结构体)\n\n特性目标类型:\n* System.AttributeTargets.Struct\n\n#### `__Default__`\n\n详细信息见[enum 枚举类型](#enum-枚举类型)和[struct 结构体](#struct-结构体)\n\n特性目标类型:\n* System.AttributeTargets.Enum\n* System.AttributeTargets.Struct\n* System.AttributeTargets.Member\n\n#### `__Delegate__`\n\n封装目标函数来使用\n\n特性目标类型:\n* System.AttributeTargets.Function\n* System.AttributeTargets.Member\n\n用法：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tfunction decorate(func, ...)\n\t\tprint(\"Call\", func, ...)\n\t\treturn func(...)\n\tend\n\n\t__Delegate__(decorate)\n\tfunction test() end\n\n\t-- Call function: 02E7B1C8  1   2   3\n\ttest(1, 2, 3)\nend)\n```\n\n#### `__EventChangeHandler__`\n\n详细信息见[事件处理方法变更的处理](#事件处理方法变更的处理)\n\n特性目标类型:\n* System.AttributeTargets.Event\n\n#### `__Final__`\n\n设置类或者接口为最终，最终类无法被继承，最终接口无法被其他类型扩展。或者用于标记方法，属性，事件为最终，它们不应被覆盖。\n\n特性目标类型:\n* System.AttributeTargets.Class\n* System.AttributeTargets.Interface\n* System.AttributeTargets.Method\n* System.AttributeTargets.Event\n* System.AttributeTargets.Property\n\n#### `__Flags__`\n\n详细信息见[enum 枚举类型](#enum-枚举类型)\n\n特性目标类型:\n* System.AttributeTargets.Enum\n\n#### `__Get__`\n\n详细信息见[Get/Set行为修饰](#getset行为修饰)\n\n特性目标类型:\n* System.AttributeTargets.Property\n\n#### `__Indexer__`\n\n详细信息见[索引属性](#索引属性)\n\n特性目标类型:\n* System.AttributeTargets.Property\n\n#### `__Iterator__`\n\n详细信息见[特性(Attribute)和协程池(Thread Pool)](#特性attribute和协程池thread-pool)\n\nAttribute Targets:\n* System.AttributeTargets.Function\n* System.AttributeTargets.Method\n\n#### `__Namespace__`\n\n为下一个创建的类型设置姓名空间\n\n特性目标类型:\n* System.AttributeTargets.All\n\n用法：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tnamespace \"Test\"\n\n\t__Namespace__ \"MyNS\"\n\tclass \"A\" {}\n\n\tprint(A)   -- MyNS.A\nend)\n```\n\n#### `__NoNilValue__`\n\n从类对象不存在的字段设置读取值是非法的。\n\n特性目标类型:\n* System.AttributeTargets.Class\n\n用法：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__NoNilValue__()\n\tclass \"A\" {}\n\n\to = A()\n\tv = o.age -- Error: The object don't have any field that named \"age\"\nend)\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__NoNilValue__(false)\n\tclass \"A\" {}\n\n\tprint(A().Test) -- nil\nend)\n```\n\n#### `__NoRawSet__`\n\n向类对象不存在的字段设置值是非法的。\n\n特性目标类型:\n* System.AttributeTargets.Class\n\n用法：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__NoRawSet__()\n\tclass \"A\" {}\n\n\to = A()\n\to.age = 10 -- Error: The object can't accept field that named \"age\"\nend)\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__NoRawSet__(false)\n\tclass \"A\" {}\n\n\tA().Test = 123 -- Okay\nend)\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\tclass \"A\" { Test = function() end }\n\n\to = A()\n\to.Test = 123    -- 错误\n\to.Test = print  -- 正常\n\to.Test1= print  -- 错误\nend)\n```\n\n#### `__ObjectAttr__`\n\n用于标记类，这样特性系统可以使用在它生成的对象上。\n\n特性目标类型:\n* System.AttributeTargets.Class\n\n用法：:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"__Reg__\" (function(_ENV)\n\t\textend \"IAttachAttribute\"\n\n\t\tfunction AttachAttribute(self, target, targettype)\n\t\t\tprint(\"Attach To\", target.name)\n\t\tend\n\n\t\tproperty \"AttributeTarget\"  { set = false, default = AttributeTargets.Object }\n\tend)\n\n\t__ObjectAttr__()\n\tclass \"A\" { name = String }\n\n\t__Reg__()\n\tA{ name = \"Ann\" } -- Attach To Ann\nend)\n```\n\n#### `__ObjFuncAttr__`\n\n向目标类的对象写入新函数时，函数将被传入特性系统被调整（目标类型为function）\n\n特性目标类型:\n* System.AttributeTargets.Class\n\n用法：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__ObjFuncAttr__()\n\tclass \"A\" {}\n\n\to = A()\n\n\t__Async__()\n\tfunction o:Test()\n\t\tprint(coroutine.running())\n\tend\n\n\to:Test() -- thread: 02F195E8\nend)\n```\n\n如果这个类同时被标识为`__NoRawSet__`，我们依然可以向它赋予任意的函数值，因为`__ObjFuncAttr__`特性表明这个类的对象将被用来作为函数的容器。\n\n\n#### `__ObjectSource__`\n\n目标类的对象会被记录构造位置。\n\n特性目标类型:\n* System.AttributeTargets.Class\n\n用法：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__ObjectSource__()\n\tclass \"A\" {}\n\n\to = A()\n\n\tprint(Class.GetObjectSource(o)) -- @path_to_file\\file.lua:7\nend)\n```\n\n#### `__Require__`\n\n设置一个接口的所需类，参考[接口的所需类](#接口的所需类)\n\n特性目标类型:\n* System.AttributeTargets.Interface\n\n\n#### `__Return__`\n\n为函数或方法绑定返回值类型进行验证\n\n特性目标类型:\n* System.AttributeTargets.Function\n* System.AttributeTargets.Method\n\n用法：\n\n如果验证失败，因为调用已经完成，系统会尝试定位函数定义位置：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\t__Return__{ String }\n\tfunction Test() return 1 end\n\n\t-- Error: path_to_file:5: The Test Return: System.String - the 1st return value must be string, got number\n\tTest()\nend)\n```\n\n我们可以依次绑定多种返回值格式:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n    __Return__{ String } { Boolean }\n    function Test() return 1 end\n\n    -- lua: path_to_file:5: The Test should return:\n    --  Return: System.String\n    --  Return: System.Boolean\n    Test()\nend)\n```\n\n类似`__Arguments__`, 我们也可以使用可选和可变参数定义形式:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n    __Return__{ String/\"hello\", Number * 0 }\n    function Test() return nil, 1, 2, 3 end\n\n    -- hello    1   2   3\n    print(Test())\nend)\n```\n\n大多数情况下，我们用于需要限定子类申明方法的返回值类型的接口和超类：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n    interface \"IA\" (function(_ENV)\n        __Return__{ String, Number * 1 }:AsInheritable()\n        __Abstract__() function Test() end\n    end)\n\n    class \"A\" { IA, Test = function() return \"hi\" end }\n\n    -- Error: path_to_file:9: The A.Test Return: System.String, ... as System.Number - the ... must contains at least 1 return values\n    A():Test()\nend)\n```\n\n\n#### `__Sealed__`\n\n封闭枚举，结构体，接口或者类，这样它们无法被重定义。\n\n特性目标类型:\n* System.AttributeTargets.Enum\n* System.AttributeTargets.Struct\n* System.AttributeTargets.Interface\n* System.AttributeTargets.Class\n\n#### `__Set__`\n\n详细信息见[Get/Set行为修饰](#getset行为修饰)\n\n特性目标类型:\n* System.AttributeTargets.Property\n\n#### `__SingleVer__`\n\n详细信息见[类的多重版本](#类的多重版本)\n\n特性目标类型:\n* System.AttributeTargets.Class\n\n#### `__Static__`\n\n设置方法，属性或者事件为静态，只能被类型自身使用。\n\n特性目标类型:\n* System.AttributeTargets.Method\n* System.AttributeTargets.Event\n* System.AttributeTargets.Property\n\n#### `__Super__`\n\n为目标设置一个超类。\n\n特性目标类型:\n* System.AttributeTargets.Class\n\n#### `__SuperObject__`\n\n目标的对象是否使用超类对象访问形式，形如`super[self]:Method()`, `super[self].Name = xxx`.\n\n特性目标类型:\n* System.AttributeTargets.Class\n\n用法：\n```lua\n-- 确保类A使用超类对象访问形式\n__SuperObject__(true)\nclass \"A\" {}\n\n-- 确保类B不使用超类对象访问形式\n__SuperObject__(false)\nclass \"B\" {}\n```\n\n\n#### `__Throwable__`\n\n标记属性的Set方法为throwable，详见[property-throw](#property-throw).\n\n特性目标类型:\n* System.AttributeTargets.Property\n\n\n## keyword 关键字\n\n### 全局关键字\n\n**PLoop**提供两种关键字，一种是全局的，可以在所有**PLoop**的私有环境中使用:\n\n* namespace  -- 为当前环境申明命名空间\n* import     -- 为当前环境导入命名空间\n* export     -- 导出内容到当前环境\n* enum       -- 定义新枚举类型\n* struct     -- 定义新结构体类型\n* interface  -- 定义新接口类型\n* class      -- 定义新类\n* throw      -- 抛出异常\n* with \t     -- 和System.IAutoClose对象一同使用，用于自动调用对象的Open和Close方法\n\n#### export 关键字\n\n关键字**export**是为了多os thread平台设计的：\n\n```lua\nPLOOP_PLATFORM_SETTINGS = { MULTI_OS_THREAD = true }\n\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\texport {\n\t\t-- 缓存全局变量\n\t\tipairs \t= ipairs,\n\n\t\t-- 也可以直接使用全局变量名\n\t\t\"pairs\",\n\n\t\t-- 导入类型，系统能直接获取它的名字\n\t\t-- 所以无需指定\n\t\tList,\n\t}\n\n\t_G.test = function()\n\t\tprint(\"hi\")\n\tend\nend)\n\n-- [PLoop: Warn]The [print] is auto saved to table: 030066C8, need use 'export{ \"print\" }'@path_to_file\\file.lua:16\ntest()\n```\n\n在多os-thread模式中，**PLoop**会警告我们需要使用`export { \"print\" }`来导入*print*函数。\n\n**export**关键字会将table中的内容直接保存在当前环境中，那么既然**PLoop**的私有环境可以自动缓存变量，我们还需要这么处理呢？\n\n比较不幸的是，自动缓存机制在多os-thread环境下的运行机制有些差别，运行期，我们必须避免环境table的rehash问题造成多os-thread访问冲突，为了解决这个问题，**PLoop**另外使用了一个缓存表，每次新值加入时，新的表会被用来替换它，通过无rehash的处理来避免冲突。\n\n但这就导致了，当我们通过私有环境获取自动缓存的全局变量实际时需要通过一次元表调用才能拿到，这虽然开销很小，但如果使用**export**我们可以完全去掉这开销。这对于写库是很重要的做法。\n\n对于非多os-thread平台来说，也就是Lua常对应的平台，它可以配合[写非法全局变量](#写非法全局变量)来使用，我们可以将需要被定义全局变量都在**export**中申明，这样任意其他的全局变量赋值都是非法的：\n\n\n```lua\nPLOOP_PLATFORM_SETTINGS = { GLOBAL_VARIABLE_FILTER = function() return true end, GLOBAL_VARIABLE_FILTER_USE_WARN = true }\n\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\texport {\n\t\t-- declare constant\n\t\tCONST_VAR_DATA  = 1,\n\n\t\t-- declare other global variables\n\t\tdotask \t\t\t= false,\n\t}\n\n\tfunction dotask() -- it's ok now\n\tend\n\n\t-- [PLoop: Warn]There is an illegal assignment for \"test\"@path_to_file\\file.lua:17\n\tfunction test()\n\tend\nend)\n```\n\n#### with 关键字\n\n**System.IAutoClose**是一个很简单的接口:\n\n```lua\ninterface \"System.IAutoClose\" (function(_ENV)\n    __Abstract__() function Open(self) end\n    __Abstract__() function Close(self, error) end\nend)\n```\n\n它定义了打开和关闭资源的方法，可用于文件，数据库连接等场合。**with**关键字可以接受多个IAutoClose对象，并且自动调用打开和关闭方法，不管是否存在错误:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"A\" { IAutoClose,\n\n\t\tOpen = function(self)\n\t\t\tprint( \"Open \" .. self.name )\n\t\tend,\n\n\t\tClose = function(self, err)\n\t\t\tprint(\"Close \" .. self.name .. (err and (\" with \" .. err) or \" without error\"))\n\t\tend,\n\t}\n\n\t-- Open task\n\t-- process task\n\t-- Close task without error\n\twith(A{ name = \"task\"})(function(obj)\n\t\tprint(\"process \" .. obj.name)\n\tend)\n\n\t-- Open task\n\t-- Open task2\n\t-- process task, task2\n\t-- Close task with path\\test.lua:23: 2333\n\t-- Close task2 with path\\test.lua:23: 2333\n\t-- Catch error:path\\test.lua:23: 2333\n\twith(A{ name = \"task\"}, A{ name = \"task2\"})(function(obj, obj2)\n\t\tprint(\"process \" .. obj.name .. \", \" .. obj2.name)\n\t\terror(\"2333\")\n\tend, function(err)\n\t\tprint(\"Catch error:\" .. err)\n\tend)\nend)\n```\n\n如例子所示，第二个方法被用于捕获错误，如果不指定，那么将直接使用error方法将错误继续抛出，直到它被处理。\n\n我们可以获得所有内部处理的返回值:\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"A\" { IAutoClose }\n\n\t-- 1\t2\t3\t4\n\tprint(with(A())(function(obj)\n\t\treturn 1, 2, 3, 4\n\tend))\nend)\n\n```\n\n下面是来源于实际DB处理的一个例子（参考System.Data系统）:\n\n```lua\nfunction RecordLastLogin(id)\n\t-- 创建DB上下文，打开数据库连接\n\twith(MyDBContext())(function(ctx)\n\t\t-- 启动数据库事务\n\t\twith(ctx.Transaction)(function(trans)\n\t\t\t-- 查询并锁定目标用户数据\n\t\t\tlocal user = ctx.Users:Lock{ id = id }:First()\n\t\t\tif user then\n\t\t\t\tuser.LastLogin = Date.Now\n\n\t\t\t\t-- 提交修改给数据库\n\t\t\t\tctx:SaveChanges()\n\t\t\telse\n\t\t\t\t-- 取消事务处理\n\t\t\t\ttrans:Rollback()\n\t\t\tend\n\t\tend)\n\tend)\nend\n```\n\n\n### 上下文相关的关键字\n\n其他的关键字都是为了特定上下文定义的，比如结构体，接口，类的定义环境：\n\n* struct\n\t* member   -- 定义结构体成员\n\t* array    -- 设置数组元素类型\n* interface\n\t* require  -- 设置接口的需要类\n\t* extend   -- 扩展其他接口\n\t* field    -- 添加对象字段\n\t* event    -- 定义事件\n\t* property -- 定义属性\n* class\n\t* inherit  -- 继承类\n\t* extend   -- 扩展其他接口\n\t* field    -- 添加对象字段\n\t* event    -- 定义事件\n\t* property -- 定义属性\n\n### `_G`中可用的资源\n\n**PLoop**会尝试将一些关键字和类型保存到`_G`中，这样你可以直接使用它们:\n\n* PLoop \t -- 所有命名空间的根\n* namespace  -- 为`_G`申明命名空间\n* import     -- 将命名空间及其内部的子命名空间实体都保存到`_G`\n* enum       -- 定义新枚举类型\n* struct     -- 定义新结构体类型\n* interface  -- 定义新接口类型\n* class      -- 定义新类\n* Module     -- System.Module\n\n只有**PLoop**必定存在，其他不会覆盖`_G`中同名的其他变量。\n\n\n## Serialization 序列化\n\n### 从JSON开始\n\n这是一个完整的序列化和反序列化的例子：\n\n\n```lua\nrequire \"PLoop\" (function(_ENV)\n\timport \"System.Serialization\"\n\n\tjson = [==[\n\t{\n\t\t\"debug\": \"on\\toff\",\n\t\t\"nums\" : [1,7,89,4,5,6,9,3,2,1,1,9,3,0,11]\n\t}]==]\n\n\t-- 反序列化json数据为lua table\n\tdata = Serialization.Deserialize(JsonFormatProvider(), json)\n\n\t-- 序列化lua table为字符串，带缩进\n\t-- {\n\t-- \t\tdebug = \"on\toff\",\n\t-- \t\tnums = {\n\t-- \t\t\t[1] = 1,\n\t-- \t\t\t[2] = 7,\n\t-- \t\t\t[3] = 89,\n\t-- \t\t\t[4] = 4,\n\t-- \t\t\t[5] = 5,\n\t-- \t\t\t[6] = 6,\n\t-- \t\t\t[7] = 9,\n\t-- \t\t\t[8] = 3,\n\t-- \t\t\t[9] = 2,\n\t-- \t\t\t[10] = 1,\n\t-- \t\t\t[11] = 1,\n\t-- \t\t\t[12] = 9,\n\t-- \t\t\t[13] = 3,\n\t-- \t\t\t[14] = 0,\n\t-- \t\t\t[15] = 11\n\t-- \t\t}\n\t-- }\n\tprint(Serialization.Serialize(StringFormatProvider{Indent = true}, data))\nend)\n```\n\n这个例子使用**System.Serialization**通过**System.Serialization.JsonFormatProvider**来反序列化json字符串为lua的普通table，然后使用**System.Serialization.StringFormatProvider**将这个普通table转换成lua的字符串。\n\n**System.Serialization.Serialize**和 **System.Serialization.Deserialize**是两个静态方法。\n\n**System.Serialization.Serialize**用于将**PLoop**的对象或者数据转换为普通的Lua数据，然后使用传入的格式工具（FormatProvider）将Lua数据转换为目标数据，例如字符串，或者JSON数据。\n\n**System.Serialization.Deserialize**先使用传入的格式工具将目标数据转换为普通Lua数据，然后根据传入的类型将Lua数据转换为对象或者普通数据。\n\n* Serialize : PLoop object -\u003e lua table -\u003e target format( string, json, xml )\n* Deserialize : target format -\u003e lua table -\u003e PLoop object\n\n\nJson是常见的序列化处理，每次使用JsonFormatProvider也比较麻烦，实际可以直接用`Toolset.json(data[,type])`将对象或者数据转换为Json数据包，或者用\n`Toolset.parsejson(json[, type])`将Json数据转换为Lua的数据或者PLoop的对象。\n\n同样，针对**StringFormatProvider**可以使用`Toolset.tostring(data[, type[, pretty]])`将对象或者数据序列化为字符串，或者用\n`Toolset.parsestring(str[, type])`将字符串转换为Lua的数据或者PLoop的对象。\n\n\n### 可序列化类型\n\n并非所有的**PLoop**类型都是可以序列化的，枚举类型均是可序列化的，可序列化的类或自定义结构体必须使用`System.Serialization.__Serializable__`特性标记，一个数组结构体仅当它的元素类型是可序列化，一个成员结构体仅当它的所有成员类型是可序列化的。\n\n可以使用`System.Serialization.__NonSerialized__`标记不可序列化的属性（property）或者结构体成员（member）。\n\n后面的例子中，我们只使用字符串作为目标格式，所以，我们仅需要使用**StringFormatProvider**。\n\n首先看一个例子：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\timport \"System.Serialization\"\n\n\tnamespace \"Test\"\n\n\t__Serializable__()\n\tclass \"Person\" {\n\t\tName = String,\n\t\tAge  = Number,\n\t\tChilds = struct { Person }\n\t}\n\n\tKing = Person {\n\t\tName = \"King\", Age = 65,\n\t\tChilds = {\n\t\t\tPerson {\n\t\t\t\tName = \"Ann\", Age = 33,\n\t\t\t\tChilds = {\n\t\t\t\t\tPerson { Name = \"Dio\", Age = 12 }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t--\t{\n\t--\t\t__PLoop_Serial_ObjectType = \"Test.Person\",\n\t--\t\tChilds = {\n\t--\t\t\t[1] = {\n\t--\t\t\t\t__PLoop_Serial_ObjectType = \"Test.Person\",\n\t--\t\t\t\tChilds = {\n\t--\t\t\t\t\t[1] = {\n\t--\t\t\t\t\t\t__PLoop_Serial_ObjectType = \"Test.Person\",\n\t--\t\t\t\t\t\tName = \"Dio\",\n\t--\t\t\t\t\t\tAge = 12\n\t--\t\t\t\t\t}\n\t--\t\t\t\t},\n\t--\t\t\t\tName = \"Ann\",\n\t--\t\t\t\tAge = 33\n\t--\t\t\t}\n\t--\t\t},\n\t--\t\tName = \"King\",\n\t--\t\tAge = 65\n\t--\t}\n\tprint( Serialization.Serialize( StringFormatProvider{ Indent = true }, King ) )\nend)\n```\n\n**StringFormatProvider**有以下属性：\n\n* Indent - 是否使用缩进，默认false\n* LineBreak - 换行符, 默认'\\n'\n* IndentChar - 缩进符，默认'\\t'\n* ObjectTypeIgnored - 是否不保存对象类型，默认false\n\n因为我们设置**Indent**为true，所以，我们的返回结果是格式化的。我们可以看到多个`__PLoop_Serial_ObjectType`，如果对象的类型不是匿名的，序列化时会保存数据的类型，便于之后反序列化时，系统知道该转换为何种类型。可以设置**ObjectTypeIgnored**为true关闭这个功能。\n\n之后我们可以尝试进行反序列化：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\timport \"System.Serialization\"\n\n\tnamespace \"Test\"\n\n\t__Serializable__()\n\tclass \"Person\" {\n\t\tName = String,\n\t\tAge  = Number,\n\t\tChilds = struct { Person }\n\t}\n\n\tKing = Person {\n\t\tName = \"King\", Age = 65,\n\t\tChilds = {\n\t\t\tPerson {\n\t\t\t\tName = \"Ann\", Age = 33,\n\t\t\t\tChilds = {\n\t\t\t\t\tPerson { Name = \"Dio\", Age = 12 }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdata = Serialization.Serialize( StringFormatProvider{ Indent = true }, King )\n\n\tp = Serialization.Deserialize( StringFormatProvider(), data)\n\n\t-- Test.Person\tDio\n\tprint( getmetatable(p), p.Childs[1].Childs[1].Name)\nend)\n```\n\n根据最后的结果，*p*是**Person**对象，我们拿回了所有的数据，如果我们开启**ObjectTypeIgnored**：\n\n```lua\ndata = Serialization.Serialize( StringFormatProvider{ ObjectTypeIgnored  = true }, King )\n\np = Serialization.Deserialize( StringFormatProvider(), data)\n\n-- nil\tDio\nprint( getmetatable(p), p.Childs[1].Childs[1].Name)\n```\n\n现在虽然我们拿到了*Name*，但*p*并非**Person**对象，这是因为系统无法知道数据对应的类型，我们可以在反序列化时传入类型：\n\n```lua\ndata = Serialization.Serialize( StringFormatProvider{ ObjectTypeIgnored  = true }, King )\n\np = Serialization.Deserialize( StringFormatProvider(), data, Person)\n\n-- Test.Person\tDio\nprint( getmetatable(p), p.Childs[1].Childs[1].Name)\n```\n\n通常来说，我们需要在**Serialize**和**Deserialize**中都传入类型，不过对于**Person**对象，系统可以直接从它上面获取类型信息，所以，在之前处理中可以无视这条。\n\n不过如果我们对结构体使用序列化机制，就必须给出类型，因为系统无法自行获得。\n\n至于为什么要提供结构体类型给普通的Lua数据（结构体数据一般都是普通Lua数据）。原因在于，类型会被传递给格式工具类，将会有利于格式工具处理数据，比如数据是数组结构体，那么生成Json时，就不需要检查里面的所有数据才能推断出来。\n\n### 自定义序列化和反序列化\n\n序列化系统只能处理类的属性值，而无法处理它可能存在的字段等，如果需要将这些数据序列化和反序列化，就需要类自行提供功能。如果类存在构造体，系统也无法直接传入初始化表来构造对象，同样需要类自己提供构造功能。\n\n如果类需要自行处理序列化操作，它必须扩展**System.Serialization.ISerializable**接口，然后覆盖**Serialize**虚方法，这个方法接收一个**System.Serialization.SerializationInfo**对象，这个类有两个方法：\n\n* obj:SetValue(name, value, valueType)  -- 将键值按照类型保存到obj对象中\n* obj:GetValue(name, valueType)         -- 从obj对象中按类型获取值\n\n利用这个**SerializationInfo**对象，类可以写入需要序列化的数据，也可以从中读取用来构造对象的值：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\timport \"System.Serialization\"\n\n\tnamespace \"Test\"\n\n\t__Serializable__()\n\tclass \"Person\" (function (_ENV)\n\t\textend \"ISerializable\"\n\n\t\tproperty \"Name\" { Type = String }\n\t\tproperty \"Age\"  { Type = Number }\n\n\t\tfunction Serialize(self, info)\n\t\t\t-- 按类型写入需要序列化的数据\n\t\t\tinfo:SetValue(\"name\", self.Name, String)\n\t\t\tinfo:SetValue(\"age\",  self.Age, Number)\n\t\tend\n\n\t\t__Arguments__{ String, Number }\n\t\tfunction Person(self, name, age)\n\t\t\tself.Name = name\n\t\t\tself.Age = age\n\t\tend\n\n\t\t-- 反序列化构造体\n\t\t__Arguments__{ SerializationInfo }\n\t\tfunction Person(self, info)\n\t\t\t-- 按类型获取保存的值\n\t\t\tthis(self, info:GetValue(\"name\", String) or \"Noname\", info:GetValue(\"age\", Number) or 0)\n\t\tend\n\tend)\n\n\t__Serializable__()\n\tclass \"Student\"(function (_ENV)\n\t\tinherit \"Person\"\n\n\t\tproperty \"Score\" { Type = Number }\n\n\t\tfunction Serialize(self, info)\n\t\t\t-- 保存子类型的数据\n\t\t\tinfo:SetValue(\"score\", self.Score, Number)\n\n\t\t\t-- 调用超类的序列化方法\n\t\t\tsuper.Serialize(self, info)\n\t\tend\n\n\t\t-- 子类反序列化构造体\n\t\t__Arguments__{ SerializationInfo }\n\t\tfunction Student(self, info)\n\t\t\t-- 调用超类反序列化构造体\n\t\t\tsuper(self, info)\n\n\t\t\t-- 获取子类所需的值\n\t\t\tself.Score = info:GetValue(\"score\", Number)\n\t\tend\n\n\t\t__Arguments__.Rest()\n\t\tfunction Student(self, ...)\n\t\t\tsuper(self, ...)\n\t\tend\n\tend)\n\n\tAnn = Student(\"Ann\", 16)\n\tAnn.Score = 81\n\n\tdata = Serialization.Serialize( StringFormatProvider(), Ann)\n\n\t-- {__PLoop_Serial_ObjectType=\"Test.Student\",name=\"Ann\",age=16,score=81}\n\tprint(data)\n\n\tp = Serialization.Deserialize( StringFormatProvider(), data)\n\n\t-- Test.Student\tAnn\t16\t81\n\tprint( getmetatable(p), p.Name, p.Age, p.Score)\nend)\n```\n\n\n## System.Collections 集合\n\n在[从使用集合开始](#从使用集合开始)中我们已经了解了**List**和**Dictionary**两种集合类型，现在我们更深入的进行说明。\n\n### System.Collections.Iterable\n\n这个接口是集合最基本的接口，它只有一个虚方法**GetIterator**，用于返回一个供泛型for使用的迭代器。\n\n### System.Collections.IList\n\n**IList**接口代表数组集合，数组集合仅关心元素，它们的索引在通常操作中可以被无视。它扩展了**Iterable**接口。\n\n特别的，List使用的**Map**, **Filter**, **Range**, **ToList**, **Reduce**, **Each**, **Any**, **All**, **First**这类链式方法都是定义在这个接口中，所以，如果类扩展了这个接口，就可以利用这些方法。\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\tclass \"Queue\" (function(_ENV)\n\t\textend \"IList\"\n\n\t\t__Iterator__()\n\t\tfunction GetIterator(self)\n\t\t\tfor i = self.Start, self.End - 1 do\n\t\t\t\tcoroutine.yield(i, self[i])\n\t\t\tend\n\t\tend\n\n\t\t-- Queue(1, 2, 3, 4)\n\t\tfunction __new(cls, ...)\n\t\t\treturn {...}, true\n\t\tend\n\n\t\tfunction Queue(self)\n\t\t\tself.Start = 1\n\t\t\tself.End   = #self + 1\n\t\tend\n\n\t\tfunction __call(self, val)\n\t\t\tif val ~= nil then\n\t\t\t\t-- queue\n\t\t\t\tlocal endp = self.End\n\t\t\t\tself[endp] = val\n\t\t\t\tself.End   = endp + 1\n\t\t\telse\n\t\t\t\t-- dequeue\n\t\t\t\tlocal start= self.Start\n\t\t\t\tif start \u003c self.End then\n\t\t\t\t\tval    = self[start]\n\t\t\t\t\tself[start] = nil\n\t\t\t\t\tself.Start  = start + 1\n\t\t\t\t\treturn val\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend)\n\n\tqueue = Queue(1, 2, 3, 4, 5)\n\tqueue(queue())\n\tqueue(queue())\n\n\tqueue:Each(print) -- 3  4  5  1  2\nend)\n```\n\n#### System.Collections.ICountable\n\n**ICountable**代表可以计数的数组集合，它扩展了**IList**接口。\n\n它只定义了一个**Count**虚属性，默认返回#self作为数组长度。\n\n#### System.Collections.IIndexedList\n\n**IIndexedList**接口代表数字索引集合，类可以使用`obj[idx]`的连续数字索引访问它的元素，它扩展了**ICountable**接口。\n\n特别的，List使用的Sort之类排序算法都定义在这个接口中。\n\n#### System.Collections.List\n\n**List**类扩展了**IIndexedList**接口，所以它可以使用所有的链式方法和排序算法。\n\n### System.Collections.IDictionary\n\n**IDictionary**代表所有的键值对集合，它扩展了**Iterable**接口。\n\n字典链式处理方法 **Map**, **Filter**, **Reduce**, **Each**和**Keys**, **Values**这两个终止属性都是定义在这个接口。\n\n#### System.Collections.Dictionary\n\n**IDictionary**的唯一实现，通常足以满足日常用途。\n\n### List, Dictionary和序列化\n\n为了简化序列化的处理，**List**和**Dictionary**都被申明为可序列化的类型：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\timport \"System.Serialization\"\n\n\to = Dictionary{ A = Date(2013, 8, 13), B = Date(2017, 4, 2), C = Date(2018, 3, 14)}\n\n\tv = Serialization.Serialize( StringFormatProvider{ Indent = true, ObjectTypeIgnored = false  }, o )\n\n\t--\t{\n\t--\t\t__PLoop_Serial_ObjectType = \"System.Collections.Dictionary\",\n\t--\t\t[1] = {\n\t--\t\t\t__PLoop_Serial_ObjectType = \"System.Collections.List\",\n\t--\t\t\t[1] = \"A\",\n\t--\t\t\t[2] = \"C\",\n\t--\t\t\t[3] = \"B\"\n\t--\t\t},\n\t--\t\t[2] = {\n\t--\t\t\t__PLoop_Serial_ObjectType = \"System.Collections.List\",\n\t--\t\t\t[1] = {\n\t--\t\t\t\t__PLoop_Serial_ObjectType = \"System.Date\",\n\t--\t\t\t\ttime = 1376366400\n\t--\t\t\t},\n\t--\t\t\t[2] = {\n\t--\t\t\t\t__PLoop_Serial_ObjectType = \"System.Date\",\n\t--\t\t\t\ttime = 1521000000\n\t--\t\t\t},\n\t--\t\t\t[3] = {\n\t--\t\t\t\t__PLoop_Serial_ObjectType = \"System.Date\",\n\t--\t\t\t\ttime = 1491105600\n\t--\t\t\t}\n\t--\t\t}\n\t--\t}\n\tprint(v)\n\n\to = Serialization.Deserialize( StringFormatProvider(), v)\n\n\t-- \tA\t2013-08-13 12:00:00\n\t-- \tB\t2017-04-02 12:00:00\n\t-- \tC\t2018-03-14 12:00:00\n\to:Each(print)\nend)\n```\n\n上面的**Sytem.Date**日期类型也是一个可序列化对象，所以它会被用于完成序列化处理。\n\n仔细看*v*的输出，字典对象实际被分解成两个**List**对象之后再被序列化的。这里面有很多`__PLoop_Serial_ObjectType`来帮助反序列化处理。\n\n不过很多场合下，我们无法传递对象类型:\n\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\timport \"System.Serialization\"\n\n\to = Dictionary{ A = Date(2013, 8, 13), B = Date(2017, 4, 2), C = Date(2018, 3, 14)}\n\n\tv = Serialization.Serialize( StringFormatProvider{ Indent = true, ObjectTypeIgnored = true  }, o )\n\n\t--\t{\n\t--\t\t[1] = {\n\t--\t\t\t[1] = \"A\",\n\t--\t\t\t[2] = \"C\",\n\t--\t\t\t[3] = \"B\"\n\t--\t\t},\n\t--\t\t[2] = {\n\t--\t\t\t[1] = {\n\t--\t\t\t\ttime = 1376366400\n\t--\t\t\t},\n\t--\t\t\t[2] = {\n\t--\t\t\t\ttime = 1521000000\n\t--\t\t\t},\n\t--\t\t\t[3] = {\n\t--\t\t\t\ttime = 1491105600\n\t--\t\t\t}\n\t--\t\t}\n\t--\t}\n\tprint(v)\n\n\to = Serialization.Deserialize( StringFormatProvider(), v, Dictionary)\n\n\t--\tA\ttable: 03026B90\n\t--\tC\ttable: 03026CA8\n\t--\tB\ttable: 03026CF8\n\to:Each(print)\nend)\n```\n\n可见，哪怕反序列化时，传入了**Dictionary**类型，因为序列化系统无法了解键值各自的类型，依然无法反序列化这些元素。\n\n为了解决这个问题，**List**和**Dictionary**都被定义为[模板类](#模板类)，这样我们就可以很方便的键值的类型传进去：\n\n```lua\nrequire \"PLoop\"\n\nPLoop(function(_ENV)\n\timport \"System.Serialization\"\n\n\to = Dictionary{ A = Date(2013, 8, 13), B = Date(2017, 4, 2), C = Date(2018, 3, 14)}\n\n\tv = Serialization.Serialize( StringFormatProvider{ Indent = true, ObjectTypeIgnored = true  }, o )\n\n\t--\t{\n\t--\t\t[1] = {\n\t--\t\t\t[1] = \"A\",\n\t--\t\t\t[2] = \"C\",\n\t--\t\t\t[3] = \"B\"\n\t--\t\t},\n\t--\t\t[2] = {\n\t--\t\t\t[1] = {\n\t--\t\t\t\ttime = 1376366400\n\t--\t\t\t},\n\t--\t\t\t[2] = {\n\t--\t\t\t\ttime = 1521000000\n\t--\t\t\t},\n\t--\t\t\t[3] = {\n\t--\t\t\t\ttime = 1491105600\n\t--\t\t\t}\n\t--\t\t}\n\t--\t}\n\tprint(v)\n\n\to = Serialization.Deserialize( StringFormatProvider(), v, Dictionary[{String, Date}])\n\n\t--\tA\t2013-08-13 12:00:00\n\t--\tB\t2017-04-02 12:00:00\n\t--\tC\t2018-03-14 12:00:00\n\to:Each(print)\nend)\n```\n\n现在，序列化系统可以获知键值的类型，我们也能获得我们所需要的对象。\n\n\n\n\n## Reactive \u0026 Watch\n\nPLoop完整实现了Reactive编程范式，并且类似react和vue提供了一套新的watch观察者系统，用于简化开发方式。\n\n```lua\nrequire \"PLoop\" (function(_ENV)\n    Logger.Default:AddHandler(print)\n\n    -- 申明reactive对象以及字段，基于初始数据决定字段类型\n    data = reactive{\n        x = 3,\n        y = 4,\n        z = 0,\n    }\n\n    -- watch会基于访问订阅data.x和data.y，同时它的计算结果被data.z订阅\n    data.z = watch(function(_ENV) return math.sqrt(data.x ^2 + data.y ^ 2) end)\n\n    -- [Info]Z--\u003e5\n    data.z:Dump(\"Z\")\n\n    -- 修改data.x会触发watch的代码执行，并推送结果给data.z\n    -- [Info]Z--\u003e300.02666548159\n    data.x = 300\n\n    -- [Info]Z--\u003e500\n    data.y = 400\nend)\n```\n\n详情请参考 [021.reactive.md](https://github.com/kurapica/PLoop/blob/master/Docs/021.reactive.md) 和 [026.watch_reactive.md](https://github.com/kurapica/PLoop/blob/master/Docs/026.watch_reactive.md)。\n\n","funding_links":[],"categories":["Lua","Resources"],"sub_categories":["Programming Paradigms"],"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"}