用户工具

站点工具


mudlet:manual

目录

Lua函数手册

以下转从Mudlet4.17版本官方wiki

在这里你可以找到Mudlet提供的所有可能的Lua函数和编程接口(API)的一长串列表。由于集成Lua,您也可以使用所有常规Lua函数。在下一页中,我们将解释Mudlet中添加的函数的用法、预期行为和示例。

全局变量

Mudlet定义了几个全局Lua变量,可以从任何地方访问。

内置Lua变量
变量名 描述
command 此变量保存当前用户命令,即不受任何别名或触发器的影响。这通常用于别名脚本。
line 此变量保存触发器引擎正在处理的当前行的内容。引擎在每一行从游戏到达时运行所有触发器。
matches[n] 这个Lua表由Mudlet在使用Perl正则表达式的触发器上下文中使用。 matches[1]保存整个匹配,matches[2]保存第一个捕获组,matches[n]保存第n-1个捕获组。 如果Perl触发器指示 'matchall'(与Perl /g开关相同的效果)来评估当前行内给定正则表达式的所有可能匹配,matches[n+1]将保存第二个完整匹配,匹配[n+2]第二个匹配的第一个捕获组,并且匹配[n+m]。 第二匹配的第m个捕获组。 从Mudlet 4.11+开始,它将包含命名的捕获组,除了数字组匹配(命名组也算作数字)。每一个都可以在元素下使用与组名相对应的键进行访问。 Eg.如果您捕获了名为target组,则可以通过matches[“target”]或仅通过matches.target访问它。您可以使用mudlet.supports.namedGroups标志来确定是否支持命名组。
multimatches 此表由Mudlet在使用Perl正则表达式的多行触发器的上下文中使用。它保存表matches[n],如上所述,用于多行触发器的每个基于Perl正则表达式的条件。multimatches[5][4]可以保存多行触发器中的第5个正则表达式的第3个捕获组。通过这种方式,您可以在单个脚本中检查和处理所有相关数据。
mudlet.translations 包含一些常见文本的翻译(目前,仅包含退出说明),这些文本对您使用Lua脚本编写有帮助,以及当前为用户界面选择的语言。 - translateTable()
mudlet.keymodifier 与mudlet.key相同,但用于键盘修饰符- Ctrl、Alt等。
mudlet.key 通过Lua将键名翻译成所需的数字,使您在创建新的按键绑定时更轻松-请参阅tempKey()。
mudlet.supports 列出了用户Mudlet支持的特殊功能-现在只列出了mudlet.supports.coroutines mudlet.supports.namedGroups。使用mudlet.supports有条件地启用用户Mudlet上可用的功能。
color_table Geyser、cecho和许多其他函数使用的颜色定义-参见showColors()。配置文件的颜色首选项也可以在ansi_键下访问。

还有其他变量保存游戏的MUD协议数据,这些数据也是全局的-请参阅支持的协议。

功能目录

基本函数:这些函数是普通脚本中使用的通用函数。这些主要处理日常事务,比如发送东西和在屏幕上响应。

数据库函数:帮助处理数据库的函数集合。

日期/时间函数:用于处理日期时间的函数集合。

文件系统函数:用于与文件系统交互的函数集合。

地图相关函数:操作地图及其相关功能的函数集合。

其他功能:其他功能。

网络功能:用于管理网络的功能集合。

字符串函数:这些函数用于操作字符串。

表函数:这些函数用于操作表。通过它们,您可以添加到表中,删除值,检查表中是否存在值,检查表的大小等等。

文本到语音功能:这些功能用于从书面文字中创建声音。查看我们的文本到语音手册,了解更多关于这一切如何协同工作的细节。

用户界面函数:这些函数用于构造自定义用户界面。它们主要处理miniconsole/标签/仪表的创建和操作,以及在屏幕上显示或格式化信息。

Discord功能:这些功能用于自定义Mudlet在Discord丰富的在线界面中显示的信息。有关所有这些函数如何结合在一起的概述,请参阅我们的Discord脚本概述。

此外,Lua 5.1手册中还提供了更高级的功能。

基本函数

这些函数是普通脚本中使用的通用函数。这些主要处理日常事务,比如发送东西和在屏幕上回响。

debugc

命令格式: debugc(content)
同样,这不会将任何东西发送到任何地方。但是,它不会打印到主窗口,而只会打印到错误视图。您需要打开该窗口才能看到消息。

Note注意:请勿使用此选项向最终用户显示信息。很难找到。它主要用于开发/调试。不回显到调试窗口

例子:

debugc(" Trigger successful!") 

display

命令格式: display(content)
这很像echo,它会在你的屏幕上显示文本,而不是向任何地方发送任何东西。但是,它也可以处理文本以外的其他对象,如数字、表格、函数,甚至一次处理多个参数。例如,这个函数对于查看lua表的值很有用。如果一个值是一个字母串,它会被引号包括,如果它是一个数字,则不会。

Note注意:请勿使用此选项向最终用户显示信息。它主要用于开发/调试。

例子:

myTable = {} -- 创建一个空lua表 
myTable.foo = "Hello there" -- 添加文本 
myTable.bar = 23 -- 添加数字  
myTable.ubar = function () echo("OK") end -- 增加函数成员  
display( myTable ) -- 显示lua表 

echo

命令格式:
echo([miniconsoleName or labelName], text)
echo([miniconsoleName或labelName],text)

此函数在当前行的末尾追加文本。

参数:
miniconsoleName:(可选)要回显的miniconsole,或:
labelName:(可选)要回显的标签。
text:您希望打印的文本。您可以在回显中使用\n来插入新行。如果您要将其回显到标签,则还可以使用样式来为文本着色、居中、增大/减小大小以及此处列出的各种其他格式选项。

相关命令: moveCursor()、insertText()、cecho()、decho()、hecho()

例子:

  -- 一个迷你控制台例子 
  -- 首先, 获取窗口大小  
  local windowWidth, windowHeight = getMainWindowSize()  
  -- 创建迷你控制台  
  createMiniConsole("sys", windowWidth-650,0,650,300)  
  setBackgroundColor("sys",255,69,0,255)  
  setMiniConsoleFontSize("sys", 8)   
  -- 设置窗口每行40字符   
  setWindowWrap("sys", 40)  
  echo("sys","Hello world!\n")  
  cecho("sys", "<:OrangeRed>This is random spam with the same background\n")  
  cecho("sys", "<blue:OrangeRed>and this is with a blue foreground. ")   
  cecho("sys", "<bisque:BlueViolet>Lastly, this is with both a foreground and a background.\n")  
-- 标签例子 
-- 创建一个提醒消息标签, 由于半透明(背景透明级别150), 所以可以起到提醒作用 
local width, height = getMainWindowSize()  
createLabel("messageBox",(width/2)-300,(height/2)-100,250,150,1)  
resizeWindow("messageBox",500,70)   
moveWindow("messageBox", (width/2)-300,(height/2)-100 )   
setBackgroundColor("messageBox", 255, 204, 0, 200)   
echo("messageBox", [[<p style="font-size:35px"><b><center><font color="red">You are under attack!</font></center></b></p>]])   

printDebug

命令格式:
printDebug(msg, [showStackTrace])printDebug(msg,[showStackTrace])

仅在脚本编辑器中将调试消息以绿色打印到错误控制台。不回显到调试窗口或主控制台。如果包含了showStackTrace并且不是nil或false,则包含堆栈跟踪。

参数:
msg: 返回到错误控制台的字符串
showStackTrace:(可选)boolean如果要包含堆栈跟踪,则为true;

相关命令:
printError()、debugc()

在Mudlet中可用4.14+

Note注意:即使打开了将Lua错误回显到主控制台的选项,这也不会回显到主控制台。不回显到调试窗口。因此,您可以使用它来调试信息,而不必担心它会显示出来,除非有人去寻找错误。

例子:

-- 打印调试信息, 不显示到主窗口。  
-- 与 debugc 不同, 包含 script/alias/trigger/etc 调用行信息。 
printDebug("Switching to chaos mode")    
-- true 可以包含调用堆栈。 
printDebug("Something unexpected occurred but we can recover from it. Still, we want to be able to notice and troubleshoot it with extra information.", true)   

printError

命令格式:
printError(msg, [showStackTrace], [haltExecution])

在脚本编辑器的错误控制台中以红色打印错误消息。可以选择包含堆栈跟踪信息并停止执行。

参数:
msg: 返回到错误控制台的字符串
showStackTrace:(可选)boolean如果要包含堆栈跟踪,则为true;
haltExecution: (可选)如果要停止执行,则为true。必须为showStackTrace传递一个值才能停止执行。

在Mudlet中可用4.14+

Note注意:如果打开了将Lua错误回显到主控制台的选项,这将回显到主控制台。您不应该将其用于空闲的调试信息,而应该用于可能在主窗口中显示大红色错误行的实际错误。

相关命令:
printDebug()、debugc()

例子:

    printError("Your maxhp is below your currenthp and our game doesn't allow for that.  HAX?!") 
    printError("gmcp values for this thing went missing, will carry on using defaults but you should tell somebody about this.", true) 
    printError("Our entire configuration seems to have gone missing!", true, true) 

send

命令格式:
send(command, showOnScreen)send(command,showOnScreen)
这将“命令”直接发送到网络层,跳过别名匹配。第二个可选的boolean(print)类型的参数决定了输出命令是否在屏幕上回显。

Note注意:如果你想让你的命令像别名一样被检查,使用expandAlias()代替- send()将忽略它们。

相关命令:
sendAll()、speedwalk()

例子:

send("Hello Jane") --echos the command on the screen 
send("Hello Jane", true) --echos the command on the screen 
send("Hello Jane", false) --does not echo the command on the screen 
-- use a variable in the send: 
send("kick "..target) 
-- to send directions: 
speedwalk("s;s;w;w;w;w;w;w;w;") 
-- to send many things: 
sendAll("hi", "open door e", "e", "get item", "sit") 

Note注意:游戏服务器可以选择不在屏幕上显示发送的命令(例如,如果您正在输入密码)。

数据库函数

这些数据库函数使使用Mudlet的数据库更容易。它们是对直接在Mudlet中可用的LuaSQL sqlite驱动程序的补充(也可以参见LuaSQL手册进行比较)。

db:add

命令格式:
db:add(sheet reference, table1, …, tableN)

将一个或多个新行添加到指定的工作表中。如果这些行中的任何一行违反了UNIQUE索引,则会抛出lua错误并取消执行。因此,如果使用UNIQUE索引,建议在尝试插入新行之前测试这些值。

返回 空
如果操作失败,则加上错误消息(因此它不会在Mudlet中引发运行时错误)。

例子:

-- 多行记录, 未设置的key值为空 
db:add(mydb.enemies, {name="Bob Smith", city="San Francisco"}) 
db:add(mydb.enemies,  
     {name="John Smith", city="San Francisco"}, 
     {name="Jane Smith", city="San Francisco"}, 
     {name="Richard Clark"}) 
-- 上面city字段是可选的 
-- 操作失败处理  
  local ok, err = db:add(mydb.enemies, {name="Bob Smith", city="San Francisco"}) 
  if not ok then 
    debugc(f"Error adding to the database: {err}") 
    return 
  end 

db:aggregate

命令格式:
db:aggregate(field reference, aggregate function, query, distinct)

返回对字段及其工作表调用指定聚合函数的结果。查询是可选的。

支持的聚合函数包括:
COUNT -返回工作表中或与查询匹配的记录总数。
AVG -返回指定字段中所有数字的平均值。
MAX -返回指定字段中的最大数字。
MIN -返回指定字段中的最小数字。
TOTAL -返回将指定字段的所有内容相加所得的值。

Note注意:从Mudlet 3.0开始,您可以为distinct参数提供布尔值true,以按distinct值进行过滤。

例子:

local mydb = db:get_database("my database")
echo(db:aggregate(mydb.enemies.name, "count"))

它还可以与db:like结合使用,以返回许多结果。

local query = matches[2]
local mydb = db:get_database("itemsdab")
local results = db:aggregate(mydb.itemstats.objname, "count", db:like(mydb.itemstats.objname, "%" .. query .. "%"))
cecho("Found <red>"..results.."<reset> items that match the description.")

db:AND

命令格式:
db:AND(sub-expression1, …, sub-expressionN)
返回一个复合数据库表达式,该表达式组合了传入其中的所有简单表达式;这些表达式应该用其他数据库生成:等功能 db:eq, db:like, db:lt 之类的
此复合表达式仅在所有子表达式匹配时查找工作表中的项。

db:between

命令格式:
db:between(field reference, lower_bound, upper_bound)

返回一个数据库表达式以测试工作表中的字段是否是介于lower_bound和upper_bound之间的值。这只适用于数字和时间戳。

db:close

命令格式:
db:close(database name)
关闭数据库连接,使其无法再使用。

db:create

命令格式:
db:create(database name, schema table, force)
创建和/或修改现有数据库。在Mudlet脚本的顶层定义此函数是安全的:事实上,建议您在没有任何保护的情况下在顶级运行此函数。如果命名的数据库不存在,它将创建它。如果数据库确实存在,那么它将添加以前不存在的任何列或索引到该数据库中。如果数据库已经有了所有指定的列和索引,它将不做任何事情。如果新架构中缺少至少一个非NULL值的现有列,则默认情况下将引发错误;用户可以通过将强制变元设置为真来强制删除该列。

例子:

local mydb = db:create("combat_log",
  {
    kills = {
              name = "",
              area = "",
              killed = db:Timestamp("CURRENT_TIMESTAMP"),
              damage = 0,
              _index = { {"name", "area"} }
            },
    enemies = {
                name = "",
                city = "",
                reason = "",
                enemied = db:Timestamp("CURRENT_TIMESTAMP"),
                _index = { "city" },
                _unique = { "name" },
                _violations = "IGNORE"
               }
  })

上面将创建一个有两张表的数据库;第一个是kills,用于跟踪每次成功的kills,以及kills发生的地点和时间。它有一个索引,一个跟踪名称和地区组合的复合索引。第二个工作表有两个索引,但其中一个是唯一的:不可能在敌人表中添加两个同名的物品。

对于具有唯一索引的工作表,可以指定key值,指示DB层如何处理数据重复(违反了唯一索引)的情况。您可以使用的选项包括:
FAIL-默认值。抛出硬错误,取消脚本。
IGNORE-添加违反唯一性的记录的命令只是悄无声息地失败。
REPLACE-删除与唯一索引匹配的旧记录,并添加新记录来替换它。

返回已存在数据库的引用。此实例可用于获取对数据库中定义的工作表(以及从那里获取字段)的引用。您可以使用这些引用构造查询。
如果数据库中有一个名为“敌人”的工作表,则可以通过执行以下操作来获取对该工作表的引用:

local mydb = db:get_database("my database")
local enemies_ref = mydb.enemieslocal
local name_ref = mydb.enemies.name

Note注意:db:create()支持向现有数据库添加新的列和索引已经过时,Mudlet2.1中该功能被删除了。如果要添加新列,需要:
如果您只是在测试和获取安装程序,请关闭Mudlet,并删除Mudlet文件夹中的Database_sanitized数据库名称.db文件。
如果您已经获得了一个脚本且其中有相当数量数据,或者用户已经在使用您的脚本并且告诉他们在升级时删除文件是不合理的,则可以使用SQL语句添加新列。警告,这是一个专家选项,需要SQL知识才能完成。在开始编写此代码之前,必须备份数据库文件。

-- at first, update your db:create schema to have the new field.
  -- then, we'll tell the database to create it if it doesn't exist

  -- fetch the data we've got in our sample database
  local test = db:fetch(ndb.db.people)
  -- this requires at least one entry in the database to work
  if next(test) then
    local _,someperson = next(test)
    
    -- in this example, we want to add an order key. If there is no key, means it doesn't exist yet, so it should be added.
    if someperson.order == nil then
      -- do not do the things you see here elsewhere else. This is a big hack/workaround.
      local conn = db.__conn.namedb
      -- order should be a text field, so note that we specify it's type with TEXT and the default value at the end with ""
      local sql_add = [[ALTER TABLE people ADD COLUMN "order" TEXT NULL DEFAULT ""]]
      conn:execute(sql_add)
      conn:commit()
    end

    -- here is an another example, in one where we need to add a field that is a number
    if someperson.dragon == nil then
      local conn = db.__conn.namedb
      -- observe that we use the REAL type by default instead and a default of 0
      local sql_add = [[ALTER TABLE people ADD COLUMN "dragon" REAL NULL DEFAULT 0]]
      conn:execute(sql_add)
      conn:commit()
    end
  end

db:delete

命令格式:
db:delete(sheet reference, query)
从指定工作表中删除行。query的参数试图是智能的:
如果是简单的数字,它会通过_row_id删除特定的行
如果它是包含a _row_id的表(例如,由db:get返回的表),则只删除该记录。
否则,它会删除与B:get指定的查询模式匹配的所有记录。
如果查询简单地为true,那么它将截断工作表的整个内容。

例子:
当传递一个从db:fetch获得的实际结果表时,它将删除该表的记录。

enemies = db:fetch(mydb.enemies)
db:delete(mydb.enemies, enemies[1])

当传递一个数字时,将删除that _row_id的记录。此示例演示如何从表中获取行ID。

db:delete(mydb.enemies, enemies[1]._row_id)

和上面效果一样,这个例子直接传入行id。

db:delete(mydb.enemies, 5)

在这里,我们将删除与db:fetch使用的查询类型相同的任何内容,也就是说,任何在弗朗西斯科市的人。

db:delete(mydb.enemies, db:eq(mydb.enemies.city, "San Francisco"))

最后,我们将删除敌人表的全部内容。

db:delete(mydb.enemies, true)

db:eq

命令格式:
db:eq(field reference, value)
返回数据库表达式以测试工作表中的字段是否等于值。

db:exp

命令格式:
db:exp(string)
将字符串按原样返回到数据库。
请谨慎使用此函数,但在某些情况下它非常有用。其中最常见的一种是在db:set()操作中递增现有字段,如下所示:

db:set(mydb.enemies, db:exp("kills + 1"), db:eq(mydb.enemies.name, "Ixokai"))

这将增加由名称Ixokai标识的行的kills字段的值。
但还有其他用途,因为下划线的数据库层提供了许多函数,您可以调用这些函数来完成某些事情。如果你想得到一个名字超过10个字符的所有敌人的列表,你可以这样做:

db:fetch(mydb.enemies, db:exp("length(name) > 10"))

同样,要特别注意这一点,因为您直接使用SQL语法,库不能帮助您正确处理。

db:fetch

命令格式:
db:fetch(sheet reference, query, order_by, descending)
返回一个表数组,其中包含指定工作表中每个匹配行的表。除sheet外的所有参数都是可选的。如果query为nil,则返回工作表的全部内容。
Query是一个字符串,应该通过调用各种db来构建:表达式函数,如db:eq、db:AND等。如果您愿意,可以在这里传递SQL WHERE子句,但这样做是非常危险的。如果你不太了解SQL,最好是构建表达式。
查询也可以是这样的表达式的表数组,如果是这样,它们将被隐式地AND。
返回的结果没有任何保证的顺序,尽管它们通常与插入记录的顺序相同。如果您想以任何方式依赖订单,您必须向order_by 排序字段。它可以是{ mydb.kills.area }或{ mydb.kills.area,mydb.kills.name}
结果按升序返回; 如果需要降序, 最后一个参数传true。

例子:
第一个会抓住你所有的敌人,首先按他们居住的城市排序,然后按他们的名字排序。

db:fetch(mydb.enemies, nil, {mydb.enemies.city, mydb.enemies.name})

第二个只会抓到弗朗西斯科的敌人。

db:fetch(mydb.enemies, db:eq(mydb.enemies.city, "San Francisco"))

第三个会把你在地下室杀死的所有以卓尔为名的东西都取到。

db:fetch(mydb.kills,
     {db:eq(mydb.kills.area, "Undervault"),
     db:like(mydb.kills.name, "%Drow%")}
)

db:fetch_sql

命令格式:
db:fetch_sql(sheet reference, sql string)
允许使用手工创建的SQL语句运行db:fetch。
当数据库中有大量对象时,可能需要另一种方法来访问它们。在这种情况下,您可以首先获取与查询匹配的对象的_row_id列表,该列表具有以下别名:
例子:

local mydb = db:get_database("itemsdab")
local query = matches[2]
local t = {}
res = db:fetch(mydb.itemstats, db:query_by_example(mydb.itemstats, {objname = "%" .. query .. "%"}))
for k, v in pairs(res) do
  print(v._row_id)
  table.insert(t,v._row_id)
end
handoff = table.concat(t, "|")
display(handoff)

然后,您可以在单独的别名中使用以下代码,使用先前检索的_row_id查询数据库。

local mydb = db:get_database("itemsdab")
local query = matches[2]
display(db:fetch_sql(mydb.itemstats, "select * from itemstats where _row_id ="..query))
--This alias is used to query a database by _row_id

db:gt

命令格式:
db:gt(field reference, value)

db:get_database

命令格式:
db:get_database(database_name)
获取数据库。
例子:

local mydb = db:get_database("my database")

db:gte

命令格式:
db:gte(field reference, value)

db:in_

命令格式:
db:in_(field reference, table array)
仔细注意后面的下划线!这是必需的。
例子:

local mydb = db:get_database("my database")
local areas = {"Undervault", "Hell", "Purgatory"}
db:fetch(mydb.kills, db:in_(mydb.kills.area, areas))

这将获得你在地下室,地狱或炼狱中的所有杀戮。每个db:in_ expression都可以写成db:OR,但这通常会变得非常复杂。

db:is_nil

命令格式:
db:is_nil(field reference)
判断字段是否为nil

db:is_not_nil

命令格式:
db:is_not_nil(field reference)
判断字段是否为非空

db:like

命令格式:
db:like(field reference, pattern)
LIKE模式不区分大小写,允许使用两个通配符。第一个是匹配任何单个字符的下划线“_”。第二个是一个百分号“%”,它匹配零个或多个任意字符。

db:lt

命令格式:
db:lt(field reference, value)

db:lte

命令格式:
db:lte(field reference, value)

db:merge_unique

命令格式:
db:merge_unique(sheet reference, table array)
将指定的表数组合并到工作表中,修改所有现有行并添加任何不存在的行。
例子:

local mydb = db:create("peopledb",
     {
          friends = {
               name = "",
               race = "",
               level = 0,
               city = "",
               _index = { "city" },
               _unique = { "name" }
          }
);

这里有一个数据库,其中包含了你的朋友,他们的种族,等级和他们居住的城市。假设你想把住在弗朗西斯科的每个人都找来,你可以这样做:

local results = db:fetch(mydb.friends, db:eq(mydb.friends.city, "San Francisco"))

结果中的表是静态的,对它们的任何更改都不会保存回数据库。但是,在一场大规模的放射性灾难使弗朗西斯科的每个人都变成了突变体之后,你可以这样对表格进行修改:

for _, friend in ipairs(results) do
     friend.race = "Mutant"
end

如果你现在也知道弗朗西斯科有新的人,你可以把它们添加到现有的表数组中:

results[#results+1] = {name="Bobette", race="Mutant", city="San Francisco"}

并使用以下命令将所有更改立即提交回数据库:

db:merge_unique(mydb.friends, results)

db:not_between

命令格式:
db:not_between(field reference, lower_bound, upper_bound)

db:not_eq

命令格式:
db:not_eq(field reference, value)

db:not_in

命令格式:
db:not_in(field reference, table array)

db:not_like

命令格式:
db:not_like(field reference, pattern)

db:OR

命令格式:
db:OR(sub-expression1, sub-expression2)

db:query_by_example

命令格式:
db:query_by_example(sheet reference, example table)
按例子匹配, 可用通配符
例子:

mydb = db:create("mydb",
{
  sheet = {
  name = "", id = 0, city = "",
  _index = { "name" },
  _unique = { "id" },
  _violations = "FAIL"
  }
})
test_data = {
  {name="Ixokai", city="Magnagora", id=1},
  {name="Vadi", city="New Celest", id=2},
  {name="Heiko", city="Hallifax", id=3},
  {name="Keneanung", city="Hashan", id=4},
  {name="Carmain", city="Mhaldor", id=5},
  {name="Ixokai", city="Hallifax", id=6},
}
db:add(mydb.sheet, unpack(test_data))
res = db:fetch(mydb.sheet, db:query_by_example(mydb.sheet, { name = "Ixokai"}))
display(res)
--[[
Prints
{
  {
    id = 1,
    name = "Ixokai",
    city = "Magnagora"
  },
  {
    id = 6,
    name = "Ixokai",
    city = "Hallifax"
  }
}
--]]

mydb = db:create("mydb",
  {
    sheet = {
    name = "", id = 0, city = "",
    _index = { "name" },
    _unique = { "id" },
    _violations = "FAIL"
    }
  })
test_data = {
  {name="Ixokai", city="Magnagora", id=1},
  {name="Vadi", city="New Celest", id=2},
  {name="Heiko", city="Hallifax", id=3},
  {name="Keneanung", city="Hashan", id=4},
  {name="Carmain", city="Mhaldor", id=5},
  {name="Ixokai", city="Hallifax", id=6},
}
db:add(mydb.sheet, unpack(test_data))
res = db:fetch(mydb.sheet, db:query_by_example(mydb.sheet, { name = "Ixokai", id = "1"}))
display(res)
--[[
  Prints
  {
    id = 1,
    name = "Ixokai",
    city = "Magnagora"
  }
--]]

db:Timestamp

命令格式:
db:Timestamp(time)

db:Null

命令格式:
db:Null()

db:safe_name

命令格式:
db:safe_name(string)
从输入字符串中删除所有非字母数字字符。主要用于格式化数据库名称。

db:set

命令格式:
db:set(field reference, value, query)
设置值
例子:

local mydb = db:create("egg database", {eggs = {color = "", last_found = db.Timestamp(false), found = 0}})
        db:add(mydb.eggs,
                {color = "Red"},
                {color = "Blue"},
                {color = "Green"},
                {color = "Yellow"},
                {color = "Black"}
        )
myegg = "Red" -- We will pretend a trigger set this.
        db:set(mydb.eggs.found, db:exp("found + 1"), db:eq(mydb.eggs.color, myegg))
        db:set(mydb.eggs.last_found, db.Timestamp("CURRENT_TIMESTAMP"), db:eq(mydb.eggs.color, myegg))
db:set(mydb.eggs.found, 0)
db:set(mydb.eggs.last_found, nil)

db:update

命令格式:
db:update(sheet reference, table)
此函数更新指定工作表中的一行,但只接受先前由db:fetch获取的一行。它的主要用途是,如果你执行db:fetch,然后更改一个字段或tow的值,你可以保存回那个表。

local mydb = db:get_database("my database")
local bob = db:fetch(mydb.friends, db:eq(mydb.friends.name, "Bob"))[1]
bob.notes = "He's a really awesome guy."
db:update(mydb.friends, bob)

db:_sql_convert

命令格式:
db:_sql_convert(value)
将Lua中的数据值转换SQL格式;值得注意的是,它还将转义单引号,以防止SQL注入。此外,它会将带有_timestamp键的Lua表转换为适当的时间(可能是CURRENT_TIMESTAMP),并将带有_isNull键的Lua表转换为NULL SQL关键字。

db:_sql_values

命令格式:
db:_sql_values(values)
这将在SQL列表中传递给INSERT或UPDATE操作的值加引号。也就是说,它将{x=“this”,y=“that”,z=1}转换为('this','that',1)。它是智能的数据类型;字符串被自动加引号(内部单引号转义),nil转换为NULL,时间戳转换为整数,等等。

db:_sql_values

命令格式:
db:_sql_values(values)
这将在SQL列表中传递给INSERT或UPDATE操作的值加引号。也就是说,它将{x=“this”,y=“that”,z=1}转换为('this','that',1)。它是智能的数据类型;字符串被自动加引号(内部单引号转义),nil转换为NULL,时间戳转换为整数,等等。

事务相关命令

这些函数便于使用数据库中的事务。这在大多数情况下可以安全地忽略,但在特定情况下可以提供有用的功能。事务允许在稍后接受或拒绝批处理更改集。请记住,事务会影响整个数据库。

db:_begin

命令格式:
db:_begin()
此函数暂停数据库的所有自动磁盘写入。当通过多个函数调用运行大型或频繁(每秒多次)的数据库编辑时,这尤其有用,以防止Mudlet冻结或抖动。在事务中已经存在的数据库上调用此函数不会产生任何效果,但也不会产生错误。
例子:

local mydb = db:get_database("my_database")
mydb:_begin()
-- do other things as needed

db:_commit

命令格式:
db:_commit()
此函数强制数据库将所有更改保存到磁盘上,从而在进程中开始一个新的事务。
例子:

local mydb = db:get_database("my_database")
mydb:_begin()
-- do other things as needed
mydb:_commit()

db:_end

命令格式:
db:_end()
此函数重新启用数据库的自动磁盘写入。它不会自行提交对磁盘的更改,也不会结束当前事务。使用db:_commit()或任何在此之后写入更改的数据库函数将事务保存到磁盘。在此之前再次使用db:_begin将继续上一个事务,而不向磁盘写入任何内容。
例子:

local mydb = db:get_database("my_database")
mydb:_end()

db:_rollback

命令格式:
db:_rollback()
此函数将丢弃在当前事务期间发生的所有更改,并开始新的事务。使用此函数不会切换数据库的自动写入状态。
例子:

local mydb = db:get_database("my_database")
mydb:_begin()
-- do other things as needed
mydb:_rollback()

日期和时间函数

用于处理日期时间的函数集合。

datetime:parse

命令格式:
datetime:parse(source, format, as_epoch)
根据格式(如果给定)分析指定的源字符串,以返回日期/时间的表示形式。如果提供了as_epoch并且为true,则返回值将是Unix epoch-自1970年以来的秒数。  这是与其他系统交换日期/时间的有用格式。如果as_epoch为false,则返回Lua时间表。有关时间表的详情载于Lua手册。

支持的格式代码
%b = Abbreviated Month Name
%B = Full Month Name
%d = 天
%H = 24小时制 (00-23)
%I = 12小时制 (00-12, 需要 %p)
%p = 上下午 AM or PM
%m = 2位 月份 (01-12)
%M = 分钟 (00-59)
%S = 秒 (00-59)
%y = 2位年 (00-99), 自动添加20开头
%Y = 4位年

例子:

local mydb = db:get_database("my_database")
mydb:_begin()
-- do other things as needed
mydb:_rollback()

getEpoch

命令格式:
seconds = getEpoch()
此函数返回自 Unix epoch 毫秒数。
例子:

getEpoch() -- 显示类似 1523555867.191

getTime

命令格式:
time = getTime([return as string, [custom time format]])
“return as string”是一个布尔值(在Lua中,除了false或nil之外的任何值都将转换为true)。如果为false,则函数将返回一个格式如下的表:

{ 'min': #, 'year': #, 'month': #, 'day': #, 'sec': #, 'hour': #, 'msec': # }

如果为true,它将使用传递给“customtime format”参数的格式返回日期和时间作为字符串,或者如果没有提供,则默认值为“yyyy.MM.dd hh:mm:ss.zzz”:

设置表达式的格式:

h               the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
hh              the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
H               the hour without a leading zero (0 to 23, even with AM/PM display)
HH              the hour with a leading zero (00 to 23, even with AM/PM display)
m               the minute without a leading zero (0 to 59)
mm              the minute with a leading zero (00 to 59)
s               the second without a leading zero (0 to 59)
ss              the second with a leading zero (00 to 59)
z               the milliseconds without leading zeroes (0 to 999)
zzz             the milliseconds with leading zeroes (000 to 999)
AP or A         use AM/PM display. AP will be replaced by either "AM" or "PM".
ap or a         use am/pm display. ap will be replaced by either "am" or "pm".

d               the day as number without a leading zero (1 to 31)
dd              the day as number with a leading zero (01 to 31)
ddd             the abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses QDate::shortDayName().
dddd            the long localized day name (e.g. 'Monday' to 'Qt::Sunday'). Uses QDate::longDayName().
M               the month as number without a leading zero (1-12)
MM              the month as number with a leading zero (01-12)
MMM             the abbreviated localized month name (e.g. 'Jan' to 'Dec'). Uses QDate::shortMonthName().
MMMM            the long localized month name (e.g. 'January' to 'December'). Uses QDate::longMonthName().
yy              the year as two digit number (00-99)
yyyy            the year as four digit number

例子:

-- Get time as a table
getTime()

-- Get time with default string
getTime(true)

-- Get time without date and milliseconds
getTime(true, "hh:mm:ss")

getTimestamp

命令格式:
time = getTimestamp([console_name], lineNumber)
返回当启用timestamps视图时看到的timestamps字符串(蓝色i按钮右下角)。
例子:

-- echo the timestamp of the current line in a trigger:
echo(getTimestamp(getLineCount()))

-- insert the timestamp into a "chat" miniconsole
cecho("chat", "<red>"..getTimestamp(getLineCount()))

shms

命令格式:
shms(seconds, bool)
将秒转换为小时、分钟和秒,并将结果显示为表格。可以传递一个可选的第二个参数以返回结果。

Mudlet在Mudlet中可用3.0+

例子:

--Determine the total number of seconds and display:
shms(65535, true)

文件系统功能

用于与文件系统交互的函数集合。

io.exists

命令格式:
io.exists(path)
检查给定的文件或文件夹是否存在。返回布尔值

例子:

-- Linux 例子
if io.exists("/home/vadi/Desktop") then
  echo("This folder exists!")
else
  echo("This folder doesn't exist.")
end

-- Linux/Windows例子.
if io.exists("/home/vadi/Desktop/file.tx") then
  echo("This file exists!")
else
  echo("This file doesn't exist.")
end

lfs.attributes

命令格式:
infoTable = lfs.attributes(path)
返回一个包含文件或目录详细信息的表,如果路径无效/文件或文件夹不存在,则返回nil。

Mudlet在Mudlet中可用3.0+

例子:

fileInfo = lfs.attributes("/path/to/file_or_directory")
if fileInfo then
    if fileInfo.mode == "directory" then
        echo("Path points to a directory.")
    elseif fileInfo.mode == "file" then
        echo("Path points to a file.")
    else
        echo("Path points to: "..fileInfo.mode)
    end
    display(fileInfo) -- to see the detailed information
else
    echo("The path is invalid (file/directory doesn't exist)")
end

地图相关函数

这些是将与Mudlet地图一起使用的函数。地图被设计为通用的-它只提供显示和路径计算,用于根据您正在玩的游戏量身定制的Lua脚本。有关预先制作的脚本和常规小地图讨论的集合,请访问论坛的地图相关部分。

要将脚本注册为Mudlet的地图脚本(这样Mudlet就知道配置文件中有一个,并且当用户打开小地图时不会打扰用户),请在脚本中这样做:

mudlet = mudlet or {}; mudlet.mapper_script = true

addAreaName

命令格式:
areaID = addAreaName(areaName)
添加新区域名称并返回新名称的新(正)区域ID。如果该名称已经存在,则旧版本的Mudlet返回-1,尽管从3.0开始代码将返回 nil and an error message. 和错误消息。

例子:

local newId, err = addAreaName(string.random(10))

if newId == nil or newId < 1 or err then
  echo("That area name could not be added - error is: ".. err.."\n")
else
  cecho("<green>Created new area with the ID of "..newId..".\n")
end

addCustomLine

命令格式:
addCustomLine(roomID, id_to, direction, style, color, arrow)
将新的/替换现有的自定义退出线添加到具有给定ID的房间的二维地图中。
参数: roomID: 自定义的房间ID。 id_to: 可以是房间ID号,同一区域上的房间的x和y坐标被用作SINGLE段自定义线的另一端(它并不意味着它表示的出口去哪里,只是线的末端的位置);
也可以是地图坐标(x,y and z),x和y可以是小数,z是整数(并且必须存在并且对于线上的所有点都是相同的, 尽管它与产生的内容无关,因为线是在与线所附房间相同的z坐标上绘制的!)

direction:一个字符串,用于将行与有效的退出方向、“n”、“ne”、“e”、“se”、“s”、“sw”、“w”、“nw”、“up”、“down”、“in”或“out”或特殊退出相关联(在Mudlet 3.17之前,这是区分大小写的,基本方向必须是大写的)。

style:一个字符串,其中之一:“实线”、“点线”、“虚线”、“虚线”或“虚线点线”。

color:由0到255之间的三个整数组成的表格,作为自定义线条颜色,依次为红、绿色、蓝分量。

arrow:一个布尔值,如果为true,则将自定义行设置为在最后一段的末尾有一个箭头。

在Mudlet中可用3.0+

例子:

-- create a line from roomid 1 to roomid 2
addCustomLine(1, 2, "N", "dot line", {0, 255, 255}, true)

addCustomLine(1, {{4.5, 5.5, 3}, {4.5, 9.5, 3}, {6.0, 9.5, 3}}, "climb Rope", "dash dot dot line", {128, 128, 0}, false)

一个更全的例子,将创建一个新的区域和其中的房间:

local areaid = addAreaName("my first area")
local newroomid = createRoomID()
addRoom(newroomid)
setRoomArea(newroomid, "my first area")
setRoomCoordinates(newroomid, 0, 0, 0)

local otherroomid = createRoomID()
addRoom(otherroomid)
setRoomArea(otherroomid, "my first area")
setRoomCoordinates(otherroomid, 0, 5, 0)

addSpecialExit(newroomid, otherroomid, "climb Rope")
addCustomLine(newroomid, {{4.5, 5.5, 3}, {4.5, 9.5, 3}, {6.0, 9.5, 3}}, "climb Rope", "dash dot dot line", {128, 128, 0}, false)

centerview(newroomid)

addMapEvent

命令格式:
addMapEvent(uniquename, event name, parent, display name, arguments)
将新条目添加到现有小地图右键单击条目中。您可以使用addMapMenu添加一个。如果没有显示名称,它将默认为唯一名称(否则不会显示,只是用来区分此条目)。 单击此选项时将调用的Mudlet事件,以及将被传递给handler函数。

例子:

addMapEvent("room a", "onFavorite") -- 点击调用onFavorite

-- 做一个标签“特别的房间!“收藏夹”菜单下,单击该选项将引发一个包含所有参数的事件。
addMapEvent("room b", "onFavorite", "Favorites", "Special Room!", 12345, "arg1", "arg2", "argn")

此创建菜单和两个子菜单选项:“将选定房间标记为死亡陷阱”和“将选定房间标记为单向通过”

addMapMenu("Room type")
addMapEvent("markRoomsAsDeathTrap", "onMapMarkSelectedRooms", "Room type", "Mark selected rooms as Death Trap")
addMapEvent("markRoomsAsOneRoom", "onMapMarkSelectedRooms", "Room type", "Mark selected rooms as single-pass")

function onMapMarkSelectedRooms(event, markRoomType)
  local selectedRooms = getMapSelection()["rooms"]
  for i, val in ipairs(selectedRooms) do
    if markRoomType == "markRoomsAsDeathTrap" then
      local r, g, b = unpack(color_table.black)
      --death trap
      setRoomEnv(val, 300)
      --death traps Env
      setCustomEnvColor(300, r, g, b, 255)
      setRoomChar(val, "☠️")
      lockRoom(val, true)
    elseif markRoomType == "markRoomsAsOneRoom" then
      local r, g, b = unpack(color_table.LightCoral)
      --single-pass
      setRoomEnv(val, 301)
      --one room Env
      setCustomEnvColor(301, r, g, b, 255)
      setRoomChar(val, "🚹")
    end
  end
  updateMap()
end

registerAnonymousEventHandler("onMapMarkSelectedRooms", "onMapMarkSelectedRooms")

addMapMenu

命令格式:
addMapMenu(uniquename, parent, display name)
将新子菜单添加到右键单击小地图时打开的右键单击菜单中。然后,您可以向它添加更多子菜单,或添加条目 addMapEvent()。

例子:

addMapMenu("Favorites")
addMapMenu("Favorites1234343", "Favorites", "More Favorites")

addRoom

命令格式:
addRoom(roomID)
使用给定ID创建新房间,如果成功创建房间,则返回true。

Note注意:如果你没有使用增量房间ID,而是使用其他因素拼接在一起的房间ID或者游戏内的散列作为房间ID-并且你的房间ID开始时有超过9位的数字,你需要考虑使用createRoomID()增量创建Mudlets房间ID,并通过setRoomIDbyHash()和getRoomIDbyHash()将你的房间ID与Mudlets关联。原因是boost的Mudlet的A* 寻路实现无法处理非常大的房间ID,因为它为寻路创建的结果矩阵非常巨大。

例子:

local newroomid = createRoomID()
addRoom(newroomid)

addSpecialExit

命令格式:
addSpecialExit(roomIDFrom, roomIDTo, moveCommand)
创建从一个房间到另一个房间的单向通道,将使用给定的命令通过它们。

Note注意:如果你没有使用增量房间ID,而是使用其他因素拼接在一起的房间ID或者游戏内的散列作为房间ID-并且你的房间ID开始时有超过9位的数字,你需要考虑使用createRoomID()增量创建Mudlets房间ID,并通过setRoomIDbyHash()和getRoomIDbyHash()将你的房间ID与Mudlets关联。原因是boost的Mudlet的A* 寻路实现无法处理非常大的房间ID,因为它为寻路创建的结果矩阵非常巨大。

例子:

-- add 使用命令 'pull rope' 单向行走1到2房间
addSpecialExit(1, 2, "pull rope")

-- 别名中的示例:
addSpecialExit(currentroom,tonumber(matches[2]), matches[3])
echo("\n SPECIAL EXIT ADDED TO ROOMID:"..matches[2]..", Command:"..matches[3])
centerview(currentroom)

addRoom

命令格式:
addRoom(roomID)
使用给定ID创建新房间,如果成功创建房间,则返回true。

Note注意:如果你没有使用增量房间ID,而是使用其他因素拼接在一起的房间ID或者游戏内的散列作为房间ID-并且你的房间ID开始时有超过9位的数字,你需要考虑使用createRoomID()增量创建Mudlets房间ID,并通过setRoomIDbyHash()和getRoomIDbyHash()将你的房间ID与Mudlets关联。原因是boost的Mudlet的A* 寻路实现无法处理非常大的房间ID,因为它为寻路创建的结果矩阵非常巨大。

例子:

local newroomid = createRoomID()
addRoom(newroomid)

auditAreas

命令格式:
auditAreas()
启动整个地图的一致性检查:所有房间、区域及其构成。当你第一次打开地图时,这也是自动完成的,所以可能很少需要手动完成。将结果输出至屏幕和/或日志文件,以供以后审查。

centerview

命令格式:
auditAreas()
将地图视图居中到给定的房间ID上。必须打开地图才能看到此生效。如果您知道某个区域的房间数量,并且该区域和房间都已完成,则此功能也可用于查看该区域的地图。

clearAreaUserData

命令格式:
clearAreaUserData(areaID)
清除给定区域中的所有用户数据。请注意,这不会触及房间用户数据。

clearAreaUserDataItem

命令格式:
clearAreaUserDataItem(areaID, key)
从给定区域中的用户数据中移除特定键和值。

clearMapSelection

命令格式:
clearMapSelection()
从地图中清除任何选定房间(即它们以橙色突出显示)。

clearMapUserData

命令格式:
clearMapUserData()
清除为地图本身存储的所有用户数据。请注意,这不会触及区域或房间用户数据。

clearMapUserDataItem

命令格式:
clearMapUserDataItem(mapID, key)
从地图用户数据中移除用户数据中的特定键和值。

clearRoomUserData

命令格式:
clearRoomUserData(roomID)
清除给定房间中的所有用户数据。

clearRoomUserDataItem

命令格式:
clearRoomUserDataItem(roomID, key)
从给定房间的用户数据中移除特定键和值。
在Mudlet中可用3.0+

clearSpecialExits

命令格式:
clearSpecialExits(roomID)
删除房间中的所有特殊出口。

clearSpecialExits(1337)

if #getSpecialExits(1337) == 0 then 
  echo("All special exits successfully cleared from 1337.\n")
end

closeMapWidget

命令格式:
closeMapWidget()
关闭(隐藏)地图窗口(类似于单击地图图标)

connectExitStub

命令格式:
connectExitStub(fromID, direction)
connectExitStub(fromID, toID, [direction])
用匹配的出口存根连接现有房间。如果你只给予它一个roomID和一个方向,它会计算出哪个房间应该链接到它,哪个房间有一个合适的相反的出口存根,并且位于正确的方向。您也可以只指定from和to房间ID,它将巧妙地使用正确的方向链接。最后,您可以指定所有三个参数- fromID、toID和方向(按此顺序)(如果您希望显式),或者使用 setExit()setExit() for the same effect. 同样的效果。

参数: fromID: 要在其中设置退出存根的房间ID。 direction: 您可以指定链接房间的方向和/或特定房间ID(请参见下文)。方向可以指定为数字、短方向名称(“nw”)或长方向名称(“northwest”)。 toID: 要将此房间链接到的房间ID。如果不指定,将计算出应该逻辑链接哪个房间。

例子:

-- try and connect all stubs that are in a room
local stubs = getExitStubs(roomID)
if stubs then
  for i,v in pairs(stubs) do
    connectExitStub(roomID, v)
  end
end

createMapLabel

命令格式:
labelID = createMapLabel(areaID, text, posX, posY, posZ, fgRed, fgGreen, fgBlue, bgRed, bgGreen, bgBlue[, zoom, fontSize, showOnTop, noScaling, fontName, foregroundTransparency, backgroundTransparency, temporary])
在地图上以给定的坐标创建文本标签,并使用给定的背景色和前景色。它可以在房间的上方或下方,缩放或保持静态大小。从Mudlet 4.17.0开始,一个附加参数(如果没有给出,则假定为false)使标签不保存在地图文件中,如果图像可以在将来从脚本加载时重新生成,则可以稍微减少保存的地图的大小。它返回一个标签ID,您可以在以后删除它。

参数:
areaID: 放置标签的区域ID。

  text: 要放入标签中的文本。要获取多行文本标签,在行之间添加“\n”。
  posX, posY, posZ: 标签在房间坐标(浮点数)中的位置。
  fgRed, fgGreen, fgBlue: 标签的前景颜色或文本颜色。
  bgRed, bgGreen, bgBlue: 标签的背景颜色。
  zoom:  (可选)如果noScaling为false,则标签的缩放因子。更高的缩放将给予更高的文本分辨率和更小的标签尺寸。默认值为30.0。
  fontSize: (可选,但如果提供缩放功能,则需要)文本字体的大小。默认值为50。
  showOnTop: (可选)如果为true,则标签将绘制在房间顶部,如果为false,则标签将绘制为背景,如果未指定,则默认为true。
  noScaling: (可选)如果为true,则在小地图中放大和缩小时,标签的大小将相同。如果为false,则缩放小地图时标签将缩放,如果未给出,则默认为true。
  fontName: (可选)要使用的字体名称。
  foregroundTransparency: (可选)标签上文本的透明度,默认为255(在0到255的范围内)或完全不透明(如果未给出)。
  backgroundTransparency:  标签背景本身的透明度(可选),默认值为50(范围为0到255),如果未指定,则为显著透明。
  temporary: (可选,来自Mudlet版本4.17.0)如果true不保存标签在地图保存文件中生成的图像,则默认为false(如果未给出),或者对于Mudlet的早期版本。

例子:

    local labelid = createMapLabel( 50, "my map label", 0,0,0, 255,0,0, 23,0,0, 0,20)
    local labelid = createMapLabel( 50, "1. Row One\n2. Row 2", .5,5.5,0, 255,0,0, 23,0,0, 30,50, true, false)
    
    local x,y,z = getRoomCoordinates(getPlayerRoom())
    createMapLabel(getRoomArea(getPlayerRoom()), "my map label", x,y,z, 255,0,0, 23,0,0, 0,20, false, true, "Ubuntu", 255, 100)

createMapImageLabel

命令格式:
labelID = createMapImageLabel(areaID, filePath, posx, posy, posz, width, height, zoom, showOnTop[, temporary])

在地图上以给定坐标创建图像标签,并使用给定的尺寸和缩放。您可能会发现默认的房间和图像大小相关性太大-尝试减小图像的宽度和高度,同时也放大相同的量。从Mudlet 4.17.0中,一个附加参数(如果没有从那时给出,则假设为假)使得标签不被保存在地图文件中,如果图像可以在将来加载时从加载地图文件时可用的外部文件重新生成,则可以避免显著地扩展所保存地图的大小。

例子:

createMapImageLabel(138, [[/home/vadi/Pictures/You only see what shown.png]], 0,0,0, 482/100, 555/100, 100, false, true)

createMapper

命令格式:
createMapper([name of userwindow], x, y, width, height)
为小地图创建一个miniconsole窗口,以使用给定尺寸进行渲染。您一次只能创建一个地图,并且当前不可能在小地图上或小地图下具有标签-否则,单击不会生效。

注:Mudlet 4.6.1+中可用的用户窗口名称
注意:如果不使用此命令,那么点击主工具栏的地图按钮将创建一个可停靠的小部件(它可以自由浮动到桌面上的任何地方,它可以调整大小,甚至不必驻留在同一个显示器上,如果系统中有多个屏幕)。进一步单击Map按钮将在显示和隐藏地图之间切换,无论它是使用createMapper函数创建的还是作为可停靠的小部件创建的。

例子:

createMapper(0,0,300,300) -- creates a 300x300 mapper in the top-left corner of Mudlet
setBorderLeft(305) -- adds a border so text doesn't underlap the mapper display

-- another example:
local main = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="mapper container"})
 
local mapper = Geyser.Mapper:new({
  name = "mapper",
  x = "70%", y = 0, -- edit here if you want to move it
  width = "30%", height = "50%"
}, main)

createRoomID

命令格式:
usableId = createRoomID([minimumStartingRoomId])
返回可用于创建新房间的可能最小的房间ID。如果您的地图使用的房间ID中存在间隙,则此函数将在创建更高的ID之前先遍历间隙。
参数: minimumStartingRoomId(可选,在Mudlet 3.0+中可用)
如果提供,指定一个roomID开始搜索空的roomID,而不是1。例如,如果您希望确保某些区域具有特定的房间号范围,则该选项非常有用。如果您正在使用一个巨大的地图,请将上次使用的房间ID提供给该函数,以便更快地找到可用的房间ID。

deleteArea

命令格式:
deleteArea(areaID or areaName)
删除给定区域和其中的所有房间。
例子:

-- delete by areaID
deleteArea(23)
-- or since Mudlet 3.0, by area name
deleteArea("Big city")

deleteMap

命令格式:
deleteMap()
删除整个小地图。这可能是有用的,而最初为新游戏设置地图程序包,以清除到这一点产生的错误地图数据。
注意:在引入这个函数之前,推荐的方法是使用loadMap()和一个不存在的文件名,例如“_”,但是这也会导致一个“[ ERROR ]”类型的消息出现在配置文件的主控制台上。

deleteMapLabel

命令格式:
deleteMapLabel(areaID, labelID)
从特定区域删除地图标签。

deleteRoom

命令格式:
deleteRoom(roomID)
删除单个房间,并取消所有通往该房间的出口的链接。

disableMapInfo

命令格式:
disableMapInfo(label)
禁用特定的地图信息-与从小地图下的选择框中切换关闭复选框相同。

enableMapInfo

命令格式:
enableMapInfo(label)
启用特定的地图信息-与从小地图下的选择框中切换复选框相同。
Mudlet在Mudlet中可用4.11+

getAllAreaUserData

命令格式:
dataTable = getAllAreaUserData(areaID)
返回存储在给定区域ID中的所有用户数据项;如果没有存储数据,则返回空表;如果没有具有该ID的区域,则返回空表。

getAllMapUserData

命令格式:
dataTable = getAllMapUserData()
返回存储在地图级别的所有用户数据项;如果没有存储数据,则返回空表。

getAllRoomEntrances

命令格式:
exitsTable = getAllRoomEntrances(roomID)
返回一个索引列表,其中包含通向该房间的正常出口和特殊出口。如果是双向出口,这会报告和 getRoomExits(), 但此功能也具有拾取进入房间的单向出口的能力。
例子:

for _, roomid in ipairs(getAllRoomEntrances(512)) do 
  print(roomid)
end

getAllRoomUserData

命令格式:
dataTable = getAllRoomUserData(roomID)
返回存储在给定房间ID中的所有用户数据项;如果没有存储数据,则返回空表;如果没有具有该ID的房间,则返回空表。
例子:

display(getAllRoomUserData(3441))

getAreaExits

命令格式:
roomTable = getAreaExits(areaID, showExits)
返回给定区域中房间的表(索引或键值),这些房间的出口通向其他区域(即,边界房间)。
例子:

-- list all border rooms for area 44:
getAreaExits(44)

-- returns:
--[[
{
  7091,
  10659,
  11112,
  11122,
  11133,
  11400,
  12483,
  24012
}
]]

getAreaRooms

命令格式:
roomTable = getAreaRooms(area id)
返回具有给定区域ID的所有房间ID的索引表(房间ID是值),或者 nil if no such area exists. 如果不存在这样的区域。
例子:

function echoRoomList(areaname)
  local id, msg = findAreaID(areaname)
  if id then
    local roomlist, endresult = getAreaRooms(id), {}
  
    -- obtain a room list for each of the room IDs we got
    for _, id in pairs(roomlist) do
      endresult[id] = getRoomName(id)
    end
  
    -- now display something half-decent looking
    cecho(string.format(
      "List of all rooms in %s (%d):\n", msg, table.size(endresult)))

    for roomid, roomname in pairs(endresult) do
      cecho(string.format(
        "%6s: %s\n", roomid, roomname))
    end
  elseif not id and msg then
    echo("ID not found; " .. msg)
  else
    echo("No areas matched the query.")
  end
end

getAreaTable

命令格式:
areaTable = getAreaTable()
返回一个键(区域名称)-值(区域id)表,其中包含所有已知区域及其ID。
例子:

function findAreaID(areaname)
  local list = getAreaTable()

  -- iterate over the list of areas, matching them with substring match. 
  -- if we get match a single area, then return it's ID, otherwise return
  -- 'false' and a message that there are than one are matches
  local returnid, fullareaname
  for area, id in pairs(list) do
    if area:find(areaname, 1, true) then
      if returnid then return false, "more than one area matches" end
      returnid = id; fullareaname = area
    end
  end
  
  return returnid, fullareaname
end

-- sample use:
local id, msg = findAreaID("blahblah")
if id then
  echo("Found a matching ID: " .. id)
elseif not id and msg then
  echo("ID not found: " .. msg)
else
  echo("No areas matched the query.")
end

getAreaTableSwap

命令格式:
areaTable = getAreaTableSwap()
返回一个键(区域id)-值(区域名称)表,其中包含所有已知区域及其ID。与getAreaTable不同的是,getAreaTable不会通过不同ID显示具有相同名称的所有区域,这个函数会。

getAreaUserData

命令格式:
dataValue = getAreaUserData(areaID, key)
返回针对给定区域ID号的给定键存储的特定数据项。 这与相应的房间用户数据命令非常相似,但适用于每个区域而不是每个房间数据(关于存储与整个地图相关的数据,请参见相应的地图用户数据命令)。
例子:

display(getAreaUserData(34, "country"))

getCustomEnvColorTable

命令格式:
envcolors = getCustomEnvColorTable()
返回具有自定义环境的表,其中键是环境ID,值是rgb值的索引表。
例子:

getCustomEnvColorTable()
{
  envid1 = {r, g, b, alpha},
  envid2 = {r, g, b, alpha}
}

getCustomLines

命令格式:
lineTable = getCustomLines(roomID)
返回一个表,其中包括具有给定id的房间的自定义退出行(如果有的话)的所有详细信息。
例子:

display getCustomLines(1)
{
  ["climb Rope"] = {
    attributes = {
      color = {
        b = 0,
        g = 128,
        r = 128
      },
      style = "dash dot dot line",
      arrow = false
    },
    points = {
      {
        y = 9.5,
        x = 4.5
      },
      {
        y = 9.5,
        x = 6
      },
      [0] = {
        y = 5.5,
        x = 4.5
      }
    }
  },
  N = {
    attributes = {
      color = {
        b = 255,
        g = 255,
        r = 0
      },
      style = "dot line",
      arrow = true
    },
    points = {
      [0] = {
        y = 27,
        x = -3
      }
    }
  }
}

getCustomLines1

命令格式:
lineTable = getCustomLines1(roomID)
这是getCustomLines(…)的替代品它以可以直接反馈到addCustomLine(…)的顺序和格式输出自定义线上的点的坐标表调用;类似地,颜色参数也以正确的格式报告,以同样的方式重新使用。此函数旨在使脚本更容易操作这些行。
例子:

display getCustomLines1(1)
{
  ["climb Rope"] = {
    attributes = {
      color = { 128, 128, 0 },
      style = "dash dot dot line",
      arrow = false
    },
    points = { { 4.5, 5.5, 3 }, { 4.5, 9.5, 3 }, { 6, 9.5, 3 } } 
  },
  N = {
    attributes = {
      color = { 0, 255, 255 },
      style = "dot line",
      arrow = true
    },
    points = { { -3, 27, 3 } }
  }
}

getDoors

命令格式:
doors = getDoors(roomID)
返回一个键值表,其中基本方向为键,门值为数字。如果房间中没有门,则返回一个空表。
例子:

-- an example that displays possible doors in room 2334
local doors = getDoors(2334)

if not next(doors) then cecho("\nThere aren't any doors in room 2334.") return end

local door_status = {"open", "closed", "locked"}

for direction, door in pairs(doors) do
  cecho("\nThere's a door leading in "..direction.." that is "..door_status[door]..".")
end

getExitStubs

命令格式:
stubs = getExitStubs(roomid)
返回方向#的索引表(从0开始),其中标记有出口。画地图时,您可以使用此信息在房间之间连接早期创建的出口。
例子:

-- show the exit stubs in room 6 as numbers
local stubs = getExitStubs(6)
for i = 0, #stubs do print(stubs[i]) end

Note注意:以前会在不存在的房间上抛出lua错误-现在返回nil加错误消息(和其他运行时错误一样)-以前只返回nil退出存根,但现在也返回通知错误消息,以帮助消除nil值的歧义。

getExitStubs1

命令格式:
stubs = getExitStubs1(roomid)
返回方向#的索引表(从1开始),其中标记有出口。画地图时,您可以使用此信息在房间之间连接早期创建的出口。由于这个函数从1开始索引,因为它在Lua中是默认的,所以你可以使用ipairs()来迭代结果。
例子:

for k,v in ipairs(getExitStubs1(6)) do print(k,v) end

Note注意:以前会在不存在的房间上抛出lua错误-现在返回nil加错误消息(和其他运行时错误一样)-以前只返回nil退出存根,但现在也返回通知错误消息,以帮助消除nil值的歧义。

getExitWeights

命令格式:
weights = getExitWeights(roomid)
返回房间具有的出口权重的键值表,其中方向或特殊出口作为键,值作为出口权重。如果尚未设置方向的权重,则不会列出该方向。

getGridMode

命令格式:
TrueOrFalse = getGridMode(areaID)
使用此选项可以查看特定区域是否设置了网格/荒野视图模式。通过这种方式,您还可以从脚本中计算出地图总共有多少网格区域。
例子:

getGridMode(55)
-- will return: false
setGridMode(55, true) -- set area with ID 55 to be in grid mode
getGridMode(55)
-- will return: true

getMapEvents

命令格式:
mapevents = getMapEvents()
返回当前注册的map事件列表。每个事件都是一个字典,其中包含键 uniquename, parent, event name, display name 等

在Mudlet中可用3.3+ 例子:

addMapEvent("room a", "onFavorite") -- will make a label "room a" on the map menu's right click that calls onFavorite

addMapEvent("room b", "onFavorite", "Favorites", "Special Room!", 12345, "arg1", "arg2", "argn")

local mapEvents = getMapEvents()
for _, event in ipairs(mapEvents) do
  echo(string.format("MapEvent '%s' is bound to event '%s' with these args: '%s'", event["uniquename"], event["event name"], table.concat(event["arguments"], ",")))
end

getMapLabel

命令格式:
labelinfo = getMapLabel(areaID, labelID or labelText)
返回描述区域中特定标签的键值表。它包含的键是 X, Y, Z coordinates, 坐标, Height and 和 Width, BgColor, FgColor, Pixmap, and the ,以及它包含的文本。如果标签是图像标签,则将被设置为 no text string.
例子:

lua getMapLabels(52)
{
  "no text",
  [0] = "test"
}

lua getMapLabel(52, 0)
{
  Y = -2,
  X = -8,
  Z = 11,
  Height = 3.9669418334961,
  Text = "test",
  Width = 8.6776866912842,
  BgColor = {
    b = 0,
    g = 0,
    r = 0
  },
  FgColor = {
    b = 50,
    g = 255,
    r = 255
  },
  Pixmap = "iVBORw0KG(...)lFTkSuQmCC" -- base64 encoded png image (shortened for brevity)
}

lua getMapLabel(52, "no text")
{
  Y = 8,
  X = -15,
  Z = 11,
  Height = 7.2520666122437,
  Text = "no text"
  Width = 11.21900844574,
  BgColor = {
    b = 0,
    g = 0,
    r = 0
  },
  FgColor = {
    b = 50,
    g = 255,
    r = 255
  },
  Pixmap = "iVBORw0KG(...)lFTkSuQmCC" -- base64 encoded png image (shortened for brevity)
}

getMapLabels

命令格式:
arealabels = getMapLabels(areaID)
返回区域中所有标签及其标签文本的索引表(从0开始索引)。您可以使用标签id来进行查询删除操作
如果该区域中根本没有标签,它将返回一个空表。
例子:

display(getMapLabels(43))
table {
  0: ''
  1: 'Waterways'
}

deleteMapLabel(43, 0)
display(getMapLabels(43))
table {
  1: 'Waterways'
}

getMapMenus

命令格式:
getMapMenus()
返回一个表,其中可用的地图菜单为键值,格式为 map menu - parent item 如果一个项目位于菜单的顶层,则该值将显示 top-level.

例子:

-- given the following menu structure:
top-level
  menu1
    menu1.1
      action1.1.1
    menu1.2
      action1.2.1
  menu2

getMapMenus() -- will return:
{
  menu2 = "top-level",
  menu1.2 = "menu1",
  menu1.1 = "menu1",
  menu1 = "top-level"
}

getMapSelection

命令格式:
getMapSelection()
返回一个表,其中包含2D小地图中当前鼠标选择的详细信息。

例子:

display(getMapSelection())
{
  center = 5013,
  rooms = {
    5011,
    5012,
    5013,
    5014,
    5018,
    5019,
    5020
  }
}

getMapUserData

命令格式:
getMapUserData( key )
返回用户数据项(字符串);如果在map数据中没有具有这样的键的数据,则返回nil+错误消息。

例子:

display(getMapUserData("last updated"))
--might result in:--
"December 5, 2020"

getMapZoom

命令格式:
getMapZoom([areaID])
获取当前二维地图缩放级别。函数也可以使用areaID来处理,而不是在地图中查看的当前区域。

例子:

echo("\nCurrent zoom level: " .. getMapZoom() .. "\n")
-- Could be anything from 3 upwards:

Current zoom level: 42.4242

getMapZoom

命令格式:
getMapZoom([areaID])
获取当前二维地图缩放级别。函数也可以使用areaID来处理,而不是在地图中查看的当前区域。

例子:

echo("\nCurrent zoom level: " .. getMapZoom() .. "\n")
-- Could be anything from 3 upwards:

Current zoom level: 42.4242
setMapZoom(2.5 + getMapZoom(1), 1) -- zoom out the area with ID 1 by 2.5
true

Note注:特定缩放值的精确含义可能具有潜在含义,然而,除了最小值为3.0和初始值(以及先前Mudlet版本开始每个会话时使用的)为20.0之外,尚未确定该含义。

getPath

命令格式:
getPath(roomID from, roomID to)
如果两个房间ID之间可能存在路径,则返回布尔值true/false。如果是,全球表被设置为到达那里必须采取的所有方向,并且全局 speedWalkPath 表设置为您在途中遇到的所有roomID,从3.0开始, speedWalkWeight将返回所有房间重量。另外返回3.0中布尔参数后路径的总成本(所有权重相加)。

例子:

-- check if we can go to room 155 from room 34 - if yes, go to it
if getPath(34,155) then
  gotoRoom(155)
else
  echo("\nCan't go there!")
end

getPlayerRoom

命令格式:
getPlayerRoom()
返回由设置的当前玩家位置
例子:

display("We're currently in " .. getRoomName(getPlayerRoom()))

getRoomArea

命令格式:
getRoomArea(roomID)
返回给定房间ID的区域ID。要获取区域名称,可以根据 getAreaTable() 函数,或使用 getRoomAreaName()函数
例子:

display("Area ID of room #100 is: "..getRoomArea(100))

display("Area name for room #100 is: "..getRoomAreaName(getRoomArea(100)))

getRoomAreaName

命令格式:
getRoomAreaName(areaID or areaName)
返回给定区域id的区域名称;或者给定区域名称的区域ID。
Note注意:尽管名称不同,此函数不会直接返回给定房间ID(或房间名称)的区域名称。但是,重命名或修改它会破坏现有脚本。
例子:

echo(string.format("room id #455 is in %s.", getRoomAreaName(getRoomArea(455))))

getRoomChar

命令格式:
getRoomChar(roomID)
对于给定的房间ID, 返回代表房间的ASCII字符, 3.8之后可以是UTF-8

getRoomCharColor

命令格式:
r,g,b = getRoomCharColor(roomID)
返回房间角色的颜色作为一组r,g,B颜色坐标。

local r,g,b = getRoomCharColor(12345)
decho(f"Room Character for room 12345 is <{r},{g},{b}>this color.<r> It is made up of <{r},0,0>{r} red<r>, <0,{g},0>{g} green<r>, <0,0,{b}> {b} blue<r>.\")

getRoomCoordinates

命令格式:
x,y,z = getRoomCoordinates(roomID)
返回给定房间ID的房间坐标。

local x,y,z = getRoomCoordinates(roomID)
echo("Room Coordinates for "..roomID..":")
echo("\n     X:"..x)
echo("\n     Y:"..y)
echo("\n     Z:"..z)

-- A quick function that will find all rooms on the same z-position in an area; this is useful if, say, you want to know what all the same rooms on the same "level" of an area is.
function sortByZ(areaID, zval)
  local area = getAreaRooms(areaID)
  local t = {}
  for _, id in ipairs(area) do
    local _, _, z = getRoomCoordinates(id)
    if z == zval then
      table.insert(t, id)
    end
  end
  return t
end

getRoomEnv

命令格式:
envID = getRoomEnv(roomID)
返回房间的环境ID。地图不存储环境名称,因此您需要自己跟踪哪个ID是哪个名称。

function checkID(id)
  echo(string.format("The env ID of room #%d is %d.\n", id, getRoomEnv(id)))
end

getRoomExits

命令格式:
getRoomExits (roomID)
以键索引形式返回房间当前已知的非特殊出口:

table {
  'northwest': 80
  'east': 78
}
-- 下面是一个实际示例,它查询您周围的房间并搜索特殊属性房间
local exits = getRoomExits(mycurrentroomid)
for direction,num in pairs(exits) do
  local env_num = getRoomEnv(num)
  if env_num == 22 or env_num == 20 or env_num == 30 then
    print("There's water to the "..direction.."!")
  end
end

getRoomHashByID

命令格式:
getRoomHashByID(roomID)
获取房间Hash值

for id,name in pairs(getRooms()) do
        local h = getRoomUserData(id, "herbs")
        if h ~= "" then
            echo(string.format([[["%s"] = "%s",]], getRoomHashByID(id), h))
            echo("\n")
        end
    end

getRoomIDbyHash

命令格式:
roomID = getRoomIDbyHash(hash)
房间Hash值查询房间ID

-- example taken from http://forums.mudlet.org/viewtopic.php?f=13&t=2177
local id = getRoomIDbyHash("5dfe55b0c8d769e865fd85ba63127fbc")
if id == -1 then 
  id = createRoomID()
  setRoomIDbyHash(id, "5dfe55b0c8d769e865fd85ba63127fbc")
  addRoom(id)
  setRoomCoordinates(id, 0, 0, -1)
end

getRoomName

命令格式:
getRoomName(roomID)
通过Id查询房间名字

echo(string.format("The name of the room id #455 is %s.", getRoomName(455))

getRooms

命令格式:
rooms = getRooms()
返回所有地图中的房间在整个地图中以roomid -房间名称格式显示。

-- simple, raw viewer for rooms in the world
display(getRooms())

-- iterate over all rooms in code
for id,name in pairs(getRooms()) do
  print(id, name)
end

getRoomsByPosition

命令格式:
roomTable = getRoomsByPosition(areaID, x,y,z)
返回给定区域中给定坐标处的所有房间的索引表,如果没有,则返回空的。此函数可用于检查房间是否存在于特定坐标处,或当房间重叠时。
Note注意:返回的表从0开始索引,而不是通常的lua索引1,这意味着使用#来计算返回的表的大小将产生错误的结果-使用table.size()代替。

-- sample alias to determine a room nearby, given a relative direction from the current room

local otherroom
if matches[2] == "" then
  local w = matches[3]
  local ox, oy, oz, x,y,z = getRoomCoordinates(mmp.currentroom)
  local has = table.contains
  if has({"west", "left", "w", "l"}, w) then
    x = (x or ox) - 1; y = (y or oy); z = (z or oz)
  elseif has({"east", "right", "e", "r"}, w) then
    x = (x or ox) + 1; y = (y or oy); z = (z or oz)
  elseif has({"north", "top", "n", "t"}, w) then
    x = (x or ox); y = (y or oy) + 1; z = (z or oz)
  elseif has({"south", "bottom", "s", "b"}, w) then
    x = (x or ox); y = (y or oy) - 1; z = (z or oz)
  elseif has({"northwest", "topleft", "nw", "tl"}, w) then
    x = (x or ox) - 1; y = (y or oy) + 1; z = (z or oz)
  elseif has({"northeast", "topright", "ne", "tr"}, w) then
    x = (x or ox) + 1; y = (y or oy) + 1; z = (z or oz)
  elseif has({"southeast", "bottomright", "se", "br"}, w) then
    x = (x or ox) + 1; y = (y or oy) - 1; z = (z or oz)
  elseif has({"southwest", "bottomleft", "sw", "bl"}, w) then
    x = (x or ox) - 1; y = (y or oy) - 1; z = (z or oz)
  elseif has({"up", "u"}, w) then
    x = (x or ox); y = (y or oy); z = (z or oz) + 1
  elseif has({"down", "d"}, w) then
    x = (x or ox); y = (y or oy); z = (z or oz) - 1
  end

  local carea = getRoomArea(mmp.currentroom)
  if not carea then mmp.echo("Don't know what area are we in.") return end

  otherroom = select(2, next(getRoomsByPosition(carea,x,y,z)))

  if not otherroom then
    mmp.echo("There isn't a room to the "..w.." that I see - try with an exact room id.") return
  else
    mmp.echo("The room "..w.." of us has an ID of "..otherroom)
  end

getRoomUserData

命令格式:
getRoomUserData(roomID, key)
getRoomUserData(roomID, key, enableFullErrorReporting)
返回存储在给定房间中的用户数据值(字符串)

display(getRoomUserData(341, "visitcount"))
local vNum = 341
result, errMsg = getRoomUserData(vNum, "visitcount", true)
if result ~= nil then
    display(result)
else
    echo("\nNo visitcount data for room: "..vNum.."; reason: "..errMsg.."\n")
end

getRoomUserDataKeys

命令格式:
getRoomUserDataKeys(roomID)
返回存储在给定房间ID中的用户数据项的所有键;如果没有存储数据,则返回空表;如果没有具有该ID的房间,则返回空表。

display(getRoomUserDataKeys(3441))
--might result in:--
{
  "description",
  "doorname_up",
}

getRoomWeight

命令格式:
getRoomWeight(roomID)
返回房间的重量。默认情况下,所有新房间的权重均为1。

display("Original weight of room 541: "..getRoomWeight(541))
setRoomWeight(541, 3)
display("New weight of room 541: "..getRoomWeight(541))

getSpecialExits

命令格式:
exits = getSpecialExits(roomID[, listAllExits])
在有一个以上的特殊出口的情况下,同一房间ID列表中的所有出口。
返回一个roomid表,其中包含房间中特殊出口的name/command和出口锁定状态的子表。如果房间里没有特殊的出口,返回的表将是空的。

getSpecialExits(1337)
-- In 4.10.1 and before this could results in:
table {
  42 = {"jump out window" = "0"},
  666 = {"dive into pit" = "1"}
}
-- OR
table {
  42 = {"climb down ladder" = "1"},
  666 = {"dive into pit" = "1"}
}
-- OR
table {
  42 = {"step out window" = "0"},
  666 = {"dive into pit" = "1"}
}

-- From TBA this will return:
table {
  42 = {"step out window" = "0"},
  666 = {"dive into pit" = "1"}
}

-- From TBA, with the second argument as true, this gives:
getSpecialExits(1337, true)
table {
  42 = {"step out window" = "0",
        "climb down ladder" = "1",
        "jump out window" = "0"},
  666 = {"dive into pit" = "1"}
}

getSpecialExitsSwap

命令格式:
getSpecialExitsSwap(roomID)
和getSpecialExits()类似。

gotoRoom

命令格式:
gotoRoom (roomID)
如果它能够并且知道路的话,它可以从你现在的房间快速步行到给定的房间。您必须打开小地图才能工作,否则它将返回“我不知道怎么从这里到那里

hasExitLock

命令格式:
status = hasExitLock(roomID, direction)
判断是否锁门

-- check if the east exit of room 1201 is locked
display(hasExitLock(1201, 4))
display(hasExitLock(1201, "e"))
display(hasExitLock(1201, "east"))

hasSpecialExitLock

命令格式:
hasSpecialExitLock(from roomID, to roomID, moveCommand)
判断是否锁门

-- lock a special exit from 17463 to 7814 that uses the 'enter feather' command
lockSpecialExit(17463, 7814, 'enter feather', true)

-- see if it is locked: it will say 'true', it is
display(hasSpecialExitLock(17463, 7814, 'enter feather'))

highlightRoom

命令格式:
highlightRoom( roomID, color1Red, color1Green, color1Blue, color2Red, color2Green, color2Blue, highlightRadius, color1Alpha, color2Alpha)
亮显具有给定颜色的房间,这将覆盖其环境颜色。如果你使用两种不同的颜色,那么会有一个从中心向外的阴影改变为另一种颜色。

-- color room #351 red to blue
local r,g,b = unpack(color_table.red)
local br,bg,bb = unpack(color_table.blue)
highlightRoom(351, r,g,b,br,bg,bb, 1, 255, 255)

killMapInfo

命令格式:
killMapInfo(label)
完全删除地图信息贡献者-它将不再可用。

loadJsonMap

命令格式:
loadJsonMap(pathFileName)
加载文本(JSON)格式的Mudlet地图文件。它确实比加载通常的地图文件(二进制.dat)花费更长的时间,所以它会显示一个进度对话框。

loadJsonMap(getMudletHomeDir() .. "/map.json")

loadMap

命令格式:
loadJsonMap(pathFileName)
加载地图文件

loadMap("/home/user/Desktop/Mudlet Map.dat")
loadMap(getMudletHomeDir() .. "/map.dat")

lockExit

命令格式:
lockExit(roomID, direction, lockIfTrue)
锁定房间的给定出口。目的地可以通过其他路径保持可访问,不像 lockRoom. direction可以指定为数字、短方向名称(“nw”)或长方向名称(“northwest”)。

lockExit(1201, 4, true)

lockRoom

命令格式:
lockRoom (roomID, lockIfTrue)
锁定给定的房间ID,防止将来的speedwalk(因此地图行走将永远不会通过该房间)。

lockRoom(1, true) -- locks a room if from being walked through when speedwalking.
lockRoom(1, false) -- unlocks the room, adding it back to possible rooms that can be walked through.

lockSpecialExit

命令格式:
lockSpecialExit (from roomID, to roomID, special exit command, lockIfTrue)
锁定给定的特殊出口,从一个特定房间通向另一个特定房间,该特定房间使用来自未来speedwalk的特定命令(因此地图永远不会通过该特殊出口)。

lockSpecialExit(1,2,'enter gate', true) -- locks the special exit that does 'enter gate' to get from room 1 to room 2
lockSpecialExit(1,2,'enter gate', false) -- unlocks the said exit

moveMapWidget

命令格式:
moveMapWidget(Xpos, Ypos)
将地图窗口移动到给定位置。
参数:
Xpos: 地图窗口的X位置。以像素为单位,0表示最左边。作为整数传递。
Ypos: 地图窗口的Y位置。以像素为单位测量,0表示最顶部。作为整数传递。

openMapWidget

命令格式:
openMapWidget([dockingArea | Xpos, Ypos, width, height])
openMapWidget()
openMapWidget(dockingArea)
openMapWidget(Xpos, Ypos, width, height) 打开带有给定选项的地图窗口。
参数:
Xpos: 地图窗口的X位置。以像素为单位,0表示最左边。作为整数传递。
Ypos: 地图窗口的Y位置。以像素为单位测量,0表示最顶部。作为整数传递。
width: 地图窗口宽度,以像素为单位。作为整数传递。 height: 地图窗口高度,以像素为单位。作为整数传递。

pauseSpeedwalk

命令格式:
pauseSpeedwalk()
暂停一个行走。
在Mudlet中可用4.13+ 例子:

local ok, err = pauseSpeedwalk()
if not ok then
  debugc(f"Error: unable to pause speedwalk because {err}\n")
  return
end

registerMapInfo

命令格式:
registerMapInfo(label, function)
向小地图小部件添加额外的“地图信息”,可用于显示自定义信息。
注意事项: 您可以注册多个地图信息-只需给予它们唯一的名称并切换任何您需要的名称。
参数: function: 回调函数,负责返回如何绘制地图信息片段的信息。 使用以下参数调用回调函数:

roomId - current roomId or currently selected room (when multiple selection is made this is center room)
    roomId-当前roomId或当前选择的房间(当进行多个选择时,这是中心房间)
    selectionSize-选择了多少个房间
    areaId- roomId的areaId
    displayedAreaId-当前显示的areaId

回调需要返回以下内容:

    text-将显示的文本(如果为空,则不显示任何内容,如果要“保留”行,则使用非空值“”或添加换行符“\n”)
    isBold(可选)- true/false -确定文本是否为粗体
    isItalic(可选)- true/false -确定文本是否为斜体
    color r(可选)-文本红色分量的颜色(0-255)
    color g(可选)-文本绿色分量的颜色(0-255)
    color B(可选)-文本蓝色分量的颜色(0-255)

注意事项: 地图信息以禁用状态注册,您需要通过脚本或通过选择小地图下的复选框来启用它。

registerMapInfo("My very own handler!", function(roomId, selectionSize, areaId, displayedArea) 
  return string.format("RoomId: %d\nNumbers of room selected: %d\nAreaId: %d\nDisplaying area: %d", roomId, selectionSize, areaId, displayedArea),
  true, true, 0, 255, 0
end)
enableMapInfo("My very own handler!")

示例: 使用函数参数是完全可选的,您可以确定是否以及如何在外部完全显示地图信息。

registerMapInfo("Alert", function() 
  if character.hp < 20 then
    return "Look out! Your HP is getting low", true, false, unpack(color_table.red) -- will display red, bolded warning whne character.hp is below 20
  else
    return "" -- will not return anything
  end
end)
enableMapInfo("Alert")

resumeSpeedwalk

命令格式:
resumeSpeedwalk()
继续使用暂停的高速行走。
在Mudlet4.13+中可用 例子:

local ok, err = resumeSpeedwalk()
if not ok then
  cecho(f"\n<red>Error:<reset> Problem resuming speedwalk: {err}\n")
  return
end
cecho("\n<green>Successfully resumed speedwalk!\n")

removeCustomLine

命令格式:
removeCustomLine(roomID, direction)
删除与房间特定出口关联的自定义出口线。
例子:

-- remove custom exit line that starts in room 315 going north
removeCustomLine(315, "n")

removeMapEvent

命令格式:
removeMapEvent(event name)
从小地图右键单击菜单中删除给定菜单项。
例子:

-- remove custom exit line that starts in room 315 going north
addMapEvent("room a", "onFavorite") -- add one to the general menu
removeMapEvent("room a") -- removes the said menu

removeMapMenu

命令格式:
removeMapMenu(menu name)
从小地图右键单击菜单中删除给定的子菜单。
例子:

addMapMenu("Test") -- add submenu to the general menu
removeMapMenu("Test") -- removes that same menu again

removeSpecialExit

命令格式:
removeSpecialExit(roomID, command)
roomID房间移除特殊出口
例子:

addSpecialExit(1, 2, "pull rope") -- add a special exit from room 1 to room 2
removeSpecialExit(1, "pull rope") -- removes the exit again

resetRoomArea

命令格式:
resetRoomArea (roomID)
roomID房间移除特殊出口
取消指定房间的指定区域。在未分配时,其区域ID将为-1。 请注意,自Mudlet 3.0以来,具有-1 id的“默认区域”可以在小地图上的区域选择小部件中选择
例子:

resetRoomArea(3143)

resizeMapWidget

命令格式:
resizeMapWidget(width, height)
调整一个地图窗口的大小与给定的宽度,高度.
在Mudlet中可用4.7+

roomExists

命令格式:
roomExists(roomID)
返回布尔值true/false,具体取决于具有该ID的房间是否存在(是否已创建)。

roomLocked

命令格式:
locked = roomLocked(roomID)
每当给定房间被锁定时,返回true或false。
例子:

echo(string.format("Is room #4545 locked? %s.", roomLocked(4545) and "Yep" or "Nope"))

saveJsonMap

命令格式:
saveJsonMap([pathFileName])
以文本(JSON)格式保存Mudlet小地图(.dat作为二进制格式)中通常保存的所有数据。这样做确实需要更长的时间,因此将显示一个进度对话框,指示状态。

saveJsonMap(getMudletHomeDir() .. "/map.json")

saveMap

命令格式:
saveMap([location], [version])
将地图保存到给定位置,成功时返回true。位置文件夹需要已经创建,才能保存工作。也可以在“地图设置”选项卡中保存地图。

local savedok = saveMap(getMudletHomeDir().."/my fancy map.dat")
if not savedok then
  echo("Couldn't save :(\n")
else
  echo("Saved fine!\n")
end

-- save with a particular map version
saveMap(20)

searchAreaUserData

命令格式:
searchAreaUserData(area number | area name[, case-sensitive [, exact-match]])
搜索区域的用户数据的方式与 searchRoomUserData()在所有房间的用户数据中,请参阅该命令以了解具体详细信息,但用区域和区域ID号替换对房间和房间ID号的引用除外。

searchRoom

命令格式:
searchRoom (room number | room name[, case-sensitive [, exact-match]])
搜索与给定房间名称匹配(不区分大小写,子字符串匹配)的房间。它以 roomid = roomname, 可选的第二和第三布尔参数自Mudlet 3.0以来已经可用;
例子:

-- show the behavior when given a room number:
display(searchRoom(3088))
"The North Road South of Taren Ferry"

-- show the behavior when given a string:
-- shows all rooms containing the text in any case:
display(searchRoom("North road"))
{
   [3114] = "Bend in North road",
   [3115] = "North road",
   [3116] = "North Road",
   [3117] = "North road",
   [3146] = "Bend in the North Road",
   [3088] = "The North Road South of Taren Ferry",
   [6229] = "Grassy Field By North Road"
}
-- or:
--   display(searchRoom("North road",false))
--   display(searchRoom("North road",false,false))
-- would both also produce those results.

-- shows all rooms containing the text in ONLY the letter-case provided:
display(searchRoom("North road",true,false))
{
   [3114] = "Bend in North road",
   [3115] = "North road",
   [3117] = "North road",
}

-- shows all rooms containing ONLY that text in either letter-case:
lua searchRoom("North road",false,true)
{
  [3115] = "North road",
  [3116] = "North Road",
  [3117] = "North road"
}

-- shows all rooms containing only and exactly the given text:
lua searchRoom("North road",true,true)
{
  [3115] = "North road",
  [3117] = "North road"
}

注意:从技术上讲,两个选项(区分大小写和精确匹配)都设置为true,我们可以只返回一个数字列表,因为我们确切地知道字符串将是什么,但为了在用户脚本中获得最大的灵活性,它保持不变。

searchRoomUserData

命令格式:
searchRoomUserData([key, [value]])
searchRoomUserData(key, value) 报告所有房间ID的(排序)列表,其中用户数据具有给定的(区分大小写)“键”的给定的“值”。

searchRoomUserData(key) 使用给定(区分大小写)“键”报告所有房间中包含用户数据的唯一值(排序)列表。
searchRoomUserData() 从Mudlet 3.0开始提供的所有房间的唯一密钥的(排序)列表.

-- if I had stored the details of "named doors" as part of the room user data --
display(searchRoomUserData("doorname_up"))

--[[ could result in a list:
{
  "Eastgate",
  "Northgate",
  "boulderdoor",
  "chamberdoor",
  "dirt",
  "floorboards",
  "floortrap",
  "grate",
  "irongrate",
  "rockwall",
  "tomb",
  "trap",
  "trapdoor"
}]]

-- then taking one of these keys --
display(searchRoomUserData("doorname_up","trapdoor"))

--[[ might result in a list:
{
  3441,
  6113,
  6115,
  8890
}
]]

setAreaName

命令格式:
setAreaName(areaID or areaName, newName)
命名或将现有区域重命名为新名称。

setAreaUserData

命令格式:
setAreaUserData(areaID, key (as a string), value (as a string))
设置区域用户数据。
例子:

-- can use it to store extra area details...
setAreaUserData(34, "country", "Andor.")

-- or a sound file to play in the background (with a script that checks a room's area when entered)...
setAreaUserData(34, "backgroundSound", "/home/user/mudlet-data/soundFiles/birdsong.mp4")

-- can even store tables in it, using the built-in yajl.to_string function
setAreaUserData(101, "some table", yajl.to_string({ruler = "Queen Morgase Trakand", clan = "Lion Warden"}))
display("The ruler's name is: "..yajl.to_value(getRoomUserData(101, "some table")).ruler)

setCustomEnvColor

命令格式:
setCustomEnvColor(environmentID, r,g,b,a)
为给定环境ID创建或覆盖已创建的自定义颜色定义。
例子:

setRoomEnv(571, 200) -- change the room's environment ID to something arbitrary, like 200
local r,g,b = unpack(color_table.blue)
setCustomEnvColor(200, r,g,b, 255) -- set the color of environmentID 200 to blue

setDoor

命令格式:
setDoor(roomID, exitCommand, doorStatus)
在房间中创建或删除门。门是纯粹的视觉-它们不会影响路径的寻找。但是,您可以使用这些信息根据房间中的门信息调整您的快步行走路径。
doorStatus: 门的状态是一个数字- 0 , 意味着没有(或移除)门, 1 m, 表示开门(在出口处画一个绿色方块), 2表示关闭的门(黄色方块)和 3意味着锁着的门(红色方块)。

例子:

-- make a door on the east exit of room 4234 that is currently open
setDoor(4234, 'e', 1)

-- remove a door from room 923 that points north
setDoor(923, 'n', 0)

setExit

命令格式:
setExit(from roomID, to roomID, direction)
使用标准方向创建从一个房间到另一个房间的单向出口,标准方向可以是以下任一项 n, ne, nw, e, w, s, se, sw, u, d, in, out方向的长版本,或表示方向的数字。如果在该方向上已经有一个退出存根,那么它将自动为您删除。

例子:

-- alias pattern: ^exit (\d+) (\d+) (\w+)$
-- so exit 1 2 5 will make an exit from room 1 to room 2 via north

if setExit(tonumber(matches[2]), tonumber(matches[3]), matches[4]) then
  echo("\nExit set to room:"..matches[3].." from "..matches[2]..", direction:"..string.upper(matches[3]))
else
  echo("Failed to set the exit.\n")
end

如果你这样使用,这个函数也可以删除房间的出口:

setExit(from roomID, -1, direction)

setExitStub

命令格式:
setExitStub(roomID, direction, set/unset)
按给定方向从房间创建或删除退出存根。您可以稍后使用退出存根来连接您确定在一起的房间。出口存根也会在地图上直观地显示,因此绘图仪可以很容易地分辨出哪些房间需要装修。
例子:

--  从8号房间向南创建一个出口存根:
setExitStub(8, "s", true)
-- 如何删除房间中的所有退出存根:
for i,v in pairs(getExitStubs(roomID)) do
  setExitStub(roomID, v,false)
end

setExitWeight

命令格式:
setExitWeight(roomID, exitCommand, weight)
为出口赋予一个权重,使其不太可能被选择用于寻路。默认情况下,所有出口的权重为0,您可以增加该权重。出口权重设置为单向出口-如果您希望权重应用于两种方式,请从反向房间和方向设置。

setGridMode

命令格式:
setGridMode(areaID, true/false)
为区域启用网格/荒野视图模式-这将导致房间失去可见的出口连接,就像你在压缩ASCII地图上看到的那样,无论是在2D还是3D视图模式下;对于2D地图,如果启用此模式,则也不会显示自定义出口线。

setMapUserData

命令格式:
setMapUserData(key (as a string), value (as a string))
在给定键下存储有关地图的信息。类似于Lua的键值表,除了这里只能使用字符串。使用userdata的一个优点是它存储在地图文件本身中-所以与其他人共享地图将传递用户数据。你想要多少钥匙都行。

setMapUserData

命令格式:
setMapUserData(key (as a string), value (as a string))
在给定键下存储有关地图的信息。类似于Lua的键值表,除了这里只能使用字符串。使用userdata的一个优点是它存储在地图文件本身中-所以与其他人共享地图将传递用户数据。你想要多少钥匙都行。

setMapZoom

命令格式:
setMapZoom(zoom[, areaID])
将二维(仅)小地图缩放到给定缩放级别。数字越大,地图越远。年修订 Mudlet 4.17.0 以允许对要指定的区域进行缩放,即使该区域不是当前正在观看的区域。此更改与Mudlet永久记住(保存在地图文件中)每个区域最后使用的缩放级别,并添加 getMapZoom() 功能

setRoomArea

命令格式:
setRoomArea(roomID, newAreaID or newAreaName)
将给定的房间指定给新的或不同的区域。如果该区域显示在小地图中,这将使房间也可视地移动到该区域中。

setRoomChar

命令格式:
setRoomChar(roomID, character)
最初是为网格模式下的区域设计的,采用单个ASCII字符并在2D地图中房间的矩形背景上绘制。
例子:

 setRoomChar(431, "#")

setRoomChar(123, "$")

-- emoji's work fine too, and if you'd like it coloured, set the font to Nojo Emoji in settings
setRoomChar(666, "👿")

此函数现在将采用任何可打印字符的短串作为房间符号,并且它们将被缩小以使它们全部水平地容纳,但是如果它们变得太小,则该符号可能不会显示,如果缩放使得房间符号太小而无法辨认。
由于“_”现在是一个有效的字符,现有的符号可以用空格“”或空字符串“”擦除,尽管在Mudlet的一些以前版本中这两种都不有效。
如果房间被设置为绘制为圆形,现在可以满足这一点,并且符号将调整大小以适应这将导致的缩小绘图区域。
一个指示器,用于显示符号是否可以仅由选定字体(绿色勾号)、系统中可用的字体(黄色警告三角形)或根本不可以(红十字)
地图上使用的所有符号,以及它们将如何仅使用选定字体和所有字体显示
用于创建符号的代码点序列,当与字符选择实用程序(如Windows上的charmap.exe和类Unix系统上的gucharmap)一起使用时,将非常有用
使用特定符号对房间进行计数
一个列表,仅限于使用该符号的第一个房间的条目

setRoomCharColor

命令格式:
setRoomCharColor(roomId, r, g, b)
设置房间符号的颜色。

setRoomCoordinates

命令格式:
setRoomCoordinates(roomID, x, y, z)
将给定的房间ID设置为在地图上可视的以下坐标处

注:0,0,0是地图的中心。
例子:

-- alias pattern: ^set rc (-?\d+) (-?\d+) (-?\d+)$
-- this sets the current room to the supplied coordinates
setRoomCoordinates(roomID,x,y,z)
centerview(roomID)

-- alias pattern: ^src (\w+)$
local x,y,z = getRoomCoordinates(previousRoomID)
local dir = matches[2]

if dir == "n" then
  y = y+1
elseif dir == "ne" then
  y = y+1
  x = x+1
elseif dir == "e" then
  x = x+1
elseif dir == "se" then
  y = y-1
  x = x+1
elseif dir == "s" then
  y = y-1
elseif dir == "sw" then
  y = y-1
  x = x-1
elseif dir == "w" then
  x = x-1
elseif dir == "nw" then
  y = y+1
  x = x-1
elseif dir == "u" or dir == "up" then
  z = z+1
elseif dir == "down" then
  z = z-1
end
setRoomCoordinates(roomID,x,y,z)
centerview(roomID)

setRoomEnv

命令格式:
setRoomEnv(roomID, newEnvID)
将给定房间设置为新的环境ID。你不需要使用任何函数来创建它-可以立即设置它。

setRoomEnv

命令格式:
setRoomName(roomID, newName)
将现有房间重命名为新名称。

setRoomUserData

命令格式:
setRoomUserData(roomID, key (as a string), value (as a string))
设置房间用户信息。

setRoomUserData

命令格式:
setRoomUserData(roomID, key (as a string), value (as a string))
设置房间用户信息。

setRoomWeight

命令格式:
setRoomWeight(roomID, weight)
将权重设置为给定的roomID。默认情况下,所有房间的权重均为1 -权重越高,越有可能避开房间进行路径查找。例如,如果穿越水房间比陆地房间花费更多的时间,那么您需要为所有水房间分配一个权重,这样如果有可能的陆地路径,就可以避开水房间。
完全避开房间,利用 lockRoom()

speedwalk

命令格式:
speedwalk(dirString, backwards, delay, show)
快速行走函数将在基数+序数方向(n、ne、e等)上工作。以及u(表示向上)、d(表示向下)、in和out。它可以被调用来直接执行所有方向,没有延迟,或者有一个自定义延迟,这取决于你的游戏允许你走多快。它也可以用开关调用,使函数反转整个路径并引导你向后。
delaytime参数将设置每次移动之间的延迟(例如,如果您希望脚本每半秒移动一次,则设置为0.5)。可选:如果您不指明,脚本将依次发送所有方向命令。(If如果您想要指示延迟,则必须显式地指示反向标志的true或false。)
show参数将决定此函数发送的命令是显示还是隐藏。可选:如果你没有给予一个值,脚本将显示所有发送的命令。(If如果你想使用这个选项,你必须显式地指示反向标志的true或false,以及延迟的某个数字或nil(如果你不想要延迟)。
“YourDirectionsString”包含您的方向和步骤列表(例如:“2n,3w,u,5ne”)。数字表示您希望它沿其后指定的方向行走的步数。方向必须由除了可以出现在方向本身中的字母以外的任何东西分隔。(I.e.你可以用逗号、空格、字母x等分隔。以及任何这样的组合,但你不能用字母“e”分开,或者写两个方向,彼此相邻,中间没有任何东西,例如“wn”。如果你在每个方向前写一个数字,你不需要任何分隔符。例如,写“3w1ne2e”是完全可以接受的。该函数不区分大小写。

此函数的show参数在Mudlet 3.12+中可用

例子:

speedwalk("16d1se1u")
-- Will walk 16 times down, once southeast, once up. All in immediate succession.

speedwalk("2ne,3e,2n,e")
-- Will walk twice northeast, thrice east, twice north, once east. All in immediate succession.

speedwalk("IN N 3W 2U W", false, 0.5)
-- Will walk in, north, thrice west, twice up, west, with half a second delay between every move.

speedwalk("5sw - 3s - 2n - w", true)
-- Will walk backwards: east, twice south, thrice north, five times northeast. All in immediate succession.

speedwalk("3w, 2ne, w, u", true, 1.25)
-- Will walk backwards: down, east, twice southwest, thrice east, with 1.25 seconds delay between every move.
注意:最合乎逻辑的用法可能是将其放在别名中。例如,具有模式^/(.+)$ 执行:speedwalk(matches[2], false, 0.7) ^//(.+)$ 执行:speedwalk(matches[2], true, 0.7) 或者创建别名,如:^banktohome$执行speedwalk("2ne,e,ne,e,3u,in", true, 0.5) 

stopSpeedwalk

命令格式:
stopSpeedwalk()
停止行走。
例子:

local ok, err = stopSpeedwalk()
if not ok then
  cecho(f"\n<red>Error:<reset> {err}")
  return
end
cecho(f"\n<green>Success:<reset> speedwalk stopped")

unHighlightRoom

命令格式:
unHighlightRoom(roomID)
如果房间以前亮显,则取消亮显,并恢复房间的原始环境颜色。

unsetRoomCharColor

命令格式:
unsetRoomCharColor(roomId)
从房间中删除char颜色设置,返回到根据房间背景亮度自动确定。

updateMap

命令格式:
unsetRoomCharColor(roomId)
更新小地图显示(重绘)。如果您已通过脚本编辑地图并希望显示更改,请使用此功能。

-- delete a some room
deleteRoom(500)
-- now make the map show that it's gone
updateMap()

辅助功能

addFileWatch

命令格式:
addFileWatch(path)
在目录或文件上添加文件监视。

herbs = {}
local herbsPath = getMudletHomeDir() .. "/herbs.lua"
function herbsChangedHandler(_, path)
  if path == herbsPath then
    table.load(herbsPath, herbs)
    removeFileWatch(herbsPath)
  end
end

addFileWatch

命令格式:
addFileWatch(path)
在目录或文件上添加文件监视。

herbs = {}
local herbsPath = getMudletHomeDir() .. "/herbs.lua"
function herbsChangedHandler(_, path)
  if path == herbsPath then
    table.load(herbsPath, herbs)
    removeFileWatch(herbsPath)
  end
end
addFileWatch(herbsPath)
registerAnonymousEventHandler("sysPathChanged", "herbsChangedHandler")

addSupportedTelnetOption

命令格式:
addSupportedTelnetOption(option)
添加一个telnet选项,当游戏服务器查询时,Mudlet将返回DO(253)on。使用此选项来注册您将使用Mudlet添加支持的telnet选项

<event handlers that add support for MSDP... see http://www.mudbytes.net/forum/comment/63920/#c63920 for an example>

-- register with Mudlet that it should not decline the request of MSDP support
local TN_MSDP = 69
addSupportedTelnetOption(TN_MSDP)

alert

命令格式:
alert([seconds])
提醒用户正在发生的事情-使Mudlet在Windows窗口栏中闪烁,在macOS Dock中反弹,或在Linux上闪烁。

-- flash indefinitely until Mudlet is open
alert()

-- flash for just 3 seconds
alert(3)

cfeedTriggers

命令格式:
cfeedTriggers(text)
与feedTriggers类似,但您可以使用颜色名称添加颜色信息,类似于cecho。
参数: text:要馈送到触发引擎的字符串。按名称包括颜色,如black,red,green,yellow,blue,magenta,cyan,white and light_*版本。您也可以使用一个数字来获取对应于该数字的ansi颜色。

cfeedTriggers("<green:red>green on red<r> reset <124:100> foreground of ANSI124 and background of ANSI100<r>\n")

closeMudlet

命令格式:
closeMudlet()
立即关闭Mudlet和所有配置文件。
注意:小心使用。这可能导致数据丢失,如果“关闭时保存”未激活,用户没有手动保存配置文件,因为这不会要求确认,也不会保存配置文件。也不考虑是否有其他配置文件打开,如果多播放:他们都将被关闭!

deleteAllNamedEventHandlers

命令格式:
deleteAllNamedEventHandlers(userName)
删除userName的所有命名事件处理程序,并防止它们再次触发。信息已删除,无法检索。

deleteAllNamedEventHandlers("Demonnic")

deleteNamedEventHandler

命令格式:
success = deleteNamedEventHandler(userName, handlerName)
删除名为handlerName的命名事件处理程序,并阻止它再激发。信息已删除,无法检索。

local deleted = deleteNamedEventHandler("Demonnic", "Vitals")
if deleted then
  cecho("Vitals deleted forever!!")
else
  cecho("Vitals doesn't exist and so could not be deleted.")
end

denyCurrentSend

命令格式:
denyCurrentSend()
取消任何 send()或用户输入的命令,但只有在 sysDataSendRequest 活动

-- cancels all "eat hambuger" commands
function cancelEatHamburger(event, command)
  if command == "eat hamburger" then
    denyCurrentSend()
    cecho("<red>Denied! Didn't let the command through.\n")
  end
end
registerAnonymousEventHandler("sysDataSendRequest", "cancelEatHamburger")

dfeedTriggers

命令格式:
dfeedTriggers(str)
像feedTriggers一样,但是你可以使用r,g,b添加颜色信息,类似于decho。
例子:

dfeedTriggers("<0,128,0:128,0,0>green on red<r> reset\n")

disableModuleSync

命令格式:
dfeedTriggers(str)
停止同步给定模块。

enableModuleSync

命令格式:
enableModuleSync(name)
启用给定模块名称的同步-对它所做的任何更改都将保存到磁盘中,如果模块安装在任何其他配置文件中,则在配置文件保存时也会更新。

expandAlias

命令格式:
expandAlias(command, [echoBackToBuffer])
运行命令,就像它是从命令行-所以别名被检查,如果没有匹配,它发送到游戏中不变。
注意:不建议再使用expandAlias,因为它不是很健壮,可能会导致后续问题。建议改用lua函数。有关详细信息和示例,请参见Manual:Functions_vs_expandAlias。
注意:如果你想在调用expandAlias后使用匹配表,你应该先将它保存为,例如:local oldmatches =在调用expandAlias之前匹配,因为expandAlias在再次使用后会覆盖它。
注:自Mudlet 3.17.1以来,当游戏服务器协商telnet ECHO选项以提供我们发送给他的文本的回显时,可选的第二个参数在屏幕上回显命令将无效。
例子:

expandAlias("t rat")

-- don't echo the command
expandAlias("t rat", false)

feedTriggers

命令格式:
feedTriggers(text[, dataIsUtf8Encoded = true])
这个函数将让Mudlet解析给定的文本,就像它来自游戏一样–触发器测试是一个很好的应用。内置 `echo alias 也提供了此功能。
如果需要Mudlet 4.0之前的行为,请将此设置为false。大多数玩家都不需要这个。
从Mudlet 4.0开始,假设文本是UTF-8编码的。然后它将自动转换为当前选择的游戏服务器编码。
防止自动转换对于Mudlet开发人员进行测试非常有用,或者可能对于那些在Lua子系统中为Telnet协议创建处理程序的人来说,他们需要避免对单个协议字节进行转码,否则它们可能被视为扩展ASCII字符。
如果文本包含当前游戏服务器编码无法传达的字符,则返回true;如果文本包含当前游戏服务器编码无法传达的字符,则返回nil和错误消息。
例子:

-- try using this on the command line
`echo This is a sample line from the game

-- You can use \n to represent a new line - you also want to use it before and after the text you’re testing, like so:
feedTriggers("\nYou sit yourself down.\n")

-- The function also accept ANSI color codes that are used in games. A sample table can be found http://codeworld.wikidot.com/ansicolorcodes
feedTriggers("\nThis is \27[1;32mgreen\27[0;37m, \27[1;31mred\27[0;37m, \27[46mcyan background\27[0;37m," ..
"\27[32;47mwhite background and green foreground\27[0;37m.\n")

getCharacterName

命令格式:
getCharacterName()
返回输入到连接首选项表单的“字符名称”字段中的名称。可以用来找出可能需要在脚本中特别处理的名称或任何需要个性化给玩家的名称。如果没有设置,则该条目将返回一个空字符串。
例子:

-- cast glamor on yourself
send("cast 'glamor' " .. getCharacterName())

getConfig

命令格式:
getConfig([option])
返回类似于可以使用setConfig设置的配置选项。可以使用这一点来决定脚本是否应该通知用户建议的更改。
参数:
常规选项:
enableGMCP 启用GMCP 4.17
enableMSDP 启用MSDP 4.17
enableMSSP 启用MSSP 4.17
enableMSP 启用MSP 4.17
输入线选项:
inputLineStrictUnixEndings 使用严格UNIX行结尾发送命令的解决方法选项 4.17
主显示选项:
fixUnnecessaryLinebreaks 修复不必要的换行符从输出中删除额外的换行符(主要用于IRE服务器) 4.17
地图选项:
mapRoomSize 地图房间大小 4.17
mapExitSize 地图上出口的大小 4.17
mapRoundRooms 地图圆形房间 Draw rooms round or square将房间画成圆形或方形 4.17
showRoomIdsOnMap 显示所有房间的房间ID 4.17
show3dMapView 将地图显示为3D 4.17
mapperPanelVisible 地图面板底部的控件是否可见 4.17
mapShowRoomBorders 地图展示室边界为每个房间画一条细边框 4.17
特殊选项:
specialForceCompressionOff 解决方案选项禁用MCCP压缩,以防游戏服务器无法正常工作 4.17
specialForceGAOff 解决方案选项,用于禁用Telnet Go-Ahead,以防游戏服务器无法正常工作 4.17
specialForceCharsetNegotiationOff 解决方法选项,以禁用自动设置正确的编码,以防游戏服务器无法正常工作 4.17
specialForceMxpNegotiationOffspecialForceMxp 解决方案选项禁用MXP,以防游戏服务器无法正常工作 4.17
caretShortcutCaretShortcut 对于视力受损的玩家-获得在输入行和主窗口之间切换的键(可以是“none”,“tab”,“ctrltab”,“f6”) 4.17
blankLinesBehaviour空白线行为 针对视障玩家处理空行的选项(可以是“显示”、“隐藏”、“替换空格”) 4.17

例子:

getConfig()
-- Suggest enabling GMCP if it is unchecked
if not getConfig("enableGMCP") then
  echo("\nMy script works best with GMCP enabled. You may ")
  cechoLink("<red>click here", function() setConfig("enableGMCP",true) echo("GMCP enabled\n") end, "Enable GMCP", true)
  echo(" to enable it.\n")
end

getModulePath

命令格式:
path = getModulePath(module name)
返回模块在磁盘上的位置。如果给定的名称与已安装的模块不对应,它将返回 nil
例子:

getModulePath("mudlet-mapper")

getModulePriority

命令格式:
priority = getModulePriority(module name)
以整数形式返回模块的优先级。这决定了模块的加载顺序-默认值为0。例如,如果您有一个依赖于首先加载的另一个模块的模块,则很有用。
例子:

getModulePriority("mudlet-mapper")

getModules

命令格式:
getModules()
以表形式返回已安装的模块。
例子:

--Check if the module myTabChat is installed and if it isn't install it and enable sync on it
if not table.contains(getModules(),"myTabChat") then
  installModule(getMudletHomeDir().."/modules/myTabChat.xml")
  enableModuleSync("myTabChat")
end

getModuleInfo

命令格式:
getModuleInfo(moduleName, [info])
返回包含包Meta信息的表
例子:

getModuleInfo("myModule","author")

getModuleSync

命令格式:
getModuleSync(name)
如果模块同步不是活动的,返回false;如果是活动的,返回true;如果没有找到模块,返回nil。

getMudletHomeDir

命令格式:
getMudletHomeDir()
返回当前配置文件的当前主目录。这可用于存储数据、保存统计信息或从包加载资源文件。
注意:在Windows上故意使用正斜杠/作为分隔符,因为样式表需要它们。
例子:

-- save a table
table.save(getMudletHomeDir().."/myinfo.dat", myinfo)

-- or access package data. The forward slash works even on Windows fine
local path = getMudletHomeDir().."/mypackagename"

getMudletInfo

命令格式:
getMudletInfo()
打印有关您正在运行的Mudlet的调试信息-这对诊断很有用。

getMudletVersion

命令格式:
getMudletVersion(style)
返回当前Mudlet版本。请注意,如果您想查看函数是否存在,则不应该针对特定的Mudlet版本进行硬编码,而是检查函数本身是否存在。否则,如果您想测试一个损坏的函数之类的话,检查版本会派上用场。
例子:

-- see the full Mudlet version as text:
getMudletVersion("string")
-- returns for example "3.0.0-alpha"

-- check that the major Mudlet version is at least 3:
if getMudletVersion("major") >= 3 then echo("You're running on Mudlet 3+!") end
-- but mudletOlderThan() is much better for this:
if mudletOlderThan(3) then echo("You're running on Mudlet 3+!") end 

-- if you'd like to see if a function is available however, test for it explicitly instead:
if setAppStyleSheet then
  -- example credit to http://qt-project.org/doc/qt-4.8/stylesheet-examples.html#customizing-qscrollbar
  setAppStyleSheet[[
  QScrollBar:vertical {
      border: 2px solid grey;
      background: #32CC99;
      width: 15px;
      margin: 22px 0 22px 0;
  }
  QScrollBar::handle:vertical {
      background: white;
      min-height: 20px;
  }
  QScrollBar::add-line:vertical {
      border: 2px solid grey;
      background: #32CC99;
      height: 20px;
      subcontrol-position: bottom;
      subcontrol-origin: margin;
  }
  QScrollBar::sub-line:vertical {
      border: 2px solid grey;
      background: #32CC99;
      height: 20px;
      subcontrol-position: top;
      subcontrol-origin: margin;
  }
  QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {
      border: 2px solid grey;
      width: 3px;
      height: 3px;
      background: white;
  }
  QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
      background: none;
  }
  ]]
end

getNewIDManager

命令格式:
getNewIDManager()
返回一个IDManager对象,用于管理您自己的一组命名事件和计时器,这些事件和计时器与配置文件的其余部分隔离。
例子:

demonnic = demonnic or {}
demonnic.IDManager = getNewIDManager()
local idm = demonnic.IDManager
-- assumes you have defined demonnic.vitalsUpdate and demonnic.balanceChecker as functions
idm:registerEvent("DemonVitals", "gmcp.Char.Vitals", demonnic.vitalsUpdate)
idm:registerTimer("Balance Check", 1, demonnic.balanceChecker)
idm:stopEvent("DemonVitals")

getNamedEventHandlers

命令格式:
handlers = getNamedEventHandlers(userName)
以表的形式返回userName的所有命名事件处理程序名称的列表。
例子:

local handlers = getNamedEventHandlers()
  display(handlers)
  -- {}
  registerNamedEventHandler("Test1", "testEvent", "testFunction")
  registerNamedEventHandler("Test2", "someOtherEvent", myHandlerFunction)
  handlers = getNamedEventHandlers()
  display(handlers)
  -- { "Test1", "Test2" }

getOS

命令格式:
getOS()
返回操作系统(OS)的名称。对于仅在特定操作系统下应用特定脚本非常有用,例如仅在操作系统为Windows时应用样式表。
返回的文本将是以下内容之一:“windows”、“mac”、“Linux”,以及“cygwin”、“hurd”、“freebsd”、“kfreebsd”、“openbsd”、“netbsd”、“bsd4”、“unix”或“unknown”。
此外,返回操作系统的版本,如果使用Linux,则返回正在使用的发行版(从Mudlet 4.12+开始)。
例子:

display(getOS())
if getOS() == "windows" then
  echo("\nWindows OS detected.\n")
else
  echo("\nDetected Operating system is NOT windows.\n")
end

if mudlet.supports.osVersion then
  local os, osversion = getOS()
  print(f"Running {os} {osversion}")
end

getPackages

命令格式:
getPackages()
以表形式返回已安装的包。
例子:

--Check if the generic_mapper package is installed and if so uninstall it
if table.contains(getPackages(),"generic_mapper") then
  uninstallPackage("generic_mapper")
end

getPackageInfo

命令格式:
getPackageInfo(packageName, [info])
返回包含包Meta信息的表。
例子:

getPackageInfo("myPackage", "version")

getProfileName

命令格式:
getProfileName()
返回配置文件的名称。与之结合时有用 raiseGlobalEvent() 了解全球事件来自哪个配置文件。
例子:

echo(getProfileName())

getCommandSeparator

命令格式:
getCommandSeparator()
返回配置文件使用的命令分隔符。

getServerEncoding

命令格式:
getServerEncoding()
返回当前服务器数据编码

getServerEncodingsList

命令格式:
getServerEncodingsList()
返回服务器数据编码的索引列表
例子:

-- check if UTF-8 is available:
if table.contains(getServerEncodingsList(), "UTF-8") then
  print("UTF-8 is available!")
end

getWindowsCodepage

命令格式:
getWindowsCodepage()
返回当前你的Windows系统代码页
注意:此函数仅在Windows上工作-它仅在Mudlet内部需要,以使Lua能够使用非ASCII用户名(例如Iksiński,Jäger)为IO的目的。Linux和macOS可以很好地使用这些开箱即用。
例子:

print(getWindowsCodepage())

hfeedTriggers

命令格式:
hfeedTriggers(str)
与feedTriggers类似,但您可以使用十六进制的#RRGGBB添加颜色信息,类似于hecho。
例子:

hfeedTriggers("#008000,800000green on red#r reset\n")

installModule

命令格式:
hfeedTriggers(str)
将Mudlet XML、zip或mbpackage作为模块安装。
例子:

installModule([[C:\Documents and Settings\bub\Desktop\myalias.xml]])

installPackage

命令格式:
installPackage(location or url)
要安装的xml或包的确切位置。
例子:

installPackage([[C:\Documents and Settings\bub\Desktop\myalias.xml]])
installPackage([[https://github.com/Mudlet/Mudlet/blob/development/src/run-lua-code-v4.xml]])

killAnonymousEventHandler

命令格式:
killAnonymousEventHandler(handler id)
禁用并删除给定的事件处理程序。
例子:

-- registers an event handler that prints the first 5 GMCP events and then terminates itself

local counter = 0
local handlerId = registerAnonymousEventHandler("gmcp", function(_, origEvent)
  print(origEvent)
  counter = counter + 1
  if counter == 5 then
    killAnonymousEventHandler(handlerId)
  end
end)

loadMusicFile

命令格式:
loadMusicFile(settings table) or loadMusicFile(name, [url])
将音乐文件从Internet或本地文件系统加载到配置文件的“media”文件夹中,以便以后使用 playMusicFile() and 和 stopMusic().虽然文件可以直接加载在播放时间从 playMusicFile() loadMusicFile() 提供了提前加载文件的优点。
例子:

---- Table Parameter Syntax ----

-- Download from the Internet
loadMusicFile({
    name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"
    , url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"
})

-- OR download from the profile
loadMusicFile({name = getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3"})

-- OR download from the local file system
loadMusicFile({name = "C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3"})

---- Ordered Parameter Syntax of loadMusicFile(name[, url]) ----

-- Download from the Internet
loadMusicFile(
    "167124__patricia-mcmillen__rugby-club-in-spain.mp3"
    , "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"
)

-- OR download from the profile
loadMusicFile(getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3")

-- OR download from the local file system
loadMusicFile("C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3")

mudletOlderThan

命令格式:
mudletOlderThan(major, [minor], [patch])
如果Mudlet比要检查的给定版本旧,则返回true。如果您想使用一个无法轻易检查的特性,例如协程支持,这是非常有用的。但是,如果您想检查某个函数是否存在,请不要使用这个,而使用 if mudletfunction then - 它的可读性和可靠性会更高。
要检查的Mudlet主要版本。给定Mudlet版本3.0.1,3是主版本,第二个0是次版本,第三个1是补丁版本。
例子:

-- stop doing the script of Mudlet is older than 3.2
if mudletOlderThan(3,2) then return end

-- or older than 2.1.3
if mudletOlderThan(2, 1, 3) then return end

-- however, if you'd like to check that a certain function is available, like getMousePosition(), do this instead:
if not getMousePosition then return end

-- if you'd like to check that coroutines are supported, do this instead:
if not mudlet.supportscoroutines then return end

openWebPage

命令格式:
openWebPage(URL)
打开浏览器到给定网页。
例子:

openWebPage("http://google.com")
注意:此函数也可以通过使用“file:/”和文件路径而不是“http://”打开本地文件或文件夹。 

playMusicFile

命令格式:
playMusicFile(settings table)
打开浏览器到给定网页。
例子:

播放来自Internet或本地文件系统的音乐文件到配置文件的“media”文件夹,以便以后使用 stopMusic()。

playMusicFile

命令格式:
playMusicFile(settings table)
播放来自Internet或本地文件系统的音乐文件到配置文件的“media”文件夹,以便以后使用 stopMusic()。
Required 需 Key 关键 Value 值 Default 默认 Purpose 目的
Yes 是的 name 名称 <file name>
No 没有 volume 音量 1 to 100 1至100 50 No 没有 fadein fadeIn <msec> No 没有 fadeout <msec> No 没有 start 开始 <msec> 0 No 没有 loops 环 -1, or >= 1 -1或>= 1 1 No 没有 key 关键 <key> No 没有 tag 标签 <tag> No 没有 continue 继续 true or false true或false true 真 Maybe 也许 url URL <url>

name:
媒体文件的名称。
可能包含目录信息(即weather/lightning.wav)。
可以是配置文件的一部分(即getMudletHomeDir()..“/cow.mp3”)
可以在本地设备上(即“C:/Users/YourNameHere/Documents/nevergoingtogiveyouup.mp3”)
通配符 * 和?可以在名称内使用以随机化媒体文件选择。
volume:
相对于播放器客户端上设置的音量。
fadein:
音量增加或淡入,范围从一个线性模式到使用“音量”键设置的音量。
起始位置:媒体开始。
结束位置:介质开始加上指定的毫秒数(msec)。
1000毫秒= 1秒。
fadeout:
音量减少或淡出,范围从使用“音量”键设置的音量到1的线性模式。
起始位置:介质结束减去指定的毫秒数(msec)。
结束位置:媒体结束。
1000毫秒= 1秒。
start:
以毫秒为单位在指定位置开始播放。
loops:
媒体播放的迭代次数。
值-1允许介质无限期循环。
key:
唯一地标识媒体文件的“密钥”,该密钥绑定到它们的“名称”或“url”。
在播放该媒体时,停止播放具有相同“密钥”但具有不同“名称”或“url”的当前媒体文件。
tag:
帮助 分类 媒介 。
continue:
为true时继续播放匹配的新音乐文件。
如果为false,则重新开始匹配新的音乐文件。
url:
可以下载媒体文件的资源位置。
仅当要远程下载文件时才需要。

例子:

---- Table Parameter Syntax ----

-- Play a music file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)
playMusicFile({
    name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"
})

-- OR copy once from the game's profile, and play a music file stored in the profile's media directory
---- [volume] of 75 (1 to 100)
playMusicFile({
    name = getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3"
    , volume = 75
})

-- OR copy once from the local file system, and play a music file stored in the profile's media directory
---- [volume] of 75 (1 to 100)
playMusicFile({
    name = "C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3"
    , volume = 75
})

-- OR download once from the Internet, and play music stored in the profile's media directory
---- [fadein] and increase the volume from 1 at the start position to default volume up until the position of 20 seconds
---- [fadeout] and decrease the volume from default volume to one, 53 seconds from the end of the music
---- [start] 10 seconds after position 0 (fadein scales its volume increase over a shorter duration, too)
---- [key] reference of "rugby" for stopping this unique music later
---- [tag] reference of "ambience" to stop and music later with the same tag
---- [continue] playing this music if another request for the same music comes in (false restarts it) 
---- [url] to download once from the Internet if the music does not exist in the profile's media directory
playMusicFile({
    name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"
    , volume = nil -- nil lines are optional, no need to use
    , fadein = 20000
    , fadeout = 53000
    , start = 10000
    , loops = nil -- nil lines are optional, no need to use
    , key = "rugby"
    , tag = "ambience"
    , continue = true
    , url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"
})

---- Ordered Parameter Syntax of playMusicFile(name[,volume][,fadein][,fadeout][,loops][,key][,tag][,continue][,url]) ----

-- Play a music file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)
playMusicFile(
    "167124__patricia-mcmillen__rugby-club-in-spain.mp3"  -- name
)

-- OR copy once from the game's profile, and play a music file stored in the profile's media directory
---- [volume] of 75 (1 to 100)
playMusicFile(
    getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name
    , 75 -- volume
)

-- OR copy once from the local file system, and play a music file stored in the profile's media directory
---- [volume] of 75 (1 to 100)
playMusicFile(
    "C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name
    , 75 -- volume
)

-- OR download once from the Internet, and play music stored in the profile's media directory
---- [fadein] and increase the volume from 1 at the start position to default volume up until the position of 20 seconds
---- [fadeout] and decrease the volume from default volume to one, 53 seconds from the end of the music
---- [start] 10 seconds after position 0 (fadein scales its volume increase over a shorter duration, too)
---- [key] reference of "rugby" for stopping this unique music later
---- [tag] reference of "ambience" to stop and music later with the same tag
---- [continue] playing this music if another request for the same music comes in (false restarts it) 
---- [url] to download once from the Internet if the music does not exist in the profile's media directory
playMusicFile(
    "167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name
    , nil -- volume
    , 20000 -- fadein
    , 53000 -- fadeout
    , 10000 -- start
    , nil -- loops
    , "rugby" -- key 
    , "ambience" -- tag
    , true -- continue
    , "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/" -- url
)

playSoundFile

命令格式:
playSoundFile(settings table)
将声音文件从Internet或本地文件系统播放到配置文件的“media”文件夹,以便以后使用 stopSounds()。
例子:

playSoundFile({
    name = "cow.wav"
})

-- OR copy once from the game's profile, and play a sound file stored in the profile's media directory
---- [volume] of 75 (1 to 100)
playSoundFile({
    name = getMudletHomeDir().. "/cow.wav"
    , volume = 75
})

-- OR copy once from the local file system, and play a sound file stored in the profile's media directory
---- [volume] of 75 (1 to 100)
playSoundFile({
    name = "C:/Users/Tamarindo/Documents/cow.wav"
    , volume = 75
})

-- OR download once from the Internet, and play a sound stored in the profile's media directory
---- [volume] of 75
---- [loops] of 2 (-1 for indefinite repeats, 1+ for finite repeats)
---- [key] reference of "cow" for stopping this unique sound later
---- [tag] reference of "animals" to stop a group of sounds later with the same tag
---- [priority] of 25 (1 to 100, 50 default, a sound with a higher priority would stop this one)
---- [url] to download once from the Internet if the sound does not exist in the profile's media directory
playSoundFile({
    name = "cow.wav"
    , volume = 75
    , fadein = nil -- nil lines are optional, no need to use
    , fadeout = nil -- nil lines are optional, no need to use
    , start = nil -- nil lines are optional, no need to use
    , loops = 2
    , key = "cow"
    , tag = "animals"
    , priority = 25
    , url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"
})

---- Ordered Parameter Syntax of playSoundFile(name[,volume][,fadein][,fadeout][,loops][,key][,tag][,priority][,url]) ----

-- Play a sound file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)
playSoundFile(
    "cow.wav" -- name
)

-- OR copy once from the game's profile, and play a sound file stored in the profile's media directory
---- [volume] of 75 (1 to 100)
playSoundFile(
    getMudletHomeDir().. "/cow.wav" -- name
    , 75 -- volume
)

-- OR copy once from the local file system, and play a sound file stored in the profile's media directory
---- [volume] of 75 (1 to 100)
playSoundFile(
    "C:/Users/Tamarindo/Documents/cow.wav" -- name
    , 75 -- volume
)

-- OR download once from the Internet, and play a sound stored in the profile's media directory
---- [volume] of 75
---- [loops] of 2 (-1 for indefinite repeats, 1+ for finite repeats)
---- [key] reference of "cow" for stopping this unique sound later
---- [tag] reference of "animals" to stop a group of sounds later with the same tag
---- [priority] of 25 (1 to 100, 50 default, a sound with a higher priority would stop this one)
---- [url] to download once from the Internet if the sound does not exist in the profile's media directory
playSoundFile(
    "cow.wav" -- name
    , 75 -- volume
    , nil -- fadein
    , nil -- fadeout
    , nil -- start
    , 2 -- loops
    , "cow" -- key 
    , "animals" -- tag
    , 25 -- priority
    , "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/" -- url
)

purgeMediaCache

命令格式:
purgeMediaCache()
清除存储在给定Mudlet配置文件(MCMP和MSP协议使用的介质)内的介质缓存中的所有介质文件。当游戏开发者更新其游戏上的媒体文件时,这使得配置文件内的媒体文件夹能够被清除,以便媒体文件可以刷新到最新的更新。
例子:

lua purgeMediaCache()
为给定的配置文件分发触发器、按钮或其他可编写脚本的特性,以调用purgeMediaCache()

receiveMSP

命令格式:
receiveMSP()
receiveMSP(command)
接收MSP
例子:

--Play a cow.wav media file stored in the media folder of the current profile. The sound would play twice at a normal volume.
receiveMSP("!!SOUND(cow.wav L=2 V=50)")

--Stop any SOUND media files playing stored in the media folder of the current profile.
receiveMSP("!!SOUND(Off)")

--Play a city.mp3 media file stored in the media folder of the current profile. The music would play once at a low volume.
--The music would continue playing if it was triggered earlier by another room, perhaps in the same area.
receiveMSP([[!!MUSIC(city.mp3 L=1 V=25 C=1)]])

--Stop any MUSIC media files playing stored in the media folder of the current profile.
receiveMSP("!!MUSIC(Off)")

registerAnonymousEventHandler

命令格式:
registerAnonymousEventHandler(event name, functionReference, [one shot])
将函数注册到事件处理程序,而不需要通过脚本设置。 这里看到查看Mudlet引发的事件, 列表函数可以通过名称作为包含全局函数名的字符串来引用,或者通过lua函数对象本身来引用。
如果用星号 (“*”) 作为事件名称,代码将捕获所有事件。用于调试或与外部程序集成。

注:直接引用lua函数的能力,one shot参数和返回的ID是Mudlet 3.5及以上版本的特性。
例子:

-- example taken from the God Wars 2 (http://godwars2.org) Mudlet UI - forces the window to keep to a certain size
function keepStaticSize()
  setMainWindowSize(1280,720)
end -- keepStaticSize

if keepStaticSizeEventHandlerID then killAnonymousEventHandler(keepStaticSizeEventHandlerID) end -- clean up any already registered handlers for this function
keepStatisSizeEventHandlerID = registerAnonymousEventHandler("sysWindowResizeEvent", "keepStaticSize") -- register the event handler and save the ID for later killing

-- simple inventory tracker for GMCP enabled games. This version does not leak any of the methods
-- or tables into the global namespace. If you want to access it, you should export the inventory
-- table via an own namespace.
local inventory = {}

local function inventoryAdd()
  if gmcp.Char.Items.Add.location == "inv" then
    inventory[#inventory + 1] = table.deepcopy(gmcp.Char.Items.Add.item)
  end
end
if inventoryAddHandlerID then killAnonymousEventHandler(inventoryAddHandlerID) end -- clean up any already registered handlers for this function
inventoryAddHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.Add", inventoryAdd) -- register the event handler and save the ID for later killing

local function inventoryList()
  if gmcp.Char.Items.List.location == "inv" then
    inventory = table.deepcopy(gmcp.Char.Items.List.items)
  end
end
if inventoryListHandlerID then killAnonymousEventHandler(inventoryListHandlerID) end -- clean up any already registered handlers for this function
inventoryListHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.List", inventoryList) -- register the event handler and save the ID for later killing

local function inventoryUpdate()
  if gmcp.Char.Items.Remove.location == "inv" then
    local found
    local updatedItem = gmcp.Char.Items.Update.item
    for index, item in ipairs(inventory) do
      if item.id == updatedItem.id then
        found = index
        break
      end
    end
    if found then
      inventory[found] = table.deepcopy(updatedItem)
    end
  end
end
if inventoryUpdateHandlerID then killAnonymousEventHandler(inventoryUpdateHandlerID) end -- clean up any already registered handlers for this function
inventoryUpdateHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.Update", inventoryUpdate)

local function inventoryRemove()
  if gmcp.Char.Items.Remove.location == "inv" then
    local found
    local removedItem = gmcp.Char.Items.Remove.item
    for index, item in ipairs(inventory) do
      if item.id == removedItem.id then
        found = index
        break
      end
    end
    if found then
      table.remove(inventory, found)
    end
  end
end
if inventoryRemoveHandlerID then killAnonymousEventHandler(inventoryRemoveHandlerID) end -- clean up any already registered handlers for this function
inventoryRemoveHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.Remove", inventoryRemove)

-- downloads a package from the internet and kills itself after it is installed.
local saveto = getMudletHomeDir().."/dark-theme-mudlet.zip"
local url = "http://www.mudlet.org/wp-content/files/dark-theme-mudlet.zip"

if myPackageInstallHandler then killAnonymousEventHandler(myPackageInstallHandler) end
myPackageInstallHandler = registerAnonymousEventHandler(
  "sysDownloadDone",
  function(_, filename)
    if filename ~= saveto then
      return true -- keep the event handler since this was not our file
    end
    installPackage(saveto)
    os.remove(b)
  end,
  true
)

downloadFile(saveto, url)
cecho("<white>Downloading <green>"..url.."<white> to <green>"..saveto.."\n")

registerNamedEventHandler

命令格式:
success = registerNamedEventHandler(userName, handlerName, eventName, functionReference, [oneShot])
使用名称handlerName注册命名事件处理程序。与匿名事件处理程序不同,命名事件处理程序受到保护,不会重复,并且可以停止和恢复。每个userName保留单独的列表

参数: oneShot: 如果为true,则事件处理程序在引发事件时只触发一次。如果你需要扩展一个一次性事件处理程序来进行“再来一次检查”,你可以让处理程序返回true,并且它会一直触发直到函数不返回true。

例子:

-- register a named event handler. Will call demonVitalsHandler(eventName, ...) when gmcp.Char.Vitals is raised.
local ok = registerNamedEventHandler("Demonnic", "DemonVitals", "gmcp.Char.Vitals", "demonVitalsHandler")
if ok then
  cecho("Vitals handler switched to demonVitalsHandler")
end

-- something changes later, and we want to handle vitals with another function, demonBlackoutHandler()
-- note we do not use "" around demonBlackoutHandler but instead pass the function itself. Both work.
-- using the same handlerName ("DemonVitals") means it will automatically unregister the old handler
-- and reregister it using the new information.
local ok = registerNamedEventHandler("Demonnic", "DemonVitals", "gmcp.Char.Vitals", demonBlackoutHandler)
if ok then
  cecho("Vitals handler switched to demonBlackoutHandler")
end

-- Now you want to check your inventory, but you only want to do it once, so you pass the optional oneShot as true
local function handleInv()
  local list = gmcp.Char.Items.List
  if list.location ~= "inventory" then
    return true -- if list.location is, say "room" then we need to keep responding until it's "inventory"
  end
  display(list.items) -- you would probably store values and update displays or something, but here I'll just show the data as it comes in
end

-- you can ignore the response from registerNamedEventHandler if you want, it's always going to be true
-- unless there is an error, in which case it throws the error and halts execution anyway. The return is
-- in part for feedback when using the lua alias or other REPL window.
registerNamedEventHandler("Demonnic", "DemonInvCheck", "gmcp.Char.Items.List", handleInv, true)

reloadModule

命令格式:
reloadModule(module name)
重新加载模块(通过卸载和重新安装)。
例子:

reloadModule("3k-mapper")

removeFileWatch

命令格式:
removeFileWatch(path)
删除目录或文件上的文件监视。文件中的每一个更改都不会再引发 sysPathChanged event. 活动
例子:

herbs = {}
local herbsPath = getMudletHomeDir() .. "/herbs.lua"
function herbsChangedHandler(_, path)
  if path == herbsPath then
    table.load(herbsPath, herbs)
    removeFileWatch(herbsPath)
  end
end

addFileWatch(herbsPath)
registerAnonymousEventHandler("sysPathChanged", "herbsChangedHandler")

resetProfile

命令格式:
resetProfile()
重新加载您的整个Mudlet个人资料-就像您刚刚打开它一样。所有的UI元素都将被清除,所以这在编写UI代码时很有用。
注意:不要将resetProfile()放在脚本编辑器的脚本项中,因为脚本也将被resetProfile()重新加载

resumeNamedEventHandler

命令格式:
success = resumeNamedEventHandler(userName, handlerName)
恢复名为handlerName的命名事件处理程序,并使其再次开始激发。
例子:

local resumed = resumeNamedEventHandler("Demonnic", "DemonVitals")
if resumed then
  cecho("DemonVitals resumed!")
else
  cecho("DemonVitals doesn't exist, cannot resume it")
end

saveProfile

命令格式:
saveProfile()
saveProfile(location)
将当前Mudlet配置文件保存到磁盘,这相当于按下“保存配置文件”按钮。

sendSocket

命令格式:
sendSocket(data)
将给定的二进制数据按原样发送给游戏。您可以使用此选项来实现对新telnet协议, simultronics login or etcetera. 或者其他的。
注意:请记住,如果有必要将字节值255作为数据字节发送,而不是作为TelnetIAC值发送,则需要重复发送,以便Telnet忽略它,而不是将其视为后者。

例子:

TN_IAC = 255
TN_WILL = 251
TN_DO = 253
TN_SB = 250
TN_SE = 240
TN_MSDP = 69

MSDP_VAL = 1
MSDP_VAR = 2

sendSocket( string.char( TN_IAC, TN_DO, TN_MSDP ) ) -- sends IAC DO MSDP

--sends: IAC  SB MSDP MSDP_VAR "LIST" MSDP_VAL "COMMANDS" IAC SE
local msg = string.char( TN_IAC, TN_SB, TN_MSDP, MSDP_VAR ) .. " LIST " ..string.char( MSDP_VAL ) .. " COMMANDS " .. string.char( TN_IAC, TN_SE )
sendSocket( msg )

setConfig

命令格式:
setConfig(option, value)
将Mudlet选项设置为特定值。

参数:
常规选项:
enableGMCP 启用GMCP 4.16
enableMSDP 启用MSDP 4.16
enableMSSP 启用MSSP 4.16
enableMSP 启用MSP 4.16
compactInputLine 隐藏搜索,时间戳,其他按钮和标签的右下角输入行 4.17 输入线选项:
inputLineStrictUnixEndings 使用严格UNIX行结尾发送命令的解决方法选项 4.16
主显示选项:
fixUnnecessaryLinebreaks 修复不必要的换行符从输出中删除额外的换行符(主要用于IRE服务器) 4.16
地图选项:
mapRoomSize 地图房间大小 4.16
mapExitSize 地图上出口的大小 4.16
mapRoundRooms 地图圆形房间 Draw rooms round or square将房间画成圆形或方形 4.16
showRoomIdsOnMap 显示所有房间的房间ID 4.16
showMapInfo 地图覆盖文本(“完整”、“短”或任何自定义文本。地图可以一次显示多个) hideMapInfo 地图覆盖文本(“完整”、“短”或任何自定义文本。分别隐藏每个信息以隐藏全部) show3dMapView 将地图显示为3D 4.16
mapperPanelVisible 地图面板可见底部的控件是否可见 4.16
mapShowRoomBorders 地图展示室边界为每个房间画一条细边框 4.16
特殊选项:
specialForceCompressionOff 解决方案选项禁用MCCP压缩,以防游戏服务器无法正常工作 4.16
specialForceGAOff 解决方案选项,用于禁用Telnet Go-Ahead,以防游戏服务器无法正常工作 4.16
specialForceCharsetNegotiationOff 解决方法选项,以禁用自动设置正确的编码,以防游戏服务器无法正常工作 4.16
specialForceMxpNegotiationOffspecialForceMxp 解决方案选项禁用MXP,以防游戏服务器无法正常工作 4.16
caretShortcutCaretShortcut 对于视力受损的玩家-获得在输入行和主窗口之间切换的键(可以是“none”,“tab”,“ctrltab”,“f6”) 4.16
blankLinesBehaviour空白线行为 针对视障玩家处理空行的选项(可以是“显示”、“隐藏”、“替换空格”) 4.16

例子:

setConfig("mapRoomSize", 5)

setConfig({mapRoomSize = 6, mapExitSize = 12})

setMergeTables

命令格式:
setMergeTables(module)
使Mudlet合并给定GMCP或MSDP模块的表,而不是覆盖数据。如果游戏只发送部分更新,需要将全部数据合并,则这是有用的。默认情况下,“Char.Status”是唯一的合并模块。
例子:

setMergeTables("Char.Skills", "Char.Vitals")

setModuleInfo

命令格式:
setModuleInfo(moduleName, info, value)
设置模块的特定Meta信息值
例子:

setModuleInfo("myModule", "version", "1.0")

setModulePriority

命令格式:
setModulePriority(moduleName, priority)
将给定模块的模块优先级设置为数字-模块优先级确定模块的加载顺序,如果您有相互依赖的模块,这将很有帮助。这也可以从模块管理器窗口设置。

setPackageInfo

命令格式:
setPackageInfo(packageName, info, value)
设置包的特定Meta信息值
例子:

setPackageInfo("myPackage", "title", "This is my test package")

setServerEncoding

命令格式:
setServerEncoding(encoding)
设置编码
例子:

-- use UTF-8 if Mudlet knows it. Unfortunately there's no way to check if the game's server knows it too.
if table.contains(getServerEncodingsList(), "UTF-8") then
  setServerEncoding("UTF-8")
end

showNotification

命令格式:
showNotification(title, [content], [expiryTimeInSeconds]) 显示本机(系统)通知。
注意:这可能不适用于所有系统,这取决于系统。
参数

  title-纯文本通知标题
  content-可选参数,纯文本通知内容,如果省略title参数,也将用作内容
  expiryTimeInSeconds-可选参数,以秒为单位设置通知到期时间,操作系统经常忽略

例子:

showNotification("Notification title", "Notification content", 5)

spawn

命令格式:
spawn(readFunction, processToSpawn[, …arguments]) 生成一个进程并打开一个与之通信的链接 是您希望用于从进程阅读输出的函数,以及是一个包含特定于此连接的函数的表- send(data), true/false = isRunning(), and close().
这允许您设置与另一个进程的RPC通信。
例子:

-- simple example on a program that quits right away, but prints whatever it gets using the 'display' function
local f = spawn(display, "ls")
display(f.isRunning())
f.close()

local f = spawn(display, "ls", "-la")
display(f.isRunning())
f.close()

startLogging

命令格式:
startLogging(state)
控制将主控制台文本记录为文本或HTML(由“配置文件首选项”或“设置”对话框的“常规”选项卡上的“以HTML格式保存日志文件而非纯文本”设置指定)。 尽管被称为startLogging,它也可以停止进程并正确关闭正在创建的文件。文件的扩展名为“.txt”或“.html”(视情况而定),名称将采用日期/时间“yyyy-MM-dd#hh-mm-ss”(使用日志记录开始时的时间/日期)的形式。 请注意,此控件与配置文件“底部按钮”中的相应图标平行,该按钮也可以启动和停止相同的日志记录过程,并反映状态。
例子:

-- start logging
local success, message, filename, code = startLogging(true)
if code == 1 or code == -1 then print(f"Started logging to {filename}") end

-- stop logging
startLogging(false)

stopAllNamedEventHandlers

命令格式:
stopAllNamedEventHandlers(userName)
停止所有命名事件处理程序并防止它们再激发。信息被保留,处理程序可以被恢复。

stopMusic

命令格式:
stopMusic(settings table)
停止所有或特定音乐。

---- Table Parameter Syntax ----

-- Stop all playing music files for this profile associated with the API
stopMusic()

-- Stop playing the rugby mp3 by name
stopMusic({name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"})

-- Stop playing the unique sound identified as "rugby"
stopMusic({
    name = nil  -- nil lines are optional, no need to use
    , key = "rugby" -- key
    , tag = nil  -- nil lines are optional, no need to use
})

---- Ordered Parameter Syntax of stopMusic([name][,key][,tag]) ----

-- Stop all playing music files for this profile associated with the API
stopMusic()

-- Stop playing the rugby mp3 by name
stopMusic("167124__patricia-mcmillen__rugby-club-in-spain.mp3")

-- Stop playing the unique sound identified as "rugby"
stopMusic(
    nil -- name
    , "rugby" -- key
    , nil -- tag
)

stopNamedEventHandler

命令格式:
success = stopNamedEventHandler(userName, handlerName)
停止名为handlerName的命名事件处理程序,并防止其再次激发。信息被存储,因此如果需要,可以稍后恢复。
例子:

local stopped = stopNamedEventHandler("DemonVitals")
if stopped then
  cecho("DemonVitals stopped!")
else
  cecho("DemonVitals doesn't exist or already stopped; either way it won't fire any more.")
end

stopSounds

命令格式:
stopSounds(settings table)
停止所有或特定声音。

-- Stop all playing sound files for this profile associated with the API
stopSounds()

-- Stop playing the cow sound
stopSounds({name = "cow.wav"})

-- Stop playing any sounds tagged as "animals" with a priority less than or equal to 50
---- This would not stop sounds tagged as "animals" greater than priority 50.  This is an "AND" and not an "OR".
stopSounds({
    name = nil -- nil lines are optional, no need to use
    , key = nil -- nil lines are optional, no need to use
    , tag = "animals"
    , priority = 50
})

---- Ordered Parameter Syntax of stopSounds([name][,key][,tag][,priority]) ----

-- Stop all playing sound files for this profile associated with the API
stopSounds()

-- Stop playing the cow sound
stopSounds("cow.wav")

-- Stop playing any sounds tagged as "animals" with a priority less than or equal to 50
---- This would not stop sounds tagged as "animals" greater than priority 50.  This is an "AND" and not an "OR".
stopSounds(
    nil -- name
    , nil -- key
    , "animals" -- tag
    , 50 -- priority
)

timeframe

命令格式:
timeframe(vname, true_time, nil_time, …)
一个实用函数,可以帮助您在不使用大量tempTimer的情况下更改和跟踪变量状态。
例子:

-- sets the global 'limiter' variable to true immediately (see the 0) and back to nil in one second (that's the 1).
timeframe("limiter", 0, 1)

-- An angry variable 'giant' immediately set to "fee", followed every second after by "fi", "fo", and "fum" before being reset to nil at four seconds.
timeframe("giant", {0, "fee"}, 4, {1, "fi"}, {2, "fo"}, {3, "fum"})

-- sets the local 'width' variable to true immediately and back to nil in one second.
local width
timeframe(function(value) width = value end, 0, 1)

translateTable

命令格式:
uninstallModule(name)
翻译方向表
例子:

-- get the path from room 2 to room 5 and translate directions
if getPath(2, 5) then
speedWalkDir = translateTable(speedWalkDir)
print("Translated directions:")
display(speedWalkDir)

uninstallModule

命令格式:
uninstallModule(name)
卸载具有给定名称的Mudlet模块。
例子:

uninstallModule("myalias")

uninstallPackage

命令格式:
uninstallPackage(name)
卸载具有给定名称的Mudlet包。
例子:

uninstallPackage("myalias")

unzipAsync

命令格式:
unzipAsync(name)
解压缩路径中的zip文件,将内容解压缩到提供的位置。如果可以开始解压缩,返回true;如果不能,返回nil+message。
如果解压缩成功,则将zip文件位置和解压缩到的位置作为参数引发sysUnzipDone事件,如果解压缩成功,则将使用相同参数引发sysUnzipError事件。
不要使用unzip()函数,因为它是同步的,会影响Mudlet的性能(即,解压缩时冻结Mudlet)。
例子:

function handleUnzipEvents(event, ...)
  local args = {...}
  local zipName = args[1]
  local unzipLocation = args[2]
  if event == "sysUnzipDone" then
    cecho(string.format("<green>Unzip successful! Unzipped %s to %s\n", zipName, unzipLocation))
  elseif event == "sysUnzipError" then
    cecho(string.format("<firebrick>Unzip failed! Tried to unzip %s to %s\n", zipName, unzipLocation))
  end
end
if unzipSuccessHandler then killAnonymousEventHandler(unzipSuccessHandler) end
if unzipFailureHandler then killAnonymousEventHandler(unzipFailureHandler) end
unzipSuccessHandler = registerAnonymousEventHandler("sysUnzipDone", "handleUnzipEvents")
unzipFailureHandler = registerAnonymousEventHandler("sysUnzipError", "handleUnzipEvents")
--use the path to your zip file for this, not mine
local zipFileLocation = "/home/demonnic/Downloads/Junkyard_Orc.zip" 
--directory to unzip to, it does not need to exist but you do need to be able to create it
local unzipLocation = "/home/demonnic/Downloads/Junkyard_Orcs" 
unzipAsync(zipFileLocation, unzipLocation) -- this will work
unzipAsync(zipFileLocation .. "s", unzipLocation) --demonstrate error, will happen first because unzipping takes time

yajl.to_string

命令格式:
yajl.to_string(data)
将Lua表编码为JSON数据,并将其作为字符串返回。这个函数非常高效–如果你需要编码成JSON,请使用这个。
例子:

sendGMCP("Char.Skills.Get "..yajl.to_string{group = "combat"})
-- you can also use it to convert a Lua table into a string, so you can, for example, store it as room's userdata
local toserialize = yajl.to_string(continents)
setRoomUserData(1, "areaContinents", toserialize)

yajl.to_value

命令格式:
yajl.to_value(data)
将JSON数据(作为字符串)解码为Lua表。这个函数非常高效–如果你需要将代码解编码为JSON,请使用这个函数。
例子:

-- given the serialization example above with yajl.to_string, you can deserialize room userdata back into a table
local tmp = getRoomUserData(1, "areaContinents")
if tmp == "" then return end

local continents = yajl.to_value(tmp)
display(continents)

Mudlet对象函数

用于操作Mudlet脚本对象的函数集合-触发器、别名等等。

addCmdLineSuggestion

命令格式:
addCmdLineSuggestion([name], suggestion)
为指定命令行添加制表符完成建议。
参数:
name:可选的命令行名称,如果跳过主命令行,则使用
suggestion: 建议作为单个单词添加到选项卡完成(仅允许以下内容:0 -9A-Za-z_)
例子:

addCmdLineSuggestion("help")

local suggestions = {"Pneumonoultramicroscopicsilicovolcanoconiosis", "supercalifragilisticexpialidocious", "serendipitous"}
for _, suggestion in ipairs(suggestions) do
  addCmdLineSuggestion(suggestion)
end

adjustStopWatch

命令格式:
adjustStopWatch(watchID/watchName, amount)
按时间量向前或向后调整秒表上经过的时间。它甚至可以在不运行的秒表上工作,并且因此可以用于用负量预设新创建的秒表,使得它在预设时间从负时间朝零运行。
参数:
watchID:你得到的秒表ID
amount: (十进制数):以秒为单位的调整秒表的量,正数增加记录的经过时间。
返回 如果找到秒表并因此调整成功,则为true;如果没有,则为nil并显示错误消息。 例子:任务计时的例子

function mission(time)
  local missionTimeTable = missionTimeTable or {}

  if createStopWatch("missionStopWatch") then
    adjustStopWatch("missionStopWatch", -tonumber(time))
    setStopWatchPersistence("missionStopWatch", true)
    missionTimeTable = getStopWatchBrokenDownTime("missionStopWatch")

    echo(string.format("Get cracking, you have %02i:%02i:%02i hg:m:s left.\n", missionTimeTable.hours, missionTimeTable.minutes, missionTimeTable.seconds))
    startStopWatch("missionStopWatch")
  else
    -- it already exists, so instead report what is/was the time on it
    --[=[ We know that the stop watch exists - we just need to find the ID
      so we can get the running detail which is only available from the getStopWatches()
      table and that is indexed by ID]=]
    for k,v in pairs(getStopWatches()) do
      if v.name == "missionStopWatch" then
        missionTimeTable = v
      end
    end
    if missionTimeTable.isRunning then
      if missionTimeTable.elapsedTime.negative then
        echo(string.format("Better hurry up, the clock is ticking on an existing mission and you only have %02i:%02i:%02i h:m:s left.\n", missionTimeTable.elapsedTime.hours, missionTimeTable.elapsedTime.minutes, missionTimeTable.elapsedTime.seconds))
      else
        echo(string.format("Bad news, you are past the deadline on an existing mission by %02i:%02i:%02i h:m:s !\n", missionTimeTable.elapsedTime.hours, missionTimeTable.elapsedTime.minutes, missionTimeTable.elapsedTime.seconds))
      end
    else
      if missionTimeTable.elapsedTime.negative then
        echo(string.format("Well done! You have already completed a mission %02i:%02i:%02i h:m:s before the deadline ...\n", missionTimeTable.elapsedTime.hours, missionTimeTable.elapsedTime.minutes, missionTimeTable.elapsedTime.seconds))
      else
        echo(string.format("Uh oh! You failed to meet the deadline on an existing mission by %02i:%02i:%02i h:m:s !\n", missionTimeTable.elapsedTime.hours, missionTimeTable.elapsedTime.minutes, missionTimeTable.elapsedTime.seconds))
      end
    end
  end
end


-- in use:
lua mission(60*60)
Get cracking, you have 01:00:00 h:m:s left.

lua mission(60*60)
Better hurry up, the clock is ticking on an existing mission and you only have 00:59:52 h:m:s left.

appendScript

命令格式:
appendScript(scriptName, luaCode, [occurrence])
将Lua代码追加到脚本“scriptName”。如果没有出现,则设置第一个找到的脚本的代码。
返回该脚本的唯一ID号。
参数: scriptName:脚本的名称 luaCode:要追加的luaCode脚本 occurence: (可选)脚本的出现,以防有许多同名脚本

在Mudlet中可用4.8+

例子:

-- an example of appending the script lua code to the first occurrence of "testscript"
appendScript("testscript", [[echo("This is a test\n")]], 1)

appendCmdLine

命令格式:
appendCmdLine([name], text)
将文本追加到主输入行。
参数:
name:(可选)命令行名称。如果没有给出,文本将被附加到主命令行。
text: 要追加的文本
例子:

-- adds the text "55 backpacks" to whatever is currently in the input line
appendCmdLine("55 backpacks")

-- makes a link, that when clicked, will add "55 backpacks" to the input line
echoLink("press me", "appendCmdLine'55 backpack'", "Press me!")

clearCmdLine

命令格式:
clearCmdLine([name])
清除输入行中已输入的任何文本。
参数:
name:(可选)命令行名称。如果没有给出,主命令行的文本将被清除。

clearCmdLineSuggestions

命令格式:
clearCmdLineSuggestions([name])
清除命令行的所有建议。
参数:
name:(可选)命令行名称。如果没有给出,则主命令行的建议将被清除。

createStopWatch

命令格式:
createStopWatch([name], [start immediately])
createStopWatch([start immediately])
在Mudlet 4.4.0之前:
createStopWatch()
此功能可创建秒表,一种高分辨率时间测量工具。秒表可以启动、停止、重置、询问秒表启动后已经过去了多长时间。
秒表在创建时会自动启动
参数:
name(字符串)用于标识秒表的唯一文本。
返回 秒表的ID(编号) 例子:

fightStopWatch = fightStopWatch or createStopWatch() -- create, or re-use a stopwatch, and store the watchID in a global variable to access it from anywhere

-- then you can start the stop watch in some trigger/alias/script with:
startStopWatch(fightStopWatch)

-- to stop the watch and measure its time in e.g. a trigger script you can write:
fightTime = stopStopWatch(fightStopWatch)
echo("The fight lasted for " .. fightTime .. " seconds.")
resetStopWatch(fightStopWatch)

    (From Mudlet 4.4.0) in a global script you can create all stop watches that you need in your system with unique names:
    (From Mudlet 4.4.0)在全局脚本中,您可以在系统中创建所有需要的秒表,并具有唯一的名称:

createStopWatch("fightStopWatch") -- creates the stopwatch or returns nil+msg if it already exists

-- then you can start the stop watch (if it is not already started) in some trigger/alias/script with:
startStopWatch("fightStopWatch")

-- to stop the watch and measure its time in e.g. a trigger script you can write:
fightTime = stopStopWatch("fightStopWatch")
echo("The fight lasted for " .. fightTime .. " seconds.")
resetStopWatch("fightStopWatch")

注意:如果Mudlet 4.4.0之前的版本可以重复使用秒表ID,因为它们不能被删除,所以创建越来越多会占用更多的内存。从4.4.0开始,修改后的内部设计已更改,因此没有为每个秒表创建内部计时器-而是根据秒表是运行还是停止使用时间戳或固定的经过时间记录,以便在后续设计中没有“移动部件”,并且使用更少的资源-如果不再需要,可以将其删除。

deleteAllNamedTimers

命令格式:
deleteAllNamedTimers(userName)
删除所有命名计时器并阻止它们再触发。信息已删除,无法检索。
参数:
userName:事件处理程序注册时使用的用户名。

deleteNamedTimer

命令格式:
success = deleteNamedTimer(userName, handlerName)
删除名称为handlerName的命名计时器并防止其再次触发。信息已删除,无法检索。

local deleted = deleteNamedTimer("Demonnic", "DemonVitals")
if deleted then
  cecho("DemonVitals deleted forever!!")
else
  cecho("DemonVitals doesn't exist and so could not be deleted.")
end

deleteStopWatch

命令格式:
deleteStopWatch(watchID/watchName)
此函数将删除现有秒表,无论它仅用于此会话,还是设置为在会话之间保存,使用 setStopWatchPersistence()带参数

lua MyStopWatch = createStopWatch("stopwatch_mine")
true

lua display(MyStopWatch)
4

lua deleteStopWatch(MyStopWatch)
true

lua deleteStopWatch(MyStopWatch)
nil

"stopwatch with id 4 not found"

lua deleteStopWatch("stopwatch_mine")
nil

removeCmdLineSuggestion

命令格式:
removeCmdLineSuggestion([name], suggestion)
删除指定命令行的制表符补全建议。

removeCmdLineSuggestion("help")

disableAlias

命令格式:
disableAlias(name)
按别名名称禁用/停用别名。如果多个别名都有此名称,它们都将被禁用。如果禁用别名组,则该组内的所有别名也将被禁用。

disableKey

命令格式:
disableKey(name)
禁用键(宏)或键组。禁用密钥组时,组中的所有密钥也将被隐式禁用。

disableScript

命令格式:
disableScript(name)
禁用以前启用的脚本。请注意,禁用脚本只能阻止它在将来运行-它不会“撤消”脚本所做的任何事情,例如屏幕上的标签。

disableTimer

命令格式:
disableTimer(name)
禁止计时器在触发时运行它的脚本-所以计时器周期仍然会发生,只是没有动作。如果要永久删除它,请使用 killTrigger . 而不是这个

disableTrigger

命令格式:
disableTrigger(name)
禁用永久触发器(触发器编辑器中的一个)或临时触发器。禁用组时,组内的所有触发器也将被禁用

enableAlias

命令格式:
enableAlias(name)
通过别名的名称启用/激活别名。如果多个别名都有此名称,它们都将被启用。

enableKey

命令格式:
enableKey(name)
启用一个键(宏)或一组键(以及其中未显式停用的所有键)。

enableScript

命令格式:
enableScript(name)
启用/激活以前禁用的脚本。

enableTimer

命令格式:
enableTimer(name)
启用或激活以前禁用的计时器。

-- enable the timer called 'my timer' that you created in Mudlets timers section
enableTimer("my timer")

-- or disable & enable a tempTimer you've made
timerID = tempTimer(10, [[echo("hi!")]])

-- it won't go off now
disableTimer(timerID)
-- it will continue going off again
enableTimer(timerID)

enableTrigger

命令格式:
enableTrigger(name)
启用或激活以前禁用的触发器。

-- enable the trigger called 'my trigger' that you created in Mudlets triggers section
enableTrigger("my trigger")

-- or disable & enable a tempTrigger you've made
triggerID = tempTrigger("some text that will match in a line", [[echo("hi!")]])

-- it won't go off now when a line with matching text comes by
disableTrigger(triggerID)

-- and now it will continue going off again
enableTrigger(triggerID)

exists

命令格式:
exists(name/IDnumber, type)
返回具有给定名称或给定类型编号的事物的数量-如果不存在则返回0。注意Lua中所有的数字都是真的,包括零。
参数: name: 名称(作为字符串)或,从 Mudlet 4.17 单个项目的ID号(该ID号将由 temp* or 或 perm* function来创建这样的项以标识该项)。 type: 类型可以是'alias','button'(Mudlet 4.10+),' trigger ',' timer ','keybind'(Mudlet 3.2+)或'script'(Mudlet 3.17+)。 注意:一个正数的ID号将返回1或0值,而不是lua布尔值true或false,这是为了保持函数对名称的行为方式的恒定性。
例子:

echo("I have " .. exists("my trigger", "trigger") .. " triggers called 'my trigger'!")

    You can also use this alias to avoid creating duplicate things, for example:
    您也可以使用此别名来避免创建重复的东西,例如:

-- this code doesn't check if an alias already exists and will keep creating new aliases
permAlias("Attack", "General", "^aa$", [[send ("kick rat")]])

-- while this code will make sure that such an alias doesn't exist first
-- we do == 0 instead of 'not exists' because 0 is considered true in Lua
if exists("Attack", "alias") == 0 then
    permAlias("Attack", "General", "^aa$", [[send ("kick rat")]])
end

    Especially helpful when working with 在与 permTimer:

if not exists("My animation timer", "timer") then
  vdragtimer = permTimer("My animation timer", "", .016, onVDragTimer) -- 60fps timer!
end
 
enableTimer("My animation timer")

getButtonState

命令格式:
getButtonState([ButtonNameOrID])
此函数可在复选框按钮脚本(2状态按钮)中使用,以确定复选框的当前状态。
注意:函数可以在任何Mudlet脚本之外的按钮自己的脚本中使用,参数ButtonNameOrID可从Mudlet版本4.13.0+获得
参数: ButtonNameOrID: 用于标识复选框按钮的数字ID或字符串名称。 返回: 2如果按钮处于“选中”状态,或1如果按钮未选中。(or如果ButtonNameOrID未标识可检查按钮,则为nil和错误消息)

-- check from within the script of a check-able button:
local checked = getButtonState()
if checked == 1 then
    hideExits()
else
    showExits()
end

-- check from anywhere in another Lua script of the same profile (available from Mudlet 4.13.0)
local checked, errMsg = getButtonState("Sleep")
if checked then
    shouldBeMounted = shouldBeMounted or false
    sendAll("wake", "stand")
    if shouldBeMounted then
        send("mount horse")
    end
else
    -- Global used to record if we were on a horse before our nap:
    shouldBeMounted = mounted or false
    if shouldBeMounted then
        send("dismount")
    end
    sendAll("sit", "sleep")
end

getCmdLine

命令格式:
getCmdLine([name])
返回给定命令行的当前内容。

getConsoleBufferSize

命令格式:
local lineLimit, sizeOfBatchDeletion = getConsoleBufferSize([consoleName])
如果成功,返回缓冲区(主窗口或迷你控制台)可以容纳的最大行数,以及当超过该限制时,一次将删除多少行数;返回一个 nil 以及失败时的错误消息。
例子:

-- sets the main window's size and how many lines will be deleted
-- when it gets to that size to be as small as possible:
setConsoleBufferSize("main", 1, 1)
true

-- find out what the numbers are:
local lineLimit, sizeOfBatchDeletion = getConsoleBufferSize()
echo("\nWhen the main console gets to " .. lineLimit .. " lines long, the first " .. sizeOfBatchDeletion .. " lines will be removed.\n")
When the main console gets to 100 lines long, the first 1 lines will be removed.

getNamedTimers

命令格式:
timers = getNamedTimers(userName)
以表的形式返回所有命名计时器名称的列表。
参数: userName: 事件处理程序注册时使用的用户名。 返回: 处理程序名称表。例如{“DemonVitals”,“DemonInv”}。{}如果没有注册

local timers = getNamedTimers("Demonnic")
  display(timers)
  -- {}
  registerNamedTimer("Test1", "testEvent", "testFunction")
  registerNamedTimer("Test2", "someOtherEvent", myHandlerFunction)
  timers = getNamedTimers("Demonnic")
  display(timers)
  -- { "Test1", "Test2" }

getProfileStats

命令格式:
getProfileStats()
返回一个表,其中包含概要文件的统计信息,其中包括概要文件具有的触发器数量、触发器中的模式、别名、键、计时器和脚本。类似于脚本编辑器中的Statistics按钮,可通过Lua脚本访问。
例子:

-- show all stats
display(getProfileStats())

-- check how many active triggers there are
activetriggers = getProfileStats().triggers.active
cecho(f"<PaleGreen>We have <SlateGrey>{activetriggers}<PaleGreen> active triggers!\n")

-- triggers can have many patterns, so let's check that as well
patterns = getProfileStats().triggers.patterns.active
triggers = getProfileStats().triggers.active
cecho(f"<PaleGreen>We have <SlateGrey>{patterns}<PaleGreen> active patterns within <SlateGrey>{triggers}<PaleGreen> triggers!\n")

getStopWatches

命令格式:
table = getStopWatches()
返回现有的每个秒表的详细信息表,键是手表ID,但由于为秒表分配的ID号可能存在间隙,因此有必要使用 pairs(…) 而不是 ipairs(…) 方法来循环访问所有的循环!。
每个秒表的详细信息将列出以下项目: name (string), isRunning (boolean), isPersistent (boolean), elapsedTime (table). 其中最后一个包含的数据与结果表从 getStopWatchBrokenDownTime() 功能-即 days (正整数), hours (整数,0至23), minutes (整数,0至59), second (整数,0至59), milliSeconds (整数,0至999), negative (boolean), decimalSeconds (秒数,小数部分为毫秒,可能还有一个负号,表示秒表上记录的整个经过时间)-也将由 getStopWatchTime()功能提供 例子:

-- on the command line:
lua getStopWatches()
-- could return something like:
{
  {
    isPersistent = true,
    elapsedTime = {
      minutes = 15,
      seconds = 2,
      negative = false,
      milliSeconds = 66,
      hours = 0,
      days = 18,
      decimalSeconds = 1556102.066
    },
    name = "Playing time",
    isRunning = true
  },
  {
    isPersistent = true,
    elapsedTime = {
      minutes = 47,
      seconds = 1,
      negative = true,
      milliSeconds = 657,
      hours = 23,
      days = 2,
      decimalSeconds = -258421.657
    },
    name = "TMC Vote",
    isRunning = true
  },
  {
    isPersistent = false,
    elapsedTime = {
      minutes = 26,
      seconds = 36,
      negative = false,
      milliSeconds = 899,
      hours = 3,
      days = 0,
      decimalSeconds = 12396.899
    },
    name = "",
    isRunning = false
  },
  [5] = {
    isPersistent = false,
    elapsedTime = {
      minutes = 0,
      seconds = 38,
      negative = false,
      milliSeconds = 763,
      hours = 0,
      days = 0,
      decimalSeconds = 38.763
    },
    name = "",
    isRunning = true
  }
}

getStopWatchTime

命令格式:
time = getStopWatchTime(watchID [or watchName from Mudlet 4.4.0])
以十进制秒数的形式返回时间,最多可保留三位小数,以给予毫秒(千分之一秒)分辨率。
例子:

-- an example of showing the time left on the stopwatch
teststopwatch = teststopwatch or createStopWatch()
startStopWatch(teststopwatch)
echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))
tempTimer(1, [[echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))]])
tempTimer(2, [[echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))]])
stopStopWatch(teststopwatch)

getStopWatchBrokenDownTime

命令格式:
brokenDownTimeTable = getStopWatchBrokenDownTime(watchID or watchName)
以表格形式返回当前秒表时间,无论秒表是在运行还是停止,并细分为:
“days” (integer)“days”(integer)

  "hours" (integer, 0 to 23)“hours”(整数,0到23)\\
  "minutes" (integer, 0 to 59)“minutes”(整数,0到59)\\
  "seconds" (integer, 0 to 59)“秒”(整数,0到59)\\
  "milliSeconds" (integer, 0 to 999)“milliSeconds”(整数,0到999)\\
  "negative" (boolean, true if value is less than zero)\\
  “negative”(布尔值,如果value小于零,则为true)\\

例子:

--an example, showing the presetting of a stopwatch.

--This will fail if the stopwatch with the given name
-- already exists, but then we can use the existing one:
local watchId = createStopWatch("TopMudSiteVoteStopWatch")
if watchId ~= nil then
  -- so we have just created the stopwatch, we want it
  -- to be saved for future sessions:
  setStopWatchPersistence("TopMudSiteVoteStopWatch", true)
  -- and set it to count down the 12 hours until we can
  -- revote:
  adjustStopWatch("TopMudSiteVoteStopWatch", -60*60*12)
  -- and start it running
  startStopWatch("TopMudSiteVoteStopWatch")

  openWebPage("http://www.topmudsites.com/vote-wotmud.html")
end

--[[ now I can check when it is time to vote again, even when
I stop the session and restart later by running the following
from a perm timer - perhaps on a 15 minute interval. Note that
when loaded in a new session the Id it gets is unlikely to be
the same as that when it was created - but that is not a
problem as the name is preserved and, if the timer is running
when the profile is saved at the end of the session then the
elapsed time will continue to increase to reflect the real-life
passage of time:]]

local voteTimeTable = getStopWatchBrokenDownTime("TopMudSiteVoteStopWatch")

if voteTimeTable["negative"] then
  if voteTimeTable["hours"] == 0 and voteTimeTable["minutes"] < 30 then
    echo("Voting for WotMUD on Top Mud Site in " .. voteTimeTable["minutes"] .. " minutes...")
  end
else
  echo("Oooh, it is " .. voteTimeTable["days"] .. " days, " .. voteTimeTable["hours"] .. " hours and " .. voteTimeTable["minutes"] .. " minutes past the time to Vote on Top Mud Site - doing it now!")
  openWebPage("http://www.topmudsites.com/vote-wotmud.html")
  resetStopWatch("TopMudSiteVoteStopWatch")
  adjustStopWatch("TopMudSiteVoteStopWatch", -60*60*12)
end

getScript

命令格式:
getScript(scriptName, [occurrence])getScript(scriptName,[occurrence])
返回具有给定名称的脚本。如果有多个脚本具有相同的名称,请指定出现次数以选取不同的脚本。如果脚本不存在,则返回-1。
参数:
scriptName:脚本的名称。
occurrence:(可选)脚本的出现次数,以防您有多个同名脚本。

invokeFileDialog

命令格式:
invokeFileDialog(fileOrFolder, dialogTitle)
打开文件选择器对话框,允许用户直观地选择文件或文件夹。该函数返回选定路径,如果未选择任何路径,则返回“”。

isActive

命令格式:
isActive(name/IDnumber, type)
您可以使用此函数来检查某个或某个事物是否处于活动状态。
返回活动对象的数量-如果没有活动对象则返回0。注意Lua中所有的数字都是真的,包括零。
Note注意:一个不存在的正ID号仍然会返回一个0值,这是为了保持函数对于一个不引用任何项的名称的行为方式不变。如有必要,应使用exists(…)确认项目的存在先

isPrompt

命令格式:
isPrompt()
返回true或false,具体取决于光标位置处的行是否为提示符。这个绝对可靠的功能适用于为游戏提供GA事件(如果它要检查是否支持,请查看主窗口的右下角)
示例使用可以作为Lua函数,使得在提示符上关闭门变得非常容易。

killAlias

命令格式:
killAlias(aliasID)
删除具有给定ID的临时别名。

killKey

命令格式:
killKey(name)
删除具有给定名称的密钥绑定。如果多个键绑定都有这个名称,它们都将被删除。

killTimer

命令格式:
killTimer(id)
删除定时器
注意:使用此函数无法删除在GUI中设置的或使用permTimer设置的非临时计时器。使用disableTimer()和enableTimer()打开或关闭它们。

killTrigger

命令格式:
killTrigger(id)
删除触发器
注意:当在触发器上下文之外使用时,触发器在从游戏接收到下一行时被禁用和删除-因此如果您正在测试别名中的触发器删除,“统计”窗口将报告禁用和等待删除的触发器计数,因此无需担心。

permAlias

命令格式:
permAlias(name, parent, regex, lua code)
创建一个持久别名,该别名在Mudlet重新启动后保留并显示在脚本编辑器中。
注意:Mudlet在设计上允许重名–所以用相同的名字调用permAlias会不断地创建新的别名。您可以使用exists函数检查别名是否已经存在。

permAlias("new alias", "my group", "^test$", [[echo ("say it works! This alias will show up in the script editor too.")]])

permGroup

命令格式:
permGroup(name, itemtype, [parent])
创建给定类型的新组。此组将在Mudlet重新启动时持续存在。
参数:
itemtype : trigger alias timer script (available in Mudlet 4.7+) key (available in Mudlet 4.11+)

permGroup("Combat triggers", "trigger")

permPromptTrigger

命令格式:
permPromptTrigger(name, parent, lua code)
为游戏中提示符创建一个持久触发器,该触发器在Mudlet重新启动并显示在脚本编辑器中。
注意:如果触发器不起作用,请检查右下角的N:是否有一个数字。此功能需要在游戏中启用telnet前进(GA)或结束记录(EOR)。提供Mudlet 3.6+

permPromptTrigger("echo on prompt", "", [[echo("hey! this thing is working!\n")]])

permRegexTrigger

命令格式:
permRegexTrigger(name, parent, pattern table, lua code)
创建具有一个或多个持久正则表达式触发器regex patterns 重新启动Mudlet并显示在脚本编辑器中后保留的模式。
注意:Mudlet设计允许重复名称-因此使用相同名称调用permRegexTrigger将继续创建新的触发器。您可以使用exists()函数检查触发器是否已经存在。

permRegexTrigger("Prompt", "", {"^(\d+)h, (\d+)m"}, [[health = tonumber(matches[2]); mana = tonumber(matches[3])]])

permBeginOfLineStringTrigger

命令格式:
permBeginOfLineStringTrigger(name, parent, pattern table, lua code)
创建一个持久首行触发器,该触发器在Mudlet重新启动后保持并显示在脚本编辑器中。
注意:Mudlet设计允许重复名称-所以用相同名称调用permBeginOfLineStringTrigger将不断创建新的触发器。您可以使用exists()函数检查触发器是否已经存在。

permRegexTrigger("Prompt", "", {"^(\d+)h, (\d+)m"}, [[health = tonumber(matches[2]); mana = tonumber(matches[3])]])

permSubstringTrigger

命令格式:
permSubstringTrigger( name, parent, pattern table, lua code )
创建一个持久子字符串触发器,该触发器在Mudlet重新启动后保持并显示在脚本编辑器中。
注意:Mudlet设计允许重复名称-所以用相同名称调用permSubstringTrigger将不断创建新的触发器。您可以使用exists()函数检查触发器是否已经存在。

permRegexTrigger("Prompt", "", {"^(\d+)h, (\d+)m"}, [[health = tonumber(matches[2]); mana = tonumber(matches[3])]])

permScript

命令格式:
permScript(name, parent, lua code)
在脚本编辑器中创建新脚本,该脚本在Mudlet重新启动后保留。
注意:脚本被调用一次,但在创建后不是活动的,它需要通过enableScript()启用。
注意:Mudlet设计允许重复名称-因此使用相同名称调用permScript将继续创建新的脚本元素。可以使用exists()函数检查脚本是否已经存在。

-- create a script in the "first script group" group
permScript("my script", "first script group", [[send ("my script that's in my first script group fired!")]])
-- create a script that's not in any group; just at the top
permScript("my script", "", [[send ("my script that's in my first script group fired!")]])

-- enable Script - a script element is disabled at creation
enableScript("my script")

permTimer

命令格式:
permTimer(name, parent, seconds, lua code)
创建一个持久计时器,该计时器在Mudlet重新启动并显示在脚本编辑器中。
注意:计时器在创建后不是活动的,它需要在启动前通过调用enableTimer()来启用。
注意:Mudlet设计允许重复名称-所以用相同名称调用permTimer将不断创建新的计时器。可以使用exists()函数检查计时器是否已经存在。

-- create a timer in the "first timer group" group
permTimer("my timer", "first timer group", 4.5, [[send ("my timer that's in my first timer group fired!")]])
-- create a timer that's not in any group; just at the top
permTimer("my timer", "", 4.5, [[send ("my timer that's in my first timer group fired!")]])

-- enable timer - they start off disabled until you're ready
enableTimer("my timer")

permKey

命令格式:
permKey(name, parent, [modifier], key code, lua code)
创建一个持久关键帧,该关键帧在Mudlet重新启动后保留并显示在脚本编辑器中。
注意:Mudlet设计允许重复名称-因此使用相同名称调用permKey将继续创建新密钥。可以使用exists()函数检查某个键是否已经存在。 即使lua代码没有正确编译,也会创建密钥–但这在编辑器中会很明显。

-- create a key at the top level for F8
permKey("my key", "", mudlet.key.F8, [[echo("hey this thing actually works!\n")]])

-- or Ctrl+F8
permKey("my key", "", mudlet.keymodifier.Control, mudlet.key.F8, [[echo("hey this thing actually works!\n")]])

-- Ctrl+Shift+W
permKey("jump keybinding", "", mudlet.keymodifier.Control + mudlet.keymodifier.Shift, mudlet.key.W, [[send("jump")]])

raiseEvent

命令格式:
raiseEvent(event_name, arg-1, … arg-n)
引发事件event_name。事件系统将调用此配置文件中已注册事件处理程序的所有此类脚本的主函数(与脚本名称完全相同的函数)。如果引发了事件,但没有向事件系统注册事件处理程序脚本,则忽略该事件,并且什么也不发生。这很方便,因为您可以在触发器,计时器,脚本等中引发事件。而不必关心实际的事件处理是否已经实现-或者更具体地说它是如何实现的。您的触发器引发一个事件,告诉系统他们已经检测到某个条件为真,或者某个事件已经发生。系统将如何以及是否响应此事件由系统决定,触发器脚本不必关心这些细节。对于小型系统,使用常规函数调用而不是事件会更方便,然而,系统越复杂,事件就越重要,因为它们有助于降低复杂性。
注意:可能的参数可以是字符串,数字,布尔,表,函数或nil。

raiseEvent("fight") a correct event handler function would be: myScript( event_name ). In this example raiseEvent uses minimal arguments, name the event name. There can only be one event handler function per script, but a script can still handle multiple events as the first argument is always the event name - so you can call your own special handlers for individual events. The reason behind this is that you should rather use many individual scripts instead of one huge script that has all your function code etc. Scripts can be organized very well in trees and thus help reduce complexity on large systems.
    raiseEvent(“fight”)正确的事件处理函数应为:myScript(event_name)。在本例中,raiseEvent使用最小参数,命名事件名称。每个脚本只能有一个事件处理函数,但一个脚本仍然可以处理多个事件,因为第一个参数始终是事件名称-因此您可以为单个事件调用自己的特殊处理程序。这背后的原因是,你应该使用许多单独的脚本,而不是一个巨大的脚本,其中包含所有的函数代码等。脚本可以很好地组织在树中,从而有助于降低大型系统的复杂性。

Where the number of arguments that your event may receive is not fixed you can use ... as the last argument in the function declaration to handle any number of arguments. For example:
如果事件可能接收的参数数量不固定,则可以使用... 作为函数声明中的最后一个参数来处理任意数量的参数。举例来说:

-- try this function out with "lua myscripthandler(1,2,3,4)"
function myscripthandler(a, b, ...)
  print("Arguments a and b are: ", a,b)
  -- save the rest of the arguments into a table
  local otherarguments = {...}
  print("Rest of the arguments are:")
  display(otherarguments)

  -- access specific otherarguments:
  print("First and second otherarguments are: ", otherarguments[1], otherarguments[2])
end

raiseGlobalEvent

命令格式:
raiseGlobalEvent(event_name, arg-1, … arg-n)
这将引发事件“event_name”,但此事件将发送给所有其他 打开的配置。简档以圆形字母顺序接收事件(如果配置“C”引发该事件并且我们具有配置“A”、“C”和“E”,则顺序是“E”→“A”,但是如果“E”引发事件,则顺序是“A”→“C”);执行控制被移交给接收简档,从而意味着长时间运行的事件可以锁定引发事件的配置。

-- from profile called "My game" this raises an event "my event" with additional arguments 1, 2, 3, "My game" to all profiles except the original one
raiseGlobalEvent("my event", 1, 2, 3)

-- want the current profile to receive it as well? Use raiseEvent
raiseEvent("my event", 1, 2, 3)

-- example of calling functions in one profile from another:
-- profile B:
control = control or {}
function control.updateStatus()
  disableTrigger("test triggers")
  print("disabling triggers worked!")
end

-- this handles calling the right function in the control table
function control.marshaller(_, callfunction)
  if control[callfunction] then control[callfunction]()
  else
    cecho("<red>Asked to call an unknown function: "..callfunction)
  end
end

registerAnonymousEventHandler("sysSendAllProfiles", "control.marshaller")

-- profile A:
raiseGlobalEvent("sysSendAllProfiles", "updateStatus")
raiseGlobalEvent("sysSendAllProfiles", "invalidfunction")

registerNamedTimer

命令格式:
success = registerNamedTimer(userName, timerName, time, functionReference, [repeating])
使用名称timerName注册命名计时器。命名计时器受到保护,不受复制,可以停止和恢复,与普通tempTimer不同。为每个userName保留一个单独的列表,以强制名称间距并避免冲突

remainingTime

命令格式:
remainingTime(timer id number or name)
以浮点形式返回具有ID号的计时器(临时或永久)的剩余时间(如果它处于活动状态),或者(第一个)具有名称的计时器的剩余时间。

resetProfileIcon

命令格式:
resetProfileIcon()
将连接屏幕中的配置文件图标重置为默认值。

resetStopWatch

命令格式:
success = resumeNamedTimer(userName, handlerName)
恢复名为handlerName的命名计时器并使其再次触发。一次,除非它被记录为重复。

setButtonState

命令格式:
setButtonState(ButtonNameOrID, checked)
从任何Mudlet项目的脚本设置可下拉(“下拉”)类型按钮的状态-但不会导致脚本或与该按钮相关联的命令之一被运行/发送。

setConsoleBufferSize

命令格式:
setConsoleBufferSize([consoleName], linesLimit, sizeOfBatchDeletion)
设置缓冲区(主窗口或迷你控制台窗口)可以容纳的最大行数。默认值为10,000。
注意:Mudlet即使是巨大的数字也能非常高效地执行,但当然,您的计算机的内存是有限制的。从Mudlet 4.7+开始,这个数量将被限制在macOS和Linux上(在Windows上,它的上限更低,因为Windows上的Mudlet是32位)。
参数: sizeOfBatchDeletion: 指定当您超过限制时Mudlet应该一次删除多少行-它批量删除,因为这样做很有效。

setProfileIcon

命令格式:
setProfileIcon(iconPath)
在连接屏幕中为此配置文件设置自定义图标。

setScript

命令格式:
setScript(scriptName, luaCode, [occurrence])
设置脚本的Lua代码,替换现有代码。如果您有许多同名的脚本,请使用“occurrence”参数在它们之间进行选择。

setStopWatchName

命令格式:
setStopWatchName(watchID/currentStopWatchName, newStopWatchName)
设置秒表名称。
注意:currentStopWatchName或newStopWatchName可以是空字符串:如果第一个是这样,则选择没有名称的最低ID编号的秒表;如果第二个是这样,则从所选择的秒表中移除现有名称。

setStopWatchPersistence

命令格式:
setStopWatchPersistence(watchID/watchName, state)
设置永久秒状态。
注意:当一个永久秒表在以后的会话中(或使用resetProfile()后)重新加载时,秒表可能不会被分配与以前相同的ID号-因此,建议在创建或结束会话之前为任何永久秒表分配一个名称。

setTriggerStayOpen

命令格式:
setTriggerStayOpen(name, number of lines)
设置触发器脚本应该触发多少行或在触发器匹配后链应该保持打开状态-因此这允许您扩展或缩短触发多条触发器。此函数的主要用途是在满足某个条件时关闭链。

startStopWatch

命令格式:
startStopWatch(watchName or watchID, [resetAndRestart])
Stopwatches可以停止 秒表 然后重新启动任意次数。为了确保向后兼容性,秒表可以设置秒数,此功能还将重置秒表为零并重新启动它-无论它是否正在运行; 否则只能启动停止的秒表,并且只能停止启动的秒表。尝试重复其中一个操作将产生一个nil和一个错误消息;而且,记录的时间不再被重置,使得它们现在可以像真实的的秒表一样用于记录总的隔离时间段。

stopAllNamedTimers

命令格式:
stopAllNamedTimers(userName)
停止userName的所有命名计时器并防止它们再次触发。信息被保留并且计时器可以被恢复。

stopNamedTimer

命令格式:
success = stopNamedTimer(userName, handlerName)
停止名称为handlerName的命名计时器并防止其再次触发。信息被存储,因此如果需要,可以稍后恢复。

stopStopWatch

命令格式:
stopStopWatch(watchID or watchName)
停止秒表, 返回在秒表设置为运行状态后调用它的时间。以秒数表示的经过时间,小数部分给予以毫秒(千分之一秒)为单位的分辨率。您也可以检索当前时间而不停止秒表

tempAnsiColorTrigger

命令格式:
tempAnsiColorTrigger(foregroundColor[, backgroundColor], code[, expireAfter])
它直接支持全套256个ANSI颜色代码,并在指定的前景和背景颜色上触发颜色触发。该函数返回后续的触发器ID 调用enableTrigger(), disableTrigger() and 和 killTrigger() 。触发器是临时的,当你关闭Mudlet时它不会停留,并且会多次触发,直到你禁用或摧毁它。也可以使其成为临时的,并在与 expireAfter parameter. 参数.
颜色代码(注意,大于或等于零的值是ANSI和游戏服务器用于8/16/256颜色模式的实际数字代码)

 特殊代码(将来可能会扩展):
-2 = 默认文本颜色(ANSI SGR 0 m代码之后使用的颜色,该代码将前景色和背景颜色重置为首选项中设置的颜色)
-1 = 忽略 前台或后台代码的值可以具有此值-否则它将不是 color trigger!
ANSI 8-color set:
0=(暗)黑
1 =(深)红色
2 =(深)绿色
3 =(深)黄色
4 =(深)蓝色
5 =(深)洋红色
6=(深色)青色
7 =(暗)白色{a.k.a.浅灰色}
附加颜色:
8 =浅黑色{a.k.a.深灰色}
9 =浅红色
10 =绿色
11 =浅黄色
12 =浅蓝色
13 =浅品洋红
14 =浅青色
15 =浅白色
6 x 6 x 6 RGB(216)颜色,显示为3x2位十六进制代码
16 = #000000
17 = #000033
18 = #000066
...
229 = #FFFF99
230 = #FFFFCC
231 = #FFFFFF
24灰度,也显示为3x2位十六进制代码
232 = #000000
233 = #0A0A0A
234 = #151515
...
253 = #E9E9E9
254 = #F4F4F4
255 = #FFFFFF255 = #FFFF

例子:

tempAnsiColorTrigger(14, -1, [[selectString(matches[1],1) fg("red")]])
-- or:
tempAnsiColorTrigger(14, -1, function()
  selectString(matches[1], 1)
  fg("red")
end)

-- match the trigger only 4 times
tempColorTrigger(14, -1, [[selectString(matches[1],1) fg("red")]], 4)

tempAlias

命令格式:
aliasID = tempAlias(regex, code to do)
创建一个临时别名-临时的意思是当Mudlet重新启动时它不会被保存(除非重新创建它)。别名将在匹配时多次触发,它不是一次性别名。该函数返回一个ID 用于enableAlias(), disableAlias() 和 killAlias() 调用

tempBeginOfLineTrigger

命令格式:
tempBeginOfLineTrigger(part of line, code, expireAfter)
创建一个触发器,只要它提供的行的一部分从一开始就与行匹配(不管行的结尾是什么),该触发器就会触发。触发器是临时的,当你关闭Mudlet时它不会停留,并且会多次触发,直到你禁用或摧毁它。也可以使其成为临时的,并在与 expireAfter 参数.该函数返回后续的触发器ID enableTrigger(), disableTrigger() and 和 killTrigger()调用

mytriggerID = tempBeginOfLineTrigger("Hello", [[echo("We matched!")]])

--[[ now this trigger will match on any of these lines:
Hello
Hello!
Hello, Bob!

but not on:
Oh, Hello
Oh, Hello!
]]

-- or as a function:
mytriggerID = tempBeginOfLineTrigger("Hello", function() echo("We matched!") end)

-- you can make the trigger match only a certain amount of times as well, 5 in this example:
tempBeginOfLineTrigger("This is the start of the line", function() echo("We matched!") end, 5)

-- if you want a trigger match not to count towards expiration, return true. In this example it'll match 5 times unless the line is "Start of line and this is the end."
tempBeginOfLineTrigger("Start of line", 
function()
  if line == "Start of line and this is the end." then
    return true
  else
    return false
  end
end, 5)

tempButton

命令格式:
tempButton(toolbar name, button text, orientation)
创建临时按钮。临时意味着,当Mudlet关闭时,它会消失。

tempButtonToolbar

命令格式:
tempButtonToolbar(name, location, orientation)
创建临时按钮工具栏。临时意味着,当Mudlet关闭时,它会消失。

tempColorTrigger

命令格式:
tempColorTrigger(foregroundColor, backgroundColor, code, expireAfter)
生成在指定的前景色和背景色上触发的颜色触发器。两种颜色都需要以简化的ANSI 16颜色模式代码的形式提供。该函数返回后续的触发器ID enableTrigger(), disableTrigger() and 和 killTrigger()调用, 触发器是临时的,当你关闭Mudlet时它不会停留,并且会多次触发,直到你禁用或摧毁它。也可以使其成为临时的,并在与 expireAfter parameter. 参数.

Color codes颜色代码

0 = default text color
1 = light black
2 = dark black
3 = light red
4 = dark red
5 = light green
6 = dark green
7 = light yellow
8 = dark yellow
9 = light blue
10 = dark blue
11 = light magenta
12 = dark magenta
13 = light cyan
14 = dark cyan
15 = light white
16 = dark white

例子:

tempColorTrigger(9, 2, [[selectString(matches[1],1) fg("red") bg("blue")]])
-- or:
tempColorTrigger(9, 2, function()
  selectString(matches[1], 1)
  fg("red")
  bg("blue")
end)

-- match the trigger only 4 times
tempColorTrigger(9, 2, [[selectString(matches[1],1) fg("red") bg("blue")]], 4)

tempComplexRegexTrigger

命令格式:
tempComplexRegexTrigger(name, regex, code, multiline, fg color, bg color, filter, match all, highlight fg color, highlight bg color, play sound file, fire length, line delta, expireAfter)
允许您使用任何UI可用选项在Mudlet中创建临时触发器。触发器是临时的,当你关闭Mudlet时它不会停留,并且会多次触发,直到你禁用或摧毁它。也可以使其成为临时的,并在与 expireAfter parameter. 参数.

参数:

  name: 此触发器的名称。\\
  regex: 要匹配的正则表达式。\\
  code: 触发器运行时要执行的代码。你需要把它包装在[[ ]]中,或者给予一个Lua函数(从Mudlet 3.5.0开始)。\\
  multiline: 如果您使用多个正则表达式(参见下面的注释),则将其设置为1,并且只有在指定的行增量中匹配了所有正则表达式时才需要触发器。然后,所有捕获将保存在多匹配中,而不是匹配中。如果此选项设置为0,则当匹配任何正则表达式时触发器。\\
  fg color: 要触发的前景色。\\
  bg color: 要触发的背景颜色。\\
  filter: 是否只希望将筛选的内容(=捕获组)传递到子触发器?否则也是最初的一行。\\
  match all: 如果希望触发器匹配行中所有可能出现的正则表达式,则设置为1。当设置为0时,触发器将在第一次成功匹配后停止。\\
  highlight fg color: 您希望突出显示匹配的前景色。\\
  highlight bg color: 您希望匹配的背景颜色。\\
  play sound file: 设置为触发器时要播放的声音文件的名称。\\
  fire length: 触发器的所有条件必须为真的行数。\\
  line delta: 在触发器或链匹配后,继续激发脚本x行。\\
  expireAfter: 在指定数量的匹配之后删除触发器(从Mudlet 3.11开始)。您可以通过在触发器触发后返回true来使触发器匹配不计入过期。\\

注意:如果不想使用从多行开始的选项,请将这些选项设置为0。否则,输入1以激活或要使用的值。
注意:如果要使用color选项,则需要同时提供fg和bg。
注意:为了制作第二个示例中的多行触发器,您需要使用相同的触发器名称和选项,并提供要添加的新模式。请注意,只有最后一个脚本会被设置,其他脚本会被忽略。

-- This trigger will be activated on any new line received.
triggerNumber = tempComplexRegexTrigger("anyText", "^(.*)$", [[echo("Text received!")]], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

-- This trigger will match two different regex patterns:
tempComplexRegexTrigger("multiTrigger", "first regex pattern", [[]], 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
tempComplexRegexTrigger("multiTrigger", "second regex pattern", [[echo("Trigger matched!")]], 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

tempExactMatchTrigger

命令格式:
tempExactMatchTrigger(exact line, code, expireAfter)
创建一个触发器,每当游戏中的行与提供的行完全匹配时(结束相同,开始相同,看起来相同)就会触发。这里不需要使用任何正则表达式符号(^和$)。该函数返回后续的触发器ID enableTrigger(), disableTrigger() and 和 killTrigger()调用. 触发器是临时的,当你关闭Mudlet时它不会停留,并且会多次触发,直到你禁用或摧毁它。也可以使其成为临时的,并在与 expireAfter parameter. 参数.

tempKey

命令格式:
tempKey([modifier], key code, lua code)
创建密钥绑定。这个键绑定并不是临时的,因为它只会触发一次(它会随着你使用它的次数而频繁地触发),而是当Mudlet关闭时它不会被保存。

tempLineTrigger

命令格式:
tempLineTrigger(from, howMany, code)
将启动的临时触发器 n 当前行之后的连续行。这对于解析已知到达某个行边距的输出或从游戏中删除不需要的输出非常有用-触发器不需要匹配任何模式。该函数返回后续的触发器ID enableTrigger(), disableTrigger() and 和 killTrigger() 调用. 触发器是临时的,当你关闭Mudlet时它不会停留,并且会多次触发,直到你禁用或摧毁它。也可以使其成为临时的,并在与 expireAfter parameter. 参数.

tempPromptTrigger

命令格式:
tempPromptTrigger(code, expireAfter)
将与游戏提示符匹配的临时触发器。该函数返回后续的触发器ID enableTrigger(), disableTrigger() and 和 killTrigger()调用. 触发器是临时的,当你关闭Mudlet时它不会停留,并且会多次触发,直到你禁用或摧毁它。也可以使其成为临时的,并在与 expireAfter 参数..

tempRegexTrigger

命令格式:
tempRegexTrigger(regex, code, expireAfter)
创建一个临时的正则表达式触发器,只要匹配就执行该代码。该函数返回后续的触发器ID enableTrigger(), disableTrigger() 和 killTrigger() 调用. 触发器是临时的,当你关闭Mudlet时它不会停留,并且会多次触发,直到你禁用或摧毁它。也可以使其成为临时的,并在与 expireAfter 参数…

-- create a non-duplicate trigger that matches on any line and calls a function
html5log = html5log or {}
if html5log.trig then killTrigger(html5log.trig) end
html5log.trig = tempRegexTrigger("^", [[html5log.recordline()]])
-- or a simpler variant:
html5log.trig = tempRegexTrigger("^", html5log.recordline)

-- only match 3 times:
tempRegexTrigger("^You prick (.+) twice in rapid succession with", function() echo("Hit "..matches[2].."!\n") end, 3)

-- since Mudlet 4.11+ you can use named capturing groups
tempRegexTrigger("^You see (?<material>\\w+) axe inside chest\\.", function() echo("\nAxe is " .. matches.material) end)

tempTimer

命令格式:
tempTimer(time, code to do[, repeating])
创建临时一次性计时器并返回计时器ID,可以与 enableTimer(), disableTimer() 和 killTimer() 函数调用一起你可以使用2.3秒或0.45秒等。当它发射后,计时器将被停用并销毁,所以它只会触发一次。这里是tempTimer的详细介绍.

-- wait half a second and then run the command
tempTimer(0.5, function() send("kill monster") end)

-- echo between 1 and 5 seconds after creation
tempTimer(math.random(1, 5), function() echo("hi!") end) 

-- or an another example - two ways to 'embed' variable in a code for later:
local name = matches[2]
tempTimer(2, [[send("hello, ]]..name..[[ !")]])
-- or:
tempTimer(2, function()
  send("hello, "..name)
end)

-- create a looping timer
timerid = tempTimer(1, function() display("hello!") end, true)

-- later when you'd like to stop it:
killTimer(timerid)

注:双括号,例如:manual可以用来引用Lua中的字符串。与通常的`”“引号语法的区别在于`manual也接受字符“。因此,您不必转义上述脚本中的“字符。另一个优点是它可以用作多行引号,因此脚本可以跨越几行。
注意:当计时器触发时,作为参数提供的Lua代码是从字符串值编译的。这意味着,如果你想通过值传递任何参数,例如:如果你想调用一个函数,它使用变量myGold的值作为参数,你必须这样做:

tempTrigger

命令格式:
tempTrigger(substring, code, expireAfter)
创建一个子字符串触发器,该触发器在代码匹配时执行代码。该函数返回后续的触发器ID enableTrigger(), disableTrigger() 和 killTrigger()调用. 触发器是临时的,当你关闭Mudlet时它不会停留,并且会多次触发,直到你禁用或摧毁它。也可以使其成为临时的,并在与 expireAfter parameter. 参数.

网络相关函数

用于管理网络的函数集合。

connectToServer

命令格式:
connectToServer(host, port, [save])
连接到给定的游戏。
参数:
host: 服务器域或IP地址。
port:服务器端口。
save: (可选,布尔值)如果提供,将新的连接参数保存在配置文件中,以便下次打开配置文件时使用它们。

disconnect

命令格式:
disconnect()
立即将您从游戏中断开。

downloadFile

命令格式:
downloadFile(saveto, url)
将给定url中的资源下载到磁盘上的保存位置。这不会在文件下载之前暂停脚本-相反,它允许脚本立即继续并在后台下载。下载完成后, 触发sysDownloadDone事件(以saveto位置作为参数),或者当下载失败时, sysDownloadError事件将引发并说明失败的原因。您可以多次调用downloadFile,并同时进行多个下载,但不能保证它们的下载顺序与您启动它们的顺序相同。

-- just download a file and save it in our profile folder
local saveto = getMudletHomeDir().."/dark-theme-mudlet.zip"
local url = "http://www.mudlet.org/wp-content/files/dark-theme-mudlet.zip"
downloadFile(saveto, url)
cecho("<white>Downloading <green>"..url.."<white> to <green>"..saveto.."\n")

一个更高级的示例,下载网页,读取它,并从中打印结果:

-- create a function to parse the downloaded webpage and display a result
function downloaded_file(_, filename)
  -- is the file that downloaded ours?
  if not filename:find("achaea-who-count.html", 1, true) then return end

  -- read the contents of the webpage in
  local f, s, webpage = io.open(filename)
  if f then webpage = f:read("*a"); io.close(f) end
  -- delete the file on disk, don't clutter
  os.remove(filename)

  -- parse our downloaded file for the player count
  local pc = webpage:match([[Total: (%d+) players online]])
  display("Achaea has "..tostring(pc).." players on right now.")
end

-- register our function to run on the event that something was downloaded
registerAnonymousEventHandler("sysDownloadDone", "downloaded_file")

-- download a list of fake users for a demo
downloadFile(getMudletHomeDir().."/achaea-who-count.html", "https://www.achaea.com/game/who")

getConnectionInfo

命令格式:
getConnectionInfo()
返回当前连接到的服务器地址和端口,以及(在Mudlet4.12+中) true 或 false 指示您当前是否连接到游戏。
在Mudlet中可用4.2+
例子:

local host, port, connected = getConnectionInfo()
cecho(string.format("<light_grey>Playing on <forest_green>%s:%s<light_grey>, currently connected? <forest_green>%s\n", host, port, tostring(connected)))

-- echo the new connection parameters whenever we connect to a different host with connectToServer()
function echoInfo()
    local host, port = getConnectionInfo()
    cecho(string.format("<light_grey>Now connected to <forest_green>%s:%s\n", host, port))
  end

registerAnonymousEventHandler("sysConnectionEvent", "echoInfo")

getIrcConnectedHost

命令格式:
getIrcConnectedHost()
返回true+host,其中host是包含IRC服务器主机名的字符串,该主机名由服务器在启动IRC连接时提供给客户端。如果客户端尚未开始或完成连接,则返回false和空字符串。
例子:

local status, hostname = getIrcConnectedHost()

if status == true then
  -- do something with connected IRC, send IRC commands, store 'hostname' elsewhere.
  -- if sysIrcMessage sender = hostname from above, message is likely a status, command response, or an error from the Server.
else 
  -- print a status, change connection settings, or just continue waiting to send IRC data.
end

getIrcNick

命令格式:
getIrcNick()
返回包含IRC客户端昵称的字符串。如果客户端尚未启动,则从IRC客户端配置加载默认昵称。

getIrcServer

命令格式:
getIrcServer()
分别以字符串和数字形式返回IRC客户端服务器名称和端口。如果客户端尚未启动,则从IRC客户端配置加载默认服务器。

getNetworkLatency

命令格式:
getNetworkLatency()
返回网络延迟

openUrl

命令格式:
openUrl (url)
打开给定URL的默认操作系统浏览器。

reconnect

命令格式:
reconnect()
强制重新连接(所以如果你已经连接,它会断开)你到游戏。

restartIrc

命令格式:
restartIrc()
重新启动IRC客户端连接,在重新连接IRC客户端之前从磁盘重新加载配置。

sendATCP

命令格式:
sendATCP(message, what)
发送ATCP消息。 具体见Achaea Telnet客户端协议规范。

sendGMCP

命令格式:
sendGMCP(command)
向服务器发送GMCP消息
请注意,此函数在实践中很少使用。对于大多数GMCP模块,当游戏中发生相关事件时,服务器会自动发送消息。例如,LOOKing在您的房间中提示服务器发送房间描述和内容,以及GMCP消息gmcp.Room。在这种情况下,不需要调用sendGMCP。

sendMSDP

命令格式:
sendMSDP(variable[, value][, value…])
向服务器发送MSDP消息。

sendIrc

命令格式:
sendIrc(target, message)sendIrc(target,message)
向IRC频道或人员发送消息。如果客户端过滤了消息或由于某种原因未能发送它。如果IRC客户端尚未启动,则此函数将启动IRC客户端并开始连接。
要接收IRC消息,请检查sysIrcMessage事件。

    /ACTION <target> <message...>
    /ADMIN (<server>)
    /AWAY (<reason...>)
    /CLEAR (<buffer>) --清除给定缓冲区名称的文本日志。如果未指定当前活动缓冲区,则使用当前活动缓冲区。
    /CLOSE (<buffer>) --关闭缓冲区并将其从缓冲区列表中删除。如果未指定当前活动缓冲区,则使用当前活动缓冲区。
    /HELP (<command>) --显示有关给定命令的一些帮助信息或列出所有可用命令。
    /INFO (<server>)
    /INVITE <user> (<#channel>)
    /JOIN <#channel> (<key>)
    /KICK (<#channel>) <user> (<reason...>)
    /KNOCK <#channel> (<message...>)
    /LIST (<channels>) (<server>)
    /ME [target] <message...>
    /MODE (<channel/user>) (<mode>) (<arg>)
    /MOTD (<server>)
    /MSG <target> <message...> --向目标发送消息,可用于发送私人消息。
    /NAMES (<#channel>)
    /NICK <nick>
    /NOTICE <#channel/user> <message...>
    /PART (<#channel>) (<message...>)
    /PING (<user>)
    /RECONNECT -- Issues a Quit command to the IRC Server and closes the IRC connection then reconnects to the IRC server. The same as calling ircRestart() in Lua.
    /QUIT (<message...>)
    /QUOTE <command> (<parameters...>)
    /STATS <query> (<server>)
    /TIME (<user>)
    /TOPIC (<#channel>) (<topic...>)
    /TRACE (<target>)
    /USERS (<server>)
    /VERSION (<user>)
    /WHO <mask>
    /WHOIS <user>
    /WHOWAS <user>

getHTTP

命令格式:
getHTTP(url, headersTable)
请求到给定的URL。
例子:

function onHttpGetDone(_, url, body)
  cecho(string.format("<white>url: <dark_green>%s<white>, body: <dark_green>%s", url, body))
end

registerAnonymousEventHandler("sysGetHttpDone", onHttpGetDone)

getHTTP("https://httpbin.org/info")
getHTTP("https://httpbin.org/are_you_awesome", {["X-am-I-awesome"] = "yep I am"})

-- Status requests typically use GET requests
local url = "http://postman-echo.com/status"
local header = {["Content-Type"] = "application/json"}

-- first we create something to handle the success, and tell us what we got
registerAnonymousEventHandler('sysGetHttpDone', function(event, rurl, response)
  if rurl == url then display(r) else return true end -- this will show us the response body, or if it's not the right url, then do not delete the handler
end, true) -- this sets it to delete itself after it fires
-- then we create something to handle the error message, and tell us what went wrong
registerAnonymousEventHandler('sysGetHttpError', function(event, response, rurl)
  if rurl == url then display(r) else return true end -- this will show us the response body, or if it's not the right url, then do not delete the handler
end, true) -- this sets it to delete itself after it fires

-- Lastly, we make the request:
getHTTP(url, header)

postHTTP

命令格式:
postHTTP(dataToSend, url, headersTable, file)
发送 HTTP POST 请求到给定的URL
例子:

function onHttpPostDone(_, url, body)
  cecho(string.format("<white>url: <dark_green>%s<white>, body: <dark_green>%s", url, body))
end

registerAnonymousEventHandler("sysPostHttpDone", onHttpPostDone)

postHTTP("why hello there!", "https://httpbin.org/post")
postHTTP("this us a request with custom headers", "https://httpbin.org/post", {["X-am-I-awesome"] = "yep I am"})
postHTTP(nil, "https://httpbin.org/post", {}, "<fill in file location to upload here, maybe get from invokeDialog>")

-- This will create a JSON message body. Many modern REST APIs expect a JSON body. 
local url = "http://postman-echo.com/post"
local data = {message = "I am the banana", user = "admin"}
local header = {["Content-Type"] = "application/json"}

-- first we create something to handle the success, and tell us what we got
registerAnonymousEventHandler('sysPostHttpDone', function(event, rurl, response)
  if rurl == url then display(response) else return true end -- this will show us the response body, or if it's not the right url, then do not delete the handler
end, true) -- this sets it to delete itself after it fires

-- then we create something to handle the error message, and tell us what went wrong
registerAnonymousEventHandler('sysPostHttpError', function(event, response, rurl)
  if rurl == url then display(response) else return true end -- this will show us the response body, or if it's not the right url, then do not delete the handler
end, true) -- this sets it to delete itself after it fires

-- Lastly, we make the request:
postHTTP(yajl.to_string(data), url, header) -- yajl.to_string converts our Lua table into a JSON-like string so the server can understand it

HTTP基本身份验证示例:
选项1:URL编码: 许多HTTP服务器允许您在URL本身的开头输入HTTP基本身份验证用户名和密码,格式如下:

https://username:password@domain.com/path/to/endpoint

选项2:授权标题: 某些HTTP服务器可能要求您将基本身份验证放入'Authorization' HTTP头值中。

function base64Encode(data)
  -- Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss <alexthkloss@web.de>
  -- licensed under the terms of the LGPL2
  local b = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    return ((data:gsub('.', function(x) 
        local r,b='',x:byte()
        for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
        return r;
    end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
        if (#x < 6) then return '' end
        local c=0
        for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
        return b:sub(c+1,c+1)
    end)..({ '', '==', '=' })[#data%3+1])
end
-- Example: base64Encode("user:12345") -> dXNlcjoxMjM0NQ== 

function postJSON(url,dataTable,headerTable)
  -- This will create a JSON message body. Many modern REST APIs expect a JSON body. 
  local data = dataTable or {text = "hello world"}
  local header = headerTable or {["Content-Type"] = "application/json"}
  -- first we create something to handle the success, and tell us what we got
  registerAnonymousEventHandler('sysPostHttpDone', function(event, rurl, response)
    if rurl == url then sL("HTTP response success"); echo(response) else return true end -- this will show us the response body, or if it's not the right url, then do not delete the handler
  end, true) -- this sets it to delete itself after it fires
  -- then we create something to handle the error message, and tell us what went wrong
  registerAnonymousEventHandler('sysPostHttpError', function(event, response, rurl)
    if rurl == url then sL("HTTP response error",3); echo(response) else return true end -- this will show us the response body, or if it's not the right url, then do not delete the handler
  end, true) -- this sets it to delete itself after it fires
  -- Lastly, we make the request:
  postHTTP(yajl.to_string(data), url, header) -- yajl.to_string converts our Lua table into a JSON-like string so the server can understand it
end

data = {
    message = "I am the banana",
    user = "admin"
}
header = {
    ["Content-Type"] = "application/json",
    ["Authorization"] = "Basic " .. base64Encode("user:12345")
}
postJSON("http://postman-echo.com/post",data,header)

-- Example: URLEncodeTable({message="hello",person="world"}) -> "message=hello&person=world"

function URLEncodeTable(Args)
  -- From: https://help.interfaceware.com/code/details/urlcode-lua
  ----------------------------------------------------------------------------
  -- URL-encode the elements of a table creating a string to be used in a
  -- URL for passing data/parameters to another script
  -- @param args Table where to extract the pairs (name=value).
  -- @return String with the resulting encoding.
  ----------------------------------------------------------------------------
  --
  local ipairs, next, pairs, tonumber, type = ipairs, next, pairs, tonumber, type
  local string = string
  local table = table
  
  --helper functions: 
  ----------------------------------------------------------------------------
  -- Decode an URL-encoded string (see RFC 2396)
  ----------------------------------------------------------------------------
  local unescape = function (str)
     str = string.gsub (str, "+", " ")
     str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end)
     return str
  end
   
  ----------------------------------------------------------------------------
  -- URL-encode a string (see RFC 2396)
  ----------------------------------------------------------------------------
  local escape = function (str)
     str = string.gsub (str, "([^0-9a-zA-Z !'()*._~-])", -- locale independent
        function (c) return string.format ("%%%02X", string.byte(c)) end)
     str = string.gsub (str, " ", "+")
     return str
  end
   
  ----------------------------------------------------------------------------
  -- Insert a (name=value) pair into table [[args]]
  -- @param args Table to receive the result.
  -- @param name Key for the table.
  -- @param value Value for the key.
  -- Multi-valued names will be represented as tables with numerical indexes
  -- (in the order they came).
  ----------------------------------------------------------------------------
  local insertfield = function (args, name, value)
     if not args[name] then
        args[name] = value
     else
        local t = type (args[name])
        if t == "string" then
           args[name] = {args[name],value,}
        elseif t == "table" then
           table.insert (args[name], value)
        else
           error ("CGILua fatal error (invalid args table)!")
        end
     end
  end
  -- end helper functions 
    
  if Args == nil or next(Args) == nil then -- no args or empty args?
    return ""
  end
  local strp = ""
  for key, vals in pairs(Args) do
    if type(vals) ~= "table" then
       vals = {vals}
    end
    for i,val in ipairs(vals) do
       strp = strp.."&"..key.."="..escape(val)
    end
  end
  -- remove first &
  return string.sub(strp,2)
end

putHTTP

命令格式:
putHTTP(dataToSend, url, [headersTable], [file])
发送 HTTP PUT 请求到给定的URL
例子:

function onHttpPutDone(_, url, body)
  cecho(string.format("<white>url: <dark_green>%s<white>, body: <dark_green>%s", url, body))
end

registerAnonymousEventHandler("sysPutHttpDone", onHttpPutDone)
putHTTP("this us a request with custom headers", "https://httpbin.org/put", {["X-am-I-awesome"] = "yep I am"})
putHTTP("https://httpbin.org/put", "<fill in file location to upload here>")

deleteHTTP

命令格式:
deleteHTTP(url, headersTable)
发送 HTTP DELETE 请求到给定的URL
例子:

function onHttpDeleteDone(_, url, body)
  cecho(string.format("<white>url: <dark_green>%s<white>, body: <dark_green>%s", url, body))
end

registerAnonymousEventHandler("sysDeleteHttpDone", onHttpDeleteDone)

deleteHTTP("https://httpbin.org/delete")
deleteHTTP("https://httpbin.org/delete", {["X-am-I-awesome"] = "yep I am"})

customHTTP

命令格式:
deleteHTTP(url, headersTable)
向给定的URL发送自定义方法请求。
例子:

function onCustomHttpDone(_, url, body, method)
  cecho(string.format("<white>url: <dark_green>%s<white>, body: <dark_green>%s<white>, method: <dark_green>%s", url, body, method))
end

registerAnonymousEventHandler("sysCustomHttpDone", sysCustomHttpDone)

customHTTP("PATCH", "this us a request with custom headers", "https://httpbin.org/put", {["X-am-I-awesome"] = "yep I am"})
customHTTP("PATCH", "https://httpbin.org/put", "<fill in file location to upload here>")

字符串函数

用于操作字符串的函数的集合。

addWordToDictionary

命令格式:
addWordToDictionary(word)
将给定的单词添加到自定义配置文件或共享词典中(以首选项中选择的为准)。
例子:

addWordToDictionary("黑暗的风")
addWordToDictionary("норм")

-- 示例-使用返回值的函数

function rememberPlayerName(name)
  if addWordToDictionary(name) then
    echo("Added '" .. name .. "' to dictionary...\n")
  end
end

cecho2string

命令格式:
plainText = cecho2string(formattedText)
从传入的字符串中剥离文本格式,只留下文本。
例子:

local exampleString = "<red>Formatted <b>string</b>"
local plainText = cecho2string(exampleString)
-- "Formatted string"

decho2string

命令格式:
plainText = decho2string(formattedText)
从传入的字符串中剥离文本格式,只留下文本。
例子:

local exampleString = "<255,0,0>Formatted <b>string</b>"
local plainText = decho2string(exampleString)

f

命令格式:
formattedString = f(str)
允许您使用以下方法将变量和函数组合为文本(字符串插值)
例子:

-- old way:
cecho("\nHello, "..matches[2]..", how is it going?")

-- new way:
cecho(f("\nHello {matches[2]}, how is it going?"))

testResult = "successful"
-- old way:
echo("The test was "..testResult.."\n")
-- with f:
echo(f("The test was {testResult}\n"))
-- echoes "The test was successful\n"

local testResult = "a failure"
echo(f("The test was {testResult}\n"))
-- echoes "The test was a failure\n" as it sees the local scope over global.

-- You can also execute simple expressions
echo(f("2 + 2 = {2 + 2}\n"))
-- echoes "2 + 2 = 4\n"

-- Or more complicated ones
local function testFunc(item)
  return item:title()
end

echo(f("You should properly capitalize names, such as {testFunc('marilyn')}\n"))
-- echoes "You should properly capitalize names, such as Marilyn\n"

echo(f("You should properly capitalize names, such as {string.title('robert')}\n")
-- same thing, but uses string.title directly and Robert instead of Marilyn

function formatter2000()
  local upvalue = "2000"
  local formatter = function() 
    echo(f("Let's evaluate: {upvalue}\n"))
  end
  formatter() -- here evaulation inside f function will work
  return formatter
end

formatter2000()() -- here evaluation inside f function will return nil
-- result
-- Let's evaluate: 2000
-- Let's evaulate: nil

You can work around this by doing the following
您可以通过执行以下操作来解决此问题

function formatter2000()
  local upvalue = "2000"
  local formatter = function()
    local upvalue = upvalue  -- this keeps upvalue in scope for the function later
    echo(f("Let's evaluate: {upvalue}\n"))
  end
  formatter() -- here evaulation inside f function will work
  return formatter
end

formatter2000()() -- here evaluation inside f function will return 2000 once again

-- result
-- Let's evaluate: 2000
-- Let's evaulate: 2000

小心! 在闭包内使用时,如果调用闭包时变量超出作用域,则可能无法正确解析变量。

getDictionaryWordList

命令格式:
getDictionaryWordList()
返回配置文件或共享自定义词典单词列表

hecho2string

命令格式:
plainText = hecho2string(formattedText)
从传入的字符串中剥离文本格式,只留下文本。

removeWordFromDictionary

命令格式:
removeWordFromDictionary(word)
已将给定的单词删除到自定义配置文件或共享词典中(以首选项中选择的为准)。

spellCheckWord

命令格式:
spellCheckWord(word, [customDictionary])
根据自定义词典或系统词典对给定单词进行拼写检查。

-- spellcheck against the language dictionary
if spellCheckWord("run") then
  echo("'run' is spelled ok!\n")
end

-- spellcheck against the custom 'add word to dictionary'
if spellCheckWord("Darkwind", true) then
  echo("'Darkwind' is spelled OK!\n")
end

spellSuggestWord

命令格式:
spellSuggestWord(word, [customDictionary])
为给定的单词建议相似的单词。

string.byte, utf8.byte

命令格式:
string.byte(string [, i [, j]]) or utf8.byte(string [, i [, j]])
mystring:byte([, i [, j]]) 返回字符的内部数字代码。

-- the following call will return the ASCII values of "A", "B" and "C"
a, b, c = string.byte("ABC", 1, 3)
echo(a .. " - " .. b .. " - " .. c) -- shows "65 - 66 - 67"

-- same for the international version but with the Unicode values
a, b, c = utf8.byte("дом", 1, 3)
echo(a .. " - " .. b .. " - " .. c) -- shows "1076 - 1086 - 1084"

string.char, utf8.char

命令格式:
string.char(···) or utf8.char(···)
接收零个或多个整数。返回长度等于参数数的字符串,其中每个字符的内部数字代码等于其相应参数。

mystring = utf8.char(1076,1086,1084)
print(mystring)

string.cut

命令格式:
string.cut(string, maxLen)
将字符串剪切到指定的最大长度。

string.dump

命令格式:
string.dump()
将函数转换为二进制字符串。 您可以稍后使用loadstring()函数来恢复该函数。
可以很好地处理英语和非英语文本。

testString = string.dump(function() echo("this is a string") end)
--The following should then echo "this is a string"
loadstring(testString)()

string.enclose

命令格式:
string.enclose(string)
manual包裹字符串

string.ends

命令格式:
string.ends(String, Suffix)
测试字符串是否以指定后缀结尾。

string.find, utf8.find

命令格式:
string.find(text, pattern [, init [, plain]]) or utf8.find
查找字符串文本中第一个匹配的模式。如果找到匹配项,find返回文本索引,该文本的开始和结束位置;否则,返回nil。第三个可选的数值参数init指定从何处开始搜索;其默认值为1,可以为负值。第四个可选参数为true,plain会关闭模式匹配功能,因此该函数执行一个普通的“查找子字符串”操作,模式中没有字符被认为是“神奇”的。请注意,如果给出了plain,那么也必须给出init。
例子:

-- check if the word appears in a variable
if string.find(matches[2], "rabbit") then
  echo("Found a rabbit!\n")
end

-- the following example will print: "3, 4"
local start, stop = string.find("This is a test.", "is")
if start then
   print(start .. ", " .. stop)
end
-- note that here "is" is being found at the end of the word "This", rather than the expected second word

-- to make it match the word on its own, prefix %f[%a] and suffix %f[%A]
if string.find("This is a test", "%f[%a]is%f[%A]") then
  echo("This 'is' is the actual stand-alone word\n")
end

string.findPattern

命令格式:
string.findPattern(text, pattern)
返回第一个匹配的子字符串或nil。

string.format

命令格式:
string.format(formatstring,…)
返回其可变数量参数的格式化版本,遵循其第一个参数(必须是字符串)中给出的描述。格式字符串遵循与标准C函数的printf家族相同的规则。唯一的区别是不支持选项/修饰符 *、l、L、n、p和h,并且存在一个额外的选项q。q选项将字符串格式化为适合Lua解释器安全读回的格式:字符串写在双引号之间,并且字符串中的所有双引号、换行符、嵌入的零和反斜杠在写入时都被正确地转义。
选项c、d、E、e、f、g、G、i、o、u、X和x都期望一个数字作为参数,而q和s期望一个字符串。

string.genNocasePattern

命令格式:
string.genNocasePattern(template)
从字符串生成不区分大小写的搜索模式。

string.gfind

命令格式:
string.gfind()
这是现在string.gmatch的旧版本。请使用string.gmatch。

string.gmatch, utf8.gmatch

命令格式:
string.gmatch(text, pattern) or utf8.gmatch
返回一个迭代器函数,每次调用该函数时,返回下一个从字符串文本上的模式捕获。如果pattern指定没有捕获,则在每次调用中生成整个匹配。

s = "hello world from Lua"
     for w in string.gmatch(s, "%a+") do
       print(w)
     end

将遍历字符串s中的所有单词,每行打印一个单词。下一个示例将给定字符串中的所有对key=value收集到一个表中:

t = {}
     s = "from=world, to=Lua"
     for k, v in string.gmatch(s, "(%w+)=(%w+)") do
       t[k] = v
     end

对于这个函数,模式开始处的“^”不能作为锚点,因为这会阻止迭代。

string.gsub, utf8.gsub

命令格式:
string.gsub(text, pattern, repl [, n]) or utf8.gsub
返回一个文本的副本,其中模式的所有(或前n个,如果给定)出现都已被repl指定的替换字符串替换,该字符串可以是字符串、表或函数。gsub还返回发生的匹配的总数作为其第二个值。
例子:

x = string.gsub("hello world", "(%w+)", "%1 %1")
     --> x="hello hello world world"
     
     x = string.gsub("hello world", "%w+", "%0 %0", 1)
     --> x="hello hello world"
     
     x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
     --> x="world hello Lua from"
     
     x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
     --> x="home = /home/roberto, user = roberto"
     
     x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
           return loadstring(s)()
         end)
     --> x="4+5 = 9"
     
     local t = {name="lua", version="5.1"}
     x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
     --> x="lua-5.1.tar.gz"

string.len, utf8.len

命令格式:
string.len(string) or utf8.len(string)
接收字符串并返回其长度。空字符串“”的长度为0。嵌入的零被计数,因此“a\000bc\000”的长度为5。
例子:

print(string.len("hello"))

-- international version
print(utf8.len("слово"))

string.lower, utf8.lower

命令格式:
string.lower(string) or utf8.lower(string)
接收一个字符串并返回此字符串的副本,其中所有大写字母都更改为小写。所有其他字符保持不变。大写字母的定义取决于当前的语言环境。

string.match, utf8.match

命令格式:
string.match(text, pattern [, init]) or utf8.match()
查找字符串文本中第一个匹配的模式。如果它找到了一个,那么match将返回来自模式的捕获;否则返回nil。如果pattern指定没有捕获,则返回整个匹配项。第三个可选的数值参数init指定从何处开始搜索;其默认值为1,可以为负值。

string.patternEscape, utf8.patternEscape

命令格式:
escapedString = string.patternEscape(str) or escapedString = utf8.patternEscape(str)
返回str的一个版本,所有Lua模式字符转义,以确保string。match/find/etc查找原始str。

例子:

-- searching for a url inside of a string. 
local helpString = [[
This feature can be accessed by going to https://some-url.com/athing.html?param=value and
retrieving the result!
]]
local url = "https://some-url.com/"
display(helpString:find(url))
-- nil
display(helpString:find(string.patternEscape(url)))
-- 42
-- 62
display(url:patternEscape())
-- "https://some%-url%.com/"

string.rep

命令格式:
string.rep(String, n)
返回一个字符串,该字符串是字符串的n个副本 .

string.reverse, utf8.reverse

命令格式:
string.reverse(string) or utf8.reverse(string)
返回一个字符串,该字符串是 string反转 .

string.split

命令格式:
string.split(string, delimiter)
按给定的分隔符将字符串拆分为表。可以使用上面的第二种形式对字符串(或包含字符串的变量)调用。

string.starts

命令格式:
string.starts(string, prefix)
测试字符串是否以指定前缀开头。 返回true或false

string.sub, utf8.sub

命令格式:
string.sub(text, i [, j]) or utf8.sub()
返回从i开始并持续到j的文本子串; i和j可以是负的。如果j不存在,则假定它等于-1(与字符串长度相同)。特别是,调用string.sub(text,1,j)返回长度为j的文本前缀,string.sub(text,-i)返回长度为i的文本后缀。

string.title

命令格式:
string.title(string)
将字符串中的第一个字符大写。

string.trim

命令格式:
string.trim(string)
修剪字符串,删除文本开头和结尾处的所有“多余”空格。

string.upper, utf8.upper

命令格式:
string.upper(string) or utf8.upper(string)
接收一个字符串并返回此字符串的副本,其中所有小写字母都已更改为大写字母。所有其他字符保持不变。小写字母的定义取决于当前的语言环境。

utf8.charpos

utf8.remove

命令格式:
utf8.remove(string[, start[, stop]])
从给定字符串中移除字符。

utf8.title

命令格式:
utf8.title(string)
返回字符串的大写版本,以用于不区分大小写的比较。如果字符串是一个数字,它被视为一个代码点,并返回转换后的代码点(作为一个数字)。

utf8.width

命令格式:
utf8.width(string[, ambi_is_double[, default_width]])
计算给定字符串的宽度。如果字符串是一个码位,则返回此码位的宽度。

utf8.widthindex

命令格式:
utf8.widthindex(string, location[, ambi_is_double[, default_width]])
返回给定字符串中位置的字符索引以及偏移量和宽度。这是utf8.width()的反向操作。

表函数

这些函数用于操作表。通过它们,您可以添加到表中,删除值,检查表中是否存在值,检查表的大小等等。

spairs

命令格式:
spairs(tbl, sortFunction)
返回一个类似于pairs(tbl)的迭代器,但在迭代之前对键进行排序。
例子:

local tbl = { Tom = 40, Mary = 50, Joe = 23 }

-- This iterates, sorting based on the key (which is the name in this case)
for name, thingies in spairs(tbl) do
  echo(string.format("%s has %d thingies\n", name, thingies))
end
--[[
Joe has 23 thingies
Mary has 50 thingies
Tom has 40 thingies
--]]

-- The function used below sorts based on the value. 
for name, thingies in spairs(tbl, function(t,a,b) return t[a] < t[b] end) do --iterate from lowest value to highest
  echo(string.format("%s has %d thingies\n", name, thingies))
end
--[[
Joe has 23 thingies
Tom has 40 thingies
Mary has 50 thingies
--]]

-- This function can be used to sort a group of Geyser gauges based on their value (what percentage of the gauge is filled)
local gaugeSort = function(t,a,b)
    local avalue = t[a].value or 100 -- treat non-gauges as though they are full gauges. If you know for -sure- the table only has gauges the 'or 100' is not needed.
    local bvalue = t[b].value or 100
    return avalue < bvalue
end
for _,gauge in spairs(tblOfGauges, gaugeSort) do
  -- do what you want with the gauges. First one will be the least full, then the next least full, until the last which will be the most full. 
  -- If you replace the < with a > it will go from most full to least full instead.
end

table.collect

命令格式:
spairs(tbl, sortFunction)
返回一个表,该表是来自tbl的func(key,value)返回true的每个键值对
参数:包含tbl中导致func(key,value)返回true的所有键/值对的表 tbl: 要从中收集项目的表 func: 用于测试是否应该收集某项的函数 返回: 例子:

local vitals = { hp = 3482, maxhp = 5000, mana = 3785, maxmana = 5000 }
local pullHpKeys = function(key, value)
  if string.match(key, "hp") then return true end
end
local hp_values = table.collect(vitals, pullHpKeys)
display(hp_values)

This prints the following: 这将打印以下内容:

{
  hp = 3482,
  maxhp = 5000
}

table.complement

命令格式:
table.complement (set1, set2)
返回一个表,该表是第一个表相对于第二个表的相对补数。返回键/值对的补码。即 包含table 1中与table 2中的键/值对不匹配的所有键/值对的表。

local t1 = {key = 1,1,2,3}
local t2 = {key = 2,1,1,1}
local comp = table.complement(t1,t2)
display(comp)

This prints the following: 这将打印以下内容:

  key = 1,
  [2] = 2,
  [3] = 3

table.concat

命令格式:
table.concat(table, delimiter, startingindex, endingindex)
将表联接为字符串。每个项目必须是可以转换成字符串的东西。
delimiter:分隔符 例子:

--This shows a basic concat with none of the optional arguments
testTable = {1,2,"hi","blah",}
testString = table.concat(testTable)
--testString would be equal to "12hiblah"

--This example shows the concat using the optional delimiter
testString = table.concat(testTable, ", ")
--testString would be equal to "1, 2, hi, blah"

--This example shows the concat using the delimiter and the optional starting index
testString = table.concat(testTable, ", ", 2)
--testString would be equal to "2, hi, blah"

--And finally, one which uses all of the arguments
testString = table.concat(testTable, ", ", 2, 3)
--testString would be equal to "2, hi"

table.contains

命令格式:
table.contains (t, value)
确定一个表是包含一个值作为键还是一个值(从Mudlet 4.8+开始递归)。
例子:

local test_table = {"value1", "value2", "value3", "value4", "value5", "value6", "value7"}
if table.contains(test_table, "value1") then 
   print("Got value 1!")
else
   print("Don't have it. Sorry!")
end

-- if the table has just a few values, you can skip making a local, named table:
if table.contains({"Anna", "Alanna", "Hanna"}, "Anna") then 
   print("Have 'Anna' in the list!")
else
   print("Don't have the name. Sorry!")
end

-- don't forget, it will return true if the item is a key in the table as well
display(table.contains({"bob"}, 1) -- displays true, as 1 is the key/index for "bob"
-- If you really only want to check values, try table.index_of, which returns the key a value is found at, or nil if it is not found.

table.deepcopy

命令格式:
table.deepcopy (table)
返回表的完整副本

table.intersection

命令格式:
table.intersection (set1, set2)
返回一个表,该表是第一个表相对于第二个表的相对交集。返回键/值对的交集。

table.insert

命令格式:
table.insert(table, [pos,] value)
在pos位置 插入元素 value值

table.index_of

命令格式:
table.index_of(table, value)
返回索引表中项的索引(位置),如果未找到则返回nil。可以把它看作是一个table.find函数(尽管它被称为table.index_of)。

table.is_empty

命令格式:
table.is_empty(table)
检查表是否空表

table.keys

命令格式:
table.keys(table)
返回一个表,该表是传入的表所使用的键的集合

table.load

命令格式:
table.load(location, table)
将表从外部文件加载到mudlet中。 要加载到的表-它必须已经存在。

例子:

mytable = mytable or {}
if io.exists(getMudletHomeDir().."/mytable.lua") then
  table.load(getMudletHomeDir().."/mytable.lua", mytable) -- using / is OK on Windows too.
end

table.matches

命令格式:
table.matches(tbl, pattern, [pattern2], [pattern_n], [check_keys])
返回tbl中的键值对表,当通过string. match检查时,这些键值对匹配提供的模式之一。这个函数不是递归的-tbl中的嵌套表不会被检查,只检查顶层。
例子:

local items = { this = "that", hp = 400, [4] = "toast", something = "else", more = "keypairs" }
local matches = table.matches(items, "%d")
-- here matches will be { hp = 400 }
local matches = table.matches(items, "%d", "that", true)
-- here matches will be { hp = 400, this = "that", [4] = "toast" }

table.maxn

命令格式:
table.maxn(table)
返回给定表的最大正数索引,如果表没有正数索引,则返回零。(To该函数对整个表进行线性遍历。

table.n_collect

命令格式:
table.n_collect(tbl, func(value))
返回一个表,其中包含tbl中的每个唯一值,其中func(value)返回true。忽略key。返回的表是ipairs可迭代的。

local items = { 
  this = "that",
  other = "thing",
  otter = "potato",
  honey = "bee"
}
local beginsWithTH = function(value)
  if string.match(value, "^th") then return true end
end
local nmatches = table.n_collect(items, beginsWithTH)
-- nmatches will be { "that", "thing" }
-- the order will not necessarily be preserved

table.n_filter

命令格式:
table.n_filter(table, function(element[, index[, table]]))
返回一个新表,其中包含通过所提供函数实现的测试的所有元素。如果没有元素通过测试,将返回一个空表。

-- 过滤掉小值:

local function isBigEnough(value) return value >= 10 end
local filtered = table.n_filter({12, 5, 8, 130, 44}, isBigEnough)
-- filtered: {12, 130, 44}

-- 筛选出无效条目:

local invalidEntries = 0
local entries = {
  { id = 15 }, { id = -1 }, { id = 0 }, { id = 3 },
  { id = 12.2 }, { }, { id = nil }, { id = false },
  { id = 'not a number' }
}

local function isNumber(t) return t and type(t) == 'number' end
local function filterByID(item)
  if isNumber(item.id) and item.id ~= 0 then
    return true
  end
  invalidEntries = invalidEntries + 1
  return false
end

local entriesByID = table.n_filter(entries, filterByID)
-- invalidEntries: 5
-- entriesByID: { { id = 15 }, { id = -1 }, { id = 3 }, { id = 12.2 } }

-- 根据搜索条件筛选出内容:

local fruits = {'apple', 'banana', 'grapes', 'mango', 'orange'}
local function filterItems(t, query)
  return table.n_filter(t, function(item)
    return item:lower():find(query:lower())
  end)
end
filterItems(fruits, 'ap') -- {'apple', 'grapes'}
filterItems(fruits, 'an') -- {'banana', 'mango', 'orange'}

table.n_flatten

命令格式:
table.n_flatten(table)
返回一个新表,其中子表元素串联到其中。

local t1 = {1, 2, {3, 4}};
local t2 = {1, 2, {3, 4, {5, 6}}};
local t3 = {1, 2, {3, 4, {5, 6, {7, 8, {9, 10}}}}};
table.n_flatten(t1) -- {1, 2, 3, 4}
table.n_flatten(t2) -- {1, 2, 3, 4, 5, 6}
table.n_flatten(t3) -- {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

table.n_matches

命令格式:
table.n_matches(tbl, pattern, [pattern2], [patternN])
返回tbl中唯一值的表,其中一个提供的模式使用string.match匹配

pattern:要使用string.match检查每个值的模式。您可以提供多个模式,用逗号分隔

table.n_union

命令格式:
table.n_union (table1, table2)
返回一个数字索引表,它是所提供的表的并集(即-将两个索引列表合并在一起)。这是一个独特价值的结合。不保留输入表的顺序和键。

display(table.n_union({"bob", "mary"}, {"august", "justinian"}))

{
  "bob",
  "mary",
  "august",
  "justinian"
}

table.n_complement

命令格式:
table.n_complement (set1, set2)
返回一个表,该表是第一个数值索引表相对于第二个数值索引表的相对补数。返回数值索引的补码。

table.n_intersection

命令格式:
table.n_intersection (…)
返回一个数字索引表,该表是提供的表的交集。这是唯一值的交集。不保留输入表的顺序和键

table.pickle

命令格式:
table.pickle( t, file, tables, lookup )
table.save()用于序列化数据的内部函数

table.remove

命令格式:
table.remove(table, value_position)
按值在表中的位置从索引表中移除值。

table.save

命令格式:
table.save(location, table)
将表保存到外部文件中 location位置.
例子:

table.save(getMudletHomeDir().."/mytable.lua", mytable)

table.sort

命令格式:
table.sort(Table [, comp])
按给定算法排序.

table.size

命令格式:
table.size (t)
返回键值表的大小(此函数必须遍历所有表以计数所有元素)。

table.unpickle

命令格式:
table.unpickle( t, tables, tcopy, pickled )
table.load()用于反序列化的内部函数。

table.update

命令格式:
table.update(table1, table2)
返回一个表,其中table 2中的键/值对被添加到table 1中,并且两个表中存在的任何键都被分配了table 2中的值,这样结果表就可以使用table 2中的信息更新table 1。

table.union

命令格式:
table.union(…)
返回一个表,该表是提供的表的并集。这是键/值对的并集。如果两个或多个表包含与相同键关联的不同值,则返回表中的键将包含一个包含所有相关值的子表。有关值的并集,请参见表.n_union()。请注意,由于ipairs()保留了键,结果表可能无法可靠地使用ipairs()遍历。如果数值索引中存在间隙,ipairs()将停止遍历。

tableA = {
   [1] = 123,
   [2] = 456,
   ["test"] = "test",
}
---
tableB = {
   [1] = 23,
   [3] = 7,
   ["test2"] = function() return true end,
}
---
tableC = {
   [5] = "c",
}
---
table.union(tableA, tableB, tableC)
-- will return the following:
{
   [1] = {
      123,
      23,
   },
   [2] = 456,
   [3] = 7,
   [5] = "c",
   ["test"] = "test",
   ["test2"] = function() return true end,
}

文本转语音函数

这些功能可以让Mudlet为你说话(从书面文字中听到的声音)。查看文本到语音手册以了解更多关于这一切如何一起工作的细节。

还有几个Mudlet事件是可用的功能:

  ttsSpeechStarted
  ttsSpeechReady
  ttsSpeechQueued
  ttsSpeechPaused
  ttsSpeechError
  ttsPitchChanged
  ttsRateChanged
  ttsVoiceChanged

ttsClearQueue

命令格式:
ttsClearQueue([index])
如果您已经排队了几行文本,现在想删除其中的一部分或全部,这个函数将有所帮助。

ttsGetCurrentLine

命令格式:
ttsGetCurrentLine()
如果您想分析当前是否说过或说了什么,这个功能适合您。

ttsGetCurrentVoice

命令格式:
ttsGetCurrentVoice()
如果您的系统上有多个可用的语音,您可能需要检查当前正在使用的是哪一个。

ttsGetPitch

命令格式:
ttsGetPitch()
如果你想分析你当前演讲的音调或音调。

ttsGetQueue

命令格式:
ttsGetPitch()
此功能可用于显示当前文本队列或其中任何单个文本。

ttsGetRate

命令格式:
ttsGetRate()
如果你想分析你当前讲话的速率或速度。以介于1(快)和-1(慢)之间的数字形式返回当前速率。

ttsGetState

命令格式:
ttsGetState()
通过这个函数,您可以找到语音引擎的当前状态。
返回以下之一:ttsSpeechReady、ttsSpeechPaused、ttsSpeechStarted、ttsSpeechError、ttsUnknownState。

ttsGetVoices

命令格式:
ttsGetVoices()
列出当前操作系统和语言设置可用的所有语音。当前使用默认的系统区域设置。

ttsGetVolume

命令格式:
ttsGetVolume()
如果你想分析你当前讲话的音量。以介于1(大声)和0(安静)之间的数字形式返回当前音量。

ttsPause

命令格式:
ttsPause()
暂停当前正在说的语音(如果有的话)。不同操作系统(Windows/macOS/Linux)上的引擎表现不同-暂停可能根本不起作用,可能需要几秒钟才能生效,或者可能会立即暂停。一些引擎会寻找一个可以稍后恢复的休息,例如句子结束。

ttsQueue

命令格式:
ttsQueue(text to queue, [index])ttsQueue(text to queue,[index])
这个函数会将给定的文本添加到您的语音队列中。队列中的文本将一个接一个地读出。这与ttsSpeak相反,ttsSpeak会立即打断任何口语文本。队列可以被查看和修改,而它们的内容还没有被说出。
例子 :

ttsQueue("We begin with some text")
ttsQueue("And we continue it without interruption")
display(ttsGetQueue())
-- will show the queued texts as follows
-- (first line ignored because it's being spoken and is not in queue):
-- {
--   "And we continue it without interruption"
-- }

ttsResume

命令格式:
ttsResume()
恢复先前所说的讲话(如果有发言被暂停)。

ttsSpeak

命令格式:
ttsSpeak(text to speak)
这将立即用当前选择的语音说出给定的文本。任何当前说出的文本都将被中断(使用语音队列代替将语音排队)。

ttsSetPitch

命令格式:
ttsSetPitch(pitch)
设置语音播放的音调或音调。应在1和-1之间,否则将受到限制。

-- talk deeply first, after 2 seconds talk highly, after 4 seconds normally again
ttsSetPitch(-1)
ttsQueue("Deep voice")

tempTimer(2, function()
  ttsSetPitch(1)
  ttsQueue("High voice")
end)

tempTimer(4, function()
  ttsSetPitch(0)
  ttsQueue("Normal voice")
end)

ttsSetRate

命令格式:
ttsSetRate(rate)
设置语音播放的速率或速度。在macOS和Windows上,调整系统速率会自动调整此值。应在1和-1之间,否则将受到限制。

-- talk slowly first, after 2 seconds talk quickly, after 4 seconds normally again
ttsSetRate(-1)
ttsQueue("Slow voice")

tempTimer(2, function ()
  ttsSetRate(1)
  ttsQueue("Quick voice")
end)

tempTimer(4, function ()
  ttsSetRate(0)
 ttsQueue("Normal voice")
end)

ttsSetVolume

命令格式:
ttsSetVolume(volume)
设置语音播放的音量。在macOS上,调整系统速率会自动调整此值。应介于1和0之间

-- talk quietly first, after 2 seconds talk a bit louder, after 4 seconds normally again
ttsSetVolume(0.2)
ttsSpeak("Quiet voice")

tempTimer(2, function ()
  ttsSetVolume(0.5)
  ttsSpeak("Low voice")
end)

tempTimer(4, function () 
  ttsSetVolume(1)
  ttsSpeak("Normal voice")
end)

ttsSetVoiceByIndex

命令格式:
ttsSetVoiceByIndex(index)
如果您有多个语音可用,您可以使用此函数切换它们,方法是给定它们的索引位置,如从ttsGetVoices()收到的表格所示。如果您知道他们的名字,也可以使用ttsSetVoiceByName。在macOS和Windows上,调整系统语音会自动调整此值。

display(ttsGetVoices())
ttsSetVoiceByIndex(1)

ttsSetVoiceByName

命令格式:
ttsSetVoiceByName(name)
如果您有多个语音可用,并且已经知道它们的名称,您可以使用此功能切换它们。在macOS和Windows上,调整系统语音会自动调整此值。

ttsSkip

命令格式:
ttsSkip()
跳过当前文本行。
例子:

ttsQueue("We hold these truths to be self-evident")
ttsQueue("that all species are created different but equal")
ttsQueue("that they are endowed with certain unalienable rights")
tempTimer(2, function () ttsSkip() end)

用户界面函数

帮助您构造自定义GUI的所有函数。它们主要处理miniconsole/标签/仪表的创建和操作,以及在屏幕上显示或格式化信息。

addCommandLineMenuEvent

命令格式:
addCommandLineMenuEvent([window,] label, eventName)
将项添加到与命令行关联的鼠标右键单击菜单中。 参数: window: 命令行所属窗口。可选,将默认为“main”(主窗口控制台) label: 项目标签 eventName: 单击时将激发的事件名称。 例子:

addCommandLineMenuEvent("My very own special paste from clipboard", "pasteFromClipboardWithoutLineBreaks" )
registerAnonymousEventHandler("pasteFromClipboardWithoutLineBreaks", function()
  local text = string.gsub(getClipboardText(), "[\r|\n]", "")
  appendCmdLine(text)
end)

addMouseEvent

命令格式:
addMouseEvent(uniqueName, eventName, [displayName, tooltipText])
右键单击控制台窗口时注册新的上下文菜单选项。如果已成功添加事件将返回 true ,否则为 nil+message会被归还。如果 displayName 还没有设定, uniqueName将用于菜单标签。 按这个顺序。应该是一个Mudlet事件,它将处理包括 event, unique name, window name 选择左上角 column and 和 row和选择右下角 column 和 row 这旨在与可用的光标函数一起使用,以满足任何选择或处理需要。
参数: uniqueName: 鼠标事件的唯一标识符。 eventName: 将处理数据的Mudlet事件的名称。 displayName: (可选)鼠标关联菜单的标签文本。如果未设置,则标签默认为 uniqueName. tooltipText: (可选)鼠标悬停在选项上时的工具提示文本。如果未设置,将看不到任何工具提示。 例子:

-- An example showing implementing a hecho-friendly copy option:

addMouseEvent("hecho copy", "onMouseCopyExample")

function rgbToHex(r,g,b)
    local rgb = (r * 0x10000) + (g * 0x100) + b
    return string.format("#%x", rgb)
end

function onMouseCopyExample(event, menu, window, startCol, startRow, endCol, endRow)
  -- Check whether there's an actual selection
  if startCol == endCol and startRow == endRow then return end
  local parsed = ""
  local lastColor = nil
  -- Loop through each symbol within the range
  for l = startRow, endRow do
    local cStart = l == startRow and startCol or 0
    moveCursor(window, cStart, l)
    local cEnd = l == endRow and endCol or #getCurrentLine() - 1
    for c = cStart, cEnd do
      selectSection(window, c, 1)
      local symbol = getSelection(window) or ""
      -- Convert the foreground color to a hex format, suitable for hecho
      local color = rgbToHex(getFgColor(window))
      -- Don't repeat the color if previous one was the same
      if color == lastColor then
        parsed = parsed .. symbol
      else
        lastColor = color
        parsed = parsed .. color .. symbol
      end
    end
    if l ~= endRow then parsed = parsed .. "\n" end
  end
  setClipboardText(parsed)
end

registerAnonymousEventHandler("onMouseCopyExample", "onMouseCopyExample")

ansi2decho

命令格式:
ansi2decho(text, default_colour)
转换ANSI颜色序列到涉及可由decho()函数处理的颜色文字标签。
参数:
text: 包含应替换的ANSI颜色序列的字符串。 default_colour: 可选- ANSI默认颜色代码(处理孤立粗体标记时使用)。 返回: string text: 已转换的文本已显示有效。 string colour: 替换中最后使用的颜色的ANSI代码(如果要根据此颜色为后续行着色,则很有用)。

 local replaced = ansi2decho('\27[0;1;36;40mYou say in a baritone voice, "Test."\27[0;37;40m')
-- 'replaced' should now contain <r><0,255,255:0,0,0>You say in a baritone voice, "Test."<r><192,192,192:0,0,0>
decho(replaced)

ansi2string

命令格式:
ansi2string(text)
从字符串(文本)中剥离ANSI颜色序列
参数:
text: 包含应删除的ANSI颜色序列的字符串。

appendBuffer

命令格式:
appendBuffer(name)
粘贴以前复制的富文本(包括颜色等文本格式)用户窗口名。
参数:
name: 要粘贴到的用户窗口的名称。作为字符串传递。

--selects and copies an entire line to user window named "Chat"
selectCurrentLine()
copy()
appendBuffer("Chat") 

bg

命令格式:
bg([window, ]colorName)
更改文本的背景色。用于突出显示文本。

calcFontSize

命令格式:
calcFontSize(window_or_fontsize, [fontname])
返回特定窗口中字符的平均高度和宽度,或字体名称和大小组合。如果您想将迷你窗口的尺寸调整到特定的尺寸,这很有帮助。

-this snippet will calculate how wide and tall a miniconsole designed to hold 4 lines of text 20 characters wide
--would need to be at 9 point font, and then changes miniconsole Chat to be that size
local width,height = calcFontSize(9)
width = width * 20
height = height * 4
resizeWindow("Chat", width, height)

cecho

命令格式:
cecho([window], text)
回显文本,可以轻松地使用彩色、斜体、粗体、删除线和下划线标记格式化。您还可以在其中包含unicode字符.

cecho("Hi! This text is <red>red, <blue>blue, <green> and green.")

cecho("<:green>Green background on normal foreground. Here we add an <ivory>ivory foreground.")

cecho("<blue:yellow>Blue on yellow text!")

cecho("\n<red>Red text with <i>italics</i>, <u>underline</u>, <s>strikethrough</s>, <o>overline</o>, and <b>bold</b>.")

cecho("\n<green><o><u>Green text with over and underline at the same time.</o></u>")

-- \n adds a new line
cecho("<red>one line\n<green>another line\n<blue>last line")

cecho("myinfo", "<green>All of this text is green in the myinfo miniconsole.")

cecho("<green>(╯°□°)<dark_green>╯︵ ┻━┻")

cecho("°º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸")

cecho([[
 ██╗    ██╗     ██╗███╗   ██╗███████╗     █████╗ ██████╗ ████████╗
███║    ██║     ██║████╗  ██║██╔════╝    ██╔══██╗██╔══██╗╚══██╔══╝
╚██║    ██║     ██║██╔██╗ ██║█████╗      ███████║██████╔╝   ██║
 ██║    ██║     ██║██║╚██╗██║██╔══╝      ██╔══██║██╔══██╗   ██║
 ██║    ███████╗██║██║ ╚████║███████╗    ██║  ██║██║  ██║   ██║
 ╚═╝    ╚══════╝╚═╝╚═╝  ╚═══╝╚══════╝    ╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝
]])

命令格式:
cechoLink([windowName], text, command, hint, true)
在当前选定行的末尾将一段文本作为可单击的链接回显-类似于cecho()此版本允许您在链接文本中使用颜色。

-- echo a link named 'press me!' that'll send the 'hi' command to the game
cechoLink("<red>press <brown:white>me!", function() send("hi") end, "This is a tooltip", true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
cechoLink("<red>press <brown:white>me!", [[send("hi")]], "This is a tooltip", true)

cecho2ansi

命令格式:
ansiFormattedString = cecho2ansi(text)
将cecho格式的文本转换为ansi格式的文本。由cfeedTriggers使用,但如果您出于任何其他原因需要ansi格式的文本,则很有用。

feedTriggers(cecho2ansi("\n<red>This is red.<reset> <i>italic</i>, <b>bold</b>, <s>strikethrough</s>, <u>underline</u>\n"))

cechoPopup

命令格式:
cechoPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
创建文本,该文本具有可左键单击的链接,以及在当前行末尾的右键单击菜单以查看更多选项,如 cecho() 添加的文本在被左键单击时将执行列表中的第一个命令。右键单击后,它将显示一个包含所有可能命令的菜单。菜单将填充提示,每行一个提示。

-- Create some text as a clickable with a popup menu:
cechoPopup("<red>activities<reset> to do", {function() send "sleep" end, function() send "sit" end, function() send "stand" end}, {"sleep", "sit", "stand"}, true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
cechoPopup("<red>activities<reset> to do", {[[send "sleep"]], [[send "sit"]], [[send "stand"]]}, {"sleep", "sit", "stand"}, true)

命令格式:
cinsertLink([windowName], text, command, hint, true)
在当前光标位置的末尾将文本作为可单击链接回显-类似于 cinsertText()此版本允许您在链接文本中使用颜色。

-- echo a link named 'press me!' that'll send the 'hi' command to the game
cinsertLink("<red>press <brown:white>me!", function() send("hi") end, "This is a tooltip", true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
cinsertLink("<red>press <brown:white>me!", [[send("hi")]], "This is a tooltip", true)

cinsertPopup

命令格式:
cinsertPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
创建文本,该文本具有可左键单击的链接,以及在当前光标位置末尾的右键单击菜单以查看更多选项,如 cinsertText(), 添加的文本在被左键单击时将执行列表中的第一个命令。右键单击后,它将显示一个包含所有可能命令的菜单。菜单将填充提示,每行一个提示。

-- Create some text as a clickable with a popup menu:
cinsertPopup("<red>activities<reset> to do", {function() send "sleep" end, function() send "sit" end, function() send "stand" end}, {"sleep", "sit", "stand"}, true)

-- Create some text as a clickable with a popup menu:
cinsertPopup("<red>activities<reset> to do", {[[send "sleep"]], [[send "sit"]], [[send "stand"]]}, {"sleep", "sit", "stand"}, true)

cinsertText

命令格式:
cinsertText([window], text)
在当前光标位置插入文本,有可能使用颜色标签。

cinsertText("Hi! This text is <red>red, <blue>blue, <green> and green.")

cinsertText("<:green>Green background on normal foreground. Here we add an <ivory>ivory foreground.")

cinsertText("<blue:yellow>Blue on yellow text!")

cinsertText("myinfo", "<green>All of this text is green in the myinfo miniconsole.")

clearUserWindow

命令格式:
clearUserWindow([name])
这是(现在)等同于 clearWindow()

clearWindow

命令格式:
clearWindow([windowName])
清除标签、迷你控制台或用户窗口的名称作为参数(删除其中的所有文本)。如果不给予它命名,它将清除主窗口。

closestColor

命令格式:
closestColor(colorOrR[,G,B])
返回color_table中与cecho和相关函数中提供的颜色最接近的颜色。
参数:
colorOrR: 来自decho或hecho的颜色的字符串表示(IE“#ff0077”或“255,0,128“)、颜色值表(IE {255,0,18})或RGB的红色分量(当后面跟着两个可选参数时)
例子:

local colorName = closestColor(255, 0, 0) -- "ansi_light_red"
local colorName = closestColor({127, 255, 127}) -- "ansi_120"
local colorName = closestColor("<127, 127, 127>") -- "ansi_008"
local colorName = closestColor("#a020e6") -- "purple"
local colorName = closestColor("blue") -- "blue" (you wouldn't necessarily do this on purpose, but during automated color conversions this might occur)

copy

命令格式:
copy([windowName])
将当前选择复制到lua虚拟剪贴板。这个函数在富文本上操作,即。e.所选文本包括其所有格式代码,如颜色、字体等。直到它被另一个复制操作覆盖。

copy2decho

命令格式:
copy2decho([window], [stringToCopy], [instanceToCopy])
从窗口的当前行复制一个字符串,包括decho格式的颜色信息。

copy2html

命令格式:
copy2html([window], [stringToCopy], [instanceToCopy])
从窗口的当前行复制一个字符串,包括html格式的颜色信息,用于回显到标签。

createBuffer

命令格式:
createBuffer(name)
为格式化文本创建一个命名缓冲区,非常类似于迷你控制台,但缓冲区不打算显示在屏幕上-使用它来格式化文本或存储格式化文本。

createCommandLine

命令格式:
createCommandLine([name of userwindow], name, x, y, width, height)
在Mudlet的主窗口中创建一个新的命令行。如果只需要miniConsole/UserWindow中的命令行, 您可以使用 appendCmdLine()/ getCmdLine() 函数和其他命令行函数来定制输入。
注意:setCmdLineAction允许您将操作附加到命令行输入中。

createConsole

命令格式:
createConsole([name of userwindow], consoleName, fontSize, charsPerLine, numberOfLines, Xpos, Ypos)
制作一个新的迷你窗口,它可以根据“W”字符的宽度和字体中任何字符应该使用的极端顶部和底部位置来调整大小。背景为黑色,文本为白色。
部分参数: charsPerLine: 字宽。作为整数传递。 numberOfLines: 行数, 作为整数传递。

createGauge

命令格式:
createGauge([name of userwindow], name, width, height, Xpos, Ypos, gaugeText, r, g, b, orientation)
createGauge([name of userwindow], name, width, height, Xpos, Ypos, gaugeText, colorName, orientation)
创建可用于表示完成的量规。例如,您可以将其用作您的健康条或xpbar。
部分参数: orientation: 仪表的方向。可以是水平的(从左到右填充)、垂直的(从下到上填充)、愚蠢的(从右到左填充)或batty的(从上到下填充)。

createGauge("healthBar", 300, 20, 30, 300, nil, 0, 255, 0)
createGauge("healthBar", 300, 20, 30, 300, nil, "green")


-- If you wish to have some text on your label, you'll change the nil part and make it look like this:
createGauge("healthBar", 300, 20, 30, 300, "Now with some text", 0, 255, 0)
-- or
createGauge("healthBar", 300, 20, 30, 300, "Now with some text", "green")

createLabel

命令格式:
createLabel([name of userwindow], name, Xpos, Ypos, width, height, fillBackground, [enableClickthrough])

创建一个高度可操作的覆盖层,可以使用一些css和html代码进行文本格式化。标签是可点击的,因此可以用作按钮。标签意味着小的可变或提示显示、消息、图像等。您不应该将它们用于更大的文本显示或将快速和高容量更新的东西,因为它们比迷你控制台窗口慢得多。
部分参数: fillBackground:是否显示背景。以整数(1或0)或布尔值(true,false)传递。1或true将显示背景色,0或false不显示。
enableClickthrough:是否启用此标签的点击。以整数(1或0)或布尔值(true,false)传递。1或true将启用点击通过,0或false将不启用。可选,如果未提供,则默认为未启用单击通过。

createLabel("a very basic label",300,400,100,200,1)

-- this example creates a transparent overlay message box to show a big warning message "You are under attack!" in the middle
-- of the screen. Because the background color has a transparency level of 150 (0-255, with 0 being completely transparent
-- and 255 opaque) the background text can still be read through.
local width, height = getMainWindowSize()
createLabel("messageBox",(width/2)-300,(height/2)-100,250,150,1)
resizeWindow("messageBox",500,70)
moveWindow("messageBox", (width/2)-300,(height/2)-100 )
setBackgroundColor("messageBox", 255, 204, 0, 200)
echo("messageBox", [[<p style="font-size:35px"><b><center><font color="red">You are under attack!</font></center></b></p>]])

-- you can also make it react to clicks!
mynamespace = {
  messageBoxClicked = function()
    echo("hey you've clicked the box!\n")
  end
}

setLabelClickCallback("messageBox", "mynamespace.messageBoxClicked")

createMiniConsole

命令格式:
createMiniConsole([name of userwindow], name, x, y, width, height)
在Mudlet的主窗口中打开一个迷你窗口。这是理想的快速彩色文本显示,对于需要更多文本的一切,如状态屏幕,聊天窗口等。与标签不同,标签中不能有透明度。

createScrollBox

命令格式:
createScrollBox([name of parent window], name, x, y, width, height)
创建能够保存其他图形元素的图形元素,例如标签、小窗口、命令行等的滚动条。如果内容大小超过显示范围,滚动条出现并允许滚动。

creplace

命令格式:
creplace([window, ]text)
用带颜色标记的字符串替换游戏的输出行。

creplaceLine

命令格式:
creplaceLine ([window], text)
用带颜色标记的字符串替换游戏的输出行。

decho

命令格式:
decho ([name of console,] text)
回显文本
注意事项: Mudlet 4.10+中提供的可选背景透明参数(BA)

decho2ansi

命令格式:
ansiFormattedString = decho2ansi(text)
将decho格式的文本转换为ansi格式的文本。由dfeedTriggers使用,但如果您出于任何其他原因需要ansi格式的文本,则很有用。

命令格式:
dechoLink([windowName], text, command, hint, true)
在当前选定行的末尾将一段文本作为可单击的链接回显-类似于 decho() 此版本允许您在链接文本中使用颜色。

dechoPopup

命令格式:
dechoPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
创建文本,该文本具有可左键单击的链接,以及在当前行末尾的右键单击菜单以查看更多选项,如 decho()添加的文本在被左键单击时将执行列表中的第一个命令。右键单击后,它将显示一个包含所有可能命令的菜单。菜单将填充提示,每行一个提示。

命令格式:
dinsertLink([windowName], text, command, hint, true)
在当前光标位置的末尾将文本作为可单击链接回显-类似于 dinsertText() 此版本允许您在链接文本中使用颜色。

dinsertPopup

命令格式:
dinsertPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
创建文本,该文本具有可左键单击的链接,以及在当前光标位置末尾的右键单击菜单以查看更多选项,如 dinsertText() 添加的文本在被左键单击时将执行列表中的第一个命令。右键单击后,它将显示一个包含所有可能命令的菜单。菜单将填充提示,每行一个提示。

deleteLabel

命令格式:
deleteLabel(labelName)
从屏幕上删除和移除标签。请注意,如果您想再次显示标签,那么隐藏/显示它会更有效。

deleteLine

命令格式:
deleteLine([windowName])
删除用户光标下的当前行。这是一个高速堵塞工具,非常擅长这项任务,但仅用于在输出中完全省略一行时。如果你echo()到该行,它将不会显示,并且用deleteLine()删除的行也不会再呈现。这是纯粹的视觉-触发器仍将按预期在线路上触发。

deselect

命令格式:
deselect([window name])
这用于清除当前选择(不再选择任何内容)。应在更改文本格式后使用,以防止稍后再次使用另一个格式调用意外更改文本。

disableHorizontalScrollBar

命令格式:
disableHorizontalScrollBar([windowName])
禁用miniConsole/用户窗口的水平滚动条

disableScrollBar

命令格式:
disableScrollBar([windowName])
禁用滚动条

dreplace

命令格式:
dreplace([window, ]text)
用带颜色标记的字符串替换游戏的输出行。

dreplaceLine

命令格式:
dreplaceLine ([window, ]text)
用带颜色标记的字符串替换游戏的输出行。

命令格式:
echoLink([windowName], text, command, hint, [useCurrentFormatElseDefault])
在当前选定行的末尾将一段文本作为可单击的链接回显-类似于 echo().

echoLink

命令格式:
echoLink([windowName], text, command, hint, [useCurrentFormatElseDefault])
在当前选定行的末尾将一段文本作为可单击的链接回显-类似于 echo().
注意:提示可以包含与可以用于“标签”的相同类型的“富文本”-并且如果命令被设置为空字符串“”,则这可以是当鼠标悬停在文本上但如果它被点击时没有运行命令时显示文本的额外信息的手段,例如:显示花式视觉链接示例的屏幕截图

echoUserWindow

命令格式:
echoUserWindow(windowName, text)
此功能将文本打印到迷你控制台窗口、坞站窗口和标签。但它已经过时了, 用echo()代替.

echoPopup

命令格式:
echoPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
创建文本,该文本具有可左键单击的链接,以及在当前行末尾的右键单击菜单以查看更多选项,如echo。添加的文本在被左键单击时将执行列表中的第一个命令。右键单击后,它将显示一个包含所有可能命令的菜单。菜单将填充提示,每行一个提示。

enableClickthrough

命令格式:
enableClickthrough(label)
使标签对点击“不可见”–这样如果你有另一个标签在下面,它将被点击而不是上面的这个标签。这会影响单击、双击、右键单击以及onEnter/onLeave事件。

enableHorizontalScrollBar

命令格式:
enableHorizontalScrollBar([windowName])
为miniConsole/用户窗口或者主窗口启用水平滚动条

enableScrollBar

命令格式:
enableScrollBar([windowName])
启用miniConsole/用户窗口的滚动条

fg

命令格式:
fg([window], colorName)
如果在选定内容上使用,则将前景色设置为 colorName

--This would change the color of the text on the current line to green
selectCurrentLine()
fg("green")
resetFormat()

--This will echo red, green, blue in their respective colors
fg("red")
echo("red ")
fg("green")
echo("green ")
fg("blue")
echo("blue ")
resetFormat()

-- example of working on a miniconsole
fg("my console", "red")
echo("my console", "red text")

getAvailableFonts

命令格式:
getAvailableFonts()
这将返回一个可用字体的“font - true”键值列表,您可以使用它来验证Mudlet是否可以访问给定字体。
要在包中安装新字体,请在zip/mpackage中包含字体文件,它将自动为您安装。

-- check if Ubuntu Mono is a font we can use
if getAvailableFonts()["Ubuntu Mono"] then
  -- make the miniconsole use the font at size 16
  setFont("my miniconsole", "Ubuntu Mono")
  setFontSize("my miniconsole", 16)
end

getBackgroundColor

命令格式:
getBackgroundColor([windowName])
获取给定标签、miniconsole或userwindow的背景。
返回4个值-红色,绿色,蓝色,透明度。返回的颜色从0到255(0表示黑色),透明度从0到255(0表示完全透明)。

local r, g, b, a = getBackgroundColor()
local rW, gW, bW, aW = getBackgroundColor("myWindow")

getBgColor

命令格式:
getBgColor(windowName)
此函数返回迷你控制台(窗口)windowName上当前选择内容的第一个字符的背景色的rgb值。如果省略windowName,Mudlet将使用主屏幕。

local r,g,b;
selectString("troll",1)
r,g,b = getBgColor()
if r == 255 and g == 0 and b == 0 then
    echo("HELP! troll is highlighted in red letters, the monster is aggressive!\n");
end

getBorderBottom

命令格式:
getBorderBottom()
返回主窗口底部边框的大小(以像素为单位)。

getBorderRight

命令格式:
getBorderRight()
返回主窗口右边框的大小(以像素为单位)。

getBorderSizes

命令格式:
getBorderSizes()
返回一个命名的表,其中包含主窗口所有边框的大小(以像素为单位)。

getBorderTop

命令格式:
getBorderTop()
返回主窗口上边框的大小(以像素为单位)。

getClipboardText

命令格式:
getClipboardText()
返回剪贴板中当前存在的任何文本。

getColorWildcard

命令格式:
getColorWildcard(ansi color number)
此函数给定ANSI颜色编号将返回当前行中与它匹配的所有字符串。
例子:

-- we can run this script on a line that has the players name coloured differently to easily capture it from
-- anywhere on the line
local match = getColorWildcard(14) -- this will be a table of every match

if match then -- if there's a table, then we try and print it on the screen!
  echo("\nFound "..table.concat(match, ", ").."!") -- this will combine all captured strings and separate them with a comma so it's easy to read.
else -- if there isn't something in match, then we haven't found anything to print on the screen!
  echo("\nDidn't find anyone.") 
end

getColumnCount

命令格式:
getColumnCount([windowName])
获取给定窗口可以在单行上显示的最大列数(字符数),同时考虑窗口宽度、字体大小、间距等因素

getColumnNumber

命令格式:
getColumnNumber([windowName])
获取当前用户游标的绝对列号。

getColumnNumber

命令格式:
getColumnNumber([windowName])
获取当前用户游标的绝对列号。
例子:

HelloWorld = Geyser.MiniConsole:new({
  name="HelloWorld",
  x="70%", y="50%",
  width="30%", height="50%",
})

HelloWorld:echo("hello!\n")
HelloWorld:echo("hello!\n")
HelloWorld:echo("hello!\n")

moveCursor("HelloWorld", 3, getLastLineNumber("HelloWorld"))
-- should say 3, because we moved the cursor in the HellWorld window to the 3rd position in the line
print("getColumnNumber: "..tostring(getColumnNumber("HelloWorld")))

moveCursor("HelloWorld", 1, getLastLineNumber("HelloWorld"))
-- should say 3, because we moved the cursor in the HellWorld window to the 1st position in the line
print("getColumnNumber: "..tostring(getColumnNumber("HelloWorld")))

getCurrentLine

命令格式:
getCurrentLine([windowName])
返回缓冲区中用户光标下当前行的内容。在此行上运行任何触发器之前。当触发器更改缓冲区的内容时,变量行将不会被调整,因此保存一个过时的字符串。line = getCurrentLine() 将更新行为当前缓冲区的真实的内容。如果要在当前行被某些触发器更改后复制它,这一点非常重要。 selectString( line,1 )将返回false并且不会选择任何内容,因为行不再等于 getCurrentLine(). 因此,会认为, selectString( getCurrentLine(), 1 ) 才是你需要的

getFgColor

命令格式:
getFgColor(windowName)
此函数返回迷你控制台(窗口)windowName上当前选定内容的第一个字符的颜色的rgb值。如果省略windowName,Mudlet将使用主屏幕。
例子:

selectString("troll",1)
local r,g,b = getFgColor()
if r == 255 and g == 0 and b == 0 then
  echo("HELP! troll is written in red letters, the monster is aggressive!\n")
end

getFont

命令格式:
getFont(windowName)
获取给定窗口或控制台名称的当前字体。可用于获取主控制台、可停靠用户窗口和迷你窗口的字体。

getFontSize

命令格式:
getFontSize(windowName)
获取给定窗口或控制台名称的当前字体大小。可用于获取主控制台以及可停靠用户窗口的字体大小。

getHTMLformat

命令格式:
spanTag = getHTMLformat(formatTable)
以与 getTextFormat() 并返回一个span标记,该标记将按照表中所描述的那样格式化它之后的文本。
例子:

-- Returns a span tag for bold, red text on a green background
local span = getHTMLformat({
  foreground = { 255, 0, 0 },
  background = "#00FF00",
  bold = true
})

-- span will be '<span style="color: rgb(255, 0, 0);background-color: #00FF00; font-weight: bold; font-style: normal; text-decoration: none;">'

getImageSize

命令格式:
getImageSize(imageLocation)
返回给定图像的宽度和高度。如果图像无法找到、加载或不是有效的图像文件- nil+错误信息将被返回。
例子:

local path = getMudletHomeDir().."/my-image.png"

cecho("Showing dimensions of the picture in: "..path.."\n")

local width, height = getImageSize(path)

if not width then
  -- in case of an problem, we don't get a height back - but the error message
  cecho("error: "..height.."\n")
else
  cecho(string.format("They are: %sx%s", width, height))
end

getLabelFormat

命令格式:
formatTable = getLabelFormat(labelName)
返回一个格式表,类似于getTextFormat返回的格式表,它适用于getHTMLformat,它将格式化文本的方式与简单地对标签执行回显一样
例子:

-- creates a test label, sets a stylesheet, and then returns the default format table for that label.
createLabel("testLabel", 10, 10, 300, 200, 1)
setLabelStyleSheet([[
  color: rgb(0,0,180);
  border-width: 1px;
  border-style: solid;
  border-color: gold;
  border-radius: 10px;
  font-size: 12.0pt;
  background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #98f041, stop: 0.1 #8cf029, stop: 0.49 #66cc00, stop: 0.5 #52a300, stop: 1 #66cc00);
]])
local fmt = getLabelFormat("testLabel"))

--[[
{
  background = "rgba(0, 0, 0, 0)", -- this is transparent
  bold = false,
  foreground = "rgb(0,0,180)",
  italic = false,
  overline = false,
  reverse = false,
  strikeout = false,
  underline = false
}
--]]

getLabelSizeHint

命令格式:
width, height = getLabelSizeHint(labelName)
以宽度和高度形式返回建议的labelsize

getLabelSizeHint

命令格式:
width, height = getLabelSizeHint(labelName)
以宽度和高度形式返回建议的labelsize

-- text resizing example
-- create the label
createLabel("textLabel",400,400,300,300,1)
-- put some text on it
echo("textLabel", "This is my Test.\nAnother Test")
-- resizes the label to fit the text
resizeWindow("textLabel", getLabelSizeHint("textLabel"))

-- image resizing example
-- create the label
createLabel("imageLabel",400,400,300,300,1)
-- put some image on it
setBackgroundImage("imageLabel", getMudletHomeDir.."/myLabelImage.png")
-- resizes the label to fit the image
resizeWindow("imageLabel", getLabelSizeHint("imageLabel"))

getLabelStyleSheet

命令格式:
getLabelStyleSheet(labelName)
返回在给定标签上设置的样式表,该样式表用于自定义标签的外观。

getLastLineNumber

命令格式:
getLastLineNumber(windowName)
返回主窗口或miniconsole中的最新行号。

getLineCount

命令格式:
getLineCount(windowName)
获取当前控制台缓冲区中的绝对行数

getLines

命令格式:
getLines([windowName,] from_line_number, to_line_number)
使用绝对行号返回屏幕文本缓冲区内容的一部分。返回一个Lua表
例子:

-- retrieve & echo the last line:
echo(getLines(getLineNumber()-1, getLineNumber())[1])

-- find out which server and port you are connected to (as per Mudlet settings dialog):
local t = getLines(0, getLineNumber())

local server, port

for i = 1, #t do
  local s, p = t[i]:match("looking up the IP address of server:(.-):(%d+)")
  if s then server, port = s, p break end
end

display(server)
display(port)

getLineNumber

命令格式:
getLineNumber([windowName])
返回当前用户光标的绝对行号(y位置)。默认情况下,光标位于触发器正在处理的当前行上-您可以使用它四处移动 moveCursor()和 moveCursorEnd() getLines()与一起使用时,此函数可以派上用场

-- use getLines() in conjuction with getLineNumber() to check if the previous line has a certain word
if getLines(getLineNumber()-1, getLineNumber())[1]:find("attacks") then echo("previous line had the word 'attacks' in it!\n") end

-- check how many lines you've got in your miniconsole after echoing some text.
-- Note the use of moveCursorEnd() to update getLineNumber()'s output
HelloWorld = Geyser.MiniConsole:new({
  name="HelloWorld",
  x="70%", y="50%",
  width="30%", height="50%",
})

print(getLineNumber("HelloWorld"))

HelloWorld:echo("hello!\n")
HelloWorld:echo("hello!\n")
HelloWorld:echo("hello!\n")

-- update the cursors position, as it seems to be necessary to do
moveCursorEnd("HelloWorld")
print(getLineNumber("HelloWorld"))

getMainConsoleWidth

命令格式:
getMainConsoleWidth()
返回单个数字;主控制台(游戏输出)的宽度,以像素为单位。这也说明了已设置的任何边界。

getMouseEvents

命令格式:
getMouseEvents()
返回已注册鼠标事件的表,包括它们可能具有的任何附加参数。

getMousePosition

命令格式:
getMousePosition()
返回鼠标相对于Mudlet窗口本身的位置坐标。

getMousePosition

命令格式:
getMousePosition()
返回鼠标相对于Mudlet窗口本身的位置坐标。
例子:

local x, y = getMousePosition()
createLabel("clickGeneratedLabel", x, y, 100, 100, 1)
-- if the label already exists, just move it
moveWindow("clickGeneratedLabel", x, y)
-- and make it easier to notice
setBackgroundColor("clickGeneratedLabel", 255, 204, 0, 200)

getProfileTabNumber

命令格式:
getProfileTabNumber()
返回您所在的当前标签号。如果你只加载了一个配置文件,它总是返回1 -否则它将是当前打开的第n个选项卡。

getMainWindowSize

命令格式:
getMainWindowSize()
返回两个数字,宽度和高度(以像素为单位)。这对于计算窗口尺寸和自定义GUI工具包项(如标签、按钮、迷你控制台等)的位置非常有用。

getRowCount

命令格式:
getRowCount([windowName])
获取给定窗口一次可以显示的最大行数,同时考虑窗口高度、字体类型、间距等因素。

getScroll

命令格式:
getScroll([windowName])
返回窗口当前滚动到的行。

-- button to jump to next instance of "Timbo"
local current = getScroll()
local data = getLines(current, getLineCount())
for count, line in ipairs(data) do
  local match = string.findPattern(line, "Timbo")
  if match then
    scrollTo(current + count)
    break
  end
end

getSelection

命令格式:
getSelection([windowName])
还将选择的起始偏移量和长度作为第二个和第三个值返回。

getTextFormat

命令格式:
getTextFormat([windowName])
获取当前选定文本的当前文本格式。可与其他控制台窗口一起使用。返回的值位于包含文本属性名称及其值的表中。给出的值将是布尔值:粗体、斜体、下划线、上划线、删除线和反转-后面是前景和背景色的颜色三元组表。
例子:

-- A suitable test for getTextFormat()
-- (copy it into an alias or a script)

clearWindow()

echo("\n")

local SGR = string.char(27)..'['
feedTriggers("Format attributes: '"..SGR.."1mBold"..SGR.."0m' '"..SGR.."3mItalic"..SGR.."0m' '"..SGR.."4mUnderline"..SGR.."0m' '"..SGR.."5mBlink"..SGR.."0m' '"..SGR.."6mF.Blink"..SGR.."0m' '"..SGR.."7mReverse"..SGR.."0m' '"..SGR.."9mStruckout"..SGR.."0m' '"..SGR.."53mOverline"..SGR.."0m'.\n")

moveCursor(1,1)
selectSection(1,1)

local results = getTextFormat()
echo("For first character in test line:\nBold detected: " .. tostring(results["bold"]))
echo("\nItalic detected: " .. tostring(results["italic"]))
echo("\nUnderline detected: " .. tostring(results["underline"]))
echo("\nReverse detected: " .. tostring(results["reverse"]))
echo("\nStrikeout detected: " .. tostring(results["strikeout"]))
echo("\nOverline detected: " .. tostring(results["overline"]))
echo("\nForeground color: (" .. results["foreground"][1] .. ", " .. results["foreground"][2] .. ", " .. results["foreground"][3] .. ")")
echo("\nBackground color: (" .. results["background"][1] .. ", " .. results["background"][2] .. ", " .. results["background"][3] .. ")")

selectSection(21,1)
echo("\n\nFor individual parts of test text:")
echo("\nBold detected (character 21): " .. tostring(results["bold"]))

selectSection(28,1)
echo("\nItalic detected (character 28): " .. tostring(results["italic"]))

selectSection(37,1)
echo("\nUnderline detected (character 37): " .. tostring(results["underline"]))

selectSection(67,1)
echo("\nReverse detected (character 67): " .. tostring(results["reverse"]))

selectSection(77,1)
echo("\nStrikeout detected (character 77): " .. tostring(results["strikeout"]))

selectSection(89,1)
echo("\nOverline detected (character 89): " .. tostring(results["overline"]))
echo("\n")

getUserWindowSize

命令格式:
getUserWindowSize(windowName)
返回两个数字,宽度和高度(以像素为单位)。这对于计算给定的用户窗口尺寸和自定义GUI工具包项目(如标签、按钮、迷你控制台等)的放置非常有用。

getWindowWrap

命令格式:
getWindowWrap(windowName)
在行中的哪个位置开始换行。

handleWindowResizeEvent

命令格式:
handleWindowResizeEvent()
此函数已弃用,不应使用;此处仅记录用于历史参考-使用 sysWindowResizeEvent 事件代替

hasFocus

命令格式:
hasFocus()
返回true false 这取决于Mudlet的主窗口当前是否处于焦点中(即,用户没有聚焦在另一个窗口上,如浏览器)。如果加载了多个配置文件,这也可以用于检查给定配置文件是否处于焦点中。

hecho

命令格式:
hecho([windowName], text)
以十六进制格式使用颜色标记轻松格式化的文本回显。也可以使用斜体、粗体、删除线和下划线标记。

hecho2ansi

命令格式:
ansiFormattedString = hecho2ansi(text)
将hecho格式的文本转换为ansi格式的文本。由hfeedTriggers使用,但如果您出于任何其他原因需要ansi格式的文本,则很有用。

feedTriggers(hecho2ansi("\n#800000This is red.#r #iitalic#/i, #bbold#/b, #sstrikethrough#/s, #uunderline#/u\n"))

命令格式:
hechoLink([windowName], text, command, hint, true)
在当前选定行的末尾将一段文本作为可单击的链接回显-类似于 hecho() 此版本允许您在链接文本中使用颜色。

hechoPopup

命令格式:
hechoPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
创建文本,该文本具有可左键单击的链接,以及在当前行末尾的右键单击菜单以查看更多选项,如 hecho() 添加的文本在被左键单击时将执行列表中的第一个命令。右键单击后,它将显示一个包含所有可能命令的菜单。菜单将填充提示,每行一个提示。

hideGauge

命令格式:
hideGauge(gaugeName)
隐藏给定的仪表。

命令格式:
hinsertLink([windowName], text, command, hint, true)
在当前光标位置的末尾将文本作为可单击链接回显-类似于 hinsertText()此版本允许您在链接文本中使用颜色。

hinsertPopup

命令格式:
hinsertPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
创建文本,该文本具有可左键单击的链接,以及在当前光标位置末尾的右键单击菜单以查看更多选项,如 hinsertText().添加的文本在被左键单击时将执行列表中的第一个命令。右键单击后,它将显示一个包含所有可能命令的菜单。菜单将填充提示,每行一个提示。

hreplaceLine

命令格式:
hreplaceLine ([window], text)
用带颜色标记的字符串替换游戏的输出行。

hreplace

命令格式:
hreplace([window, ]text)
用带颜色标记的字符串替换游戏的输出行。

hideToolBar

命令格式:
hideToolBar (name)
隐藏具有给定名称的工具栏并使其消失。如果隐藏工具栏区域(顶部、左侧、右侧)的所有工具栏,则整个工具栏区域将自动消失。

hideWindow

命令格式:
hideWindow(name)
指定要隐藏的标签或控制台。

命令格式:
insertLink([windowName], text, command, hint, [useCurrentLinkFormat])
在当前光标位置插入一段文本作为可单击链接-类似于 insertText()

insertPopup

命令格式:
insertPopup([windowName,] text, {commands}, {hints}[, useCurrentLinkFormat])
创建具有可左击链接的文本,以及在光标位置精确位置的右键菜单,类似于 insertText().插入的文本在被左键单击时将执行列表中的第一个命令。右键单击后,它将显示一个包含所有可能命令的菜单。菜单将填充提示,每行一个提示。

insertText

命令格式:
insertText([windowName], text)
insertHTML()
在窗口中的光标位置插入文本-不像 echo()它将文本插入缓冲区中最后一行(通常是由触发器处理的行)的末尾。您可以使用 moveCursor()将光标移动到第一个位置

ioprint

命令格式:
ioprint(text, some more text, …)
将文本打印到标准输出。只有当您在Windows上从cmd.exe启动Mudlet, 从终端在Mac上,或从Linux操作系统上的终端(启动终端程序,键入 mudlet 然后按回车键)。
这个函数对于解决由于脚本导致的Mudlet潜在的崩溃问题非常有用–因为当Mudlet崩溃时,您仍然会看到它打印的任何内容。

isAnsiBgColor

命令格式:
isAnsiBgColor(bgColorCode)
此函数测试的第一个字符是否 当前选择在主控制台中的背景颜色由bgColorCode指定。
要测试的颜色代码,可能的代码包括:

0 = default text color
1 = light black
2 = dark black
3 = light red
4 = dark red
5 = light green
6 = dark green
7 = light yellow
8 = dark yellow
9 = light blue
10 = dark blue
11 = light magenta
12 = dark magenta
13 = light cyan
14 = dark cyan
15 = light white
16 = dark white

isAnsiFgColor

命令格式:
isAnsiFgColor(fgColorCode)
此函数测试的第一个字符是否当前选择主控制台中的前景色由fgColorCode指定。

loadWindowLayout

命令格式:
loadWindowLayout()
将用户窗口的布局重置为上次保存的状态。

lowerWindow

命令格式:
lowerWindow(labelName)
将引用的标签/控制台移动到所有其他标签/控制台下方。有关相反的效果,请参见: raiseWindow()

moveCursor

命令格式:
moveCursor([windowName], x, y)
将窗口windowName或主窗口的用户光标移动到绝对点(x,y)。如果这样的移动是不可能的,则该函数返回false。坐标不存在。要确定正确的坐标 触发器引擎将始终在脚本运行之前将用户光标放在当前行的开头。如果省略windowName参数,则将使用主屏幕。

moveCursorDown

命令格式:
moveCursorDown([windowName,] [lines,] [keepHorizontal])
将给定窗口中的光标向下移动指定行数。

moveCursorUp

命令格式:
moveCursorUp([windowName,] [lines,] [keepHorizontal])
将给定窗口中的光标向上移动指定行数。

moveCursorEnd

命令格式:
moveCursorEnd([windowName])
将光标移动到缓冲区的末尾。“main”是主窗口的名称,否则使用用户窗口的名称。

moveGauge

命令格式:
moveGauge(gaugeName, newX, newY)
将使用createGauge创建的仪表移动到新的x,y坐标。请记住,坐标是相对于输出窗口左上角的。

moveWindow

命令格式:
moveWindow(name, x, y)
此函数将窗口名称移动到给定的x/y坐标。主屏幕无法移动。相反,你必须设置适当的边框值→首选项来移动主屏幕,例如.为聊天或信息迷你控制台或其他GUI元素腾出空间。将来moveWindow()将自动设置边界值,如果省略name参数。

openUserWindow

命令格式:
openUserWindow(windowName, [restoreLayout], [autoDock], [dockingArea])
打开用户可停靠的控制台窗口以供用户输出,例如统计、聊天等。如果已经存在这样的名称的窗口,则不会发生任何事情。您可以移动这些窗口(甚至可以移动到具有多屏幕显示器的系统上的不同屏幕),将它们停靠在主应用程序窗口的四个侧面中的任何一个,将它们设置为笔记本选项卡或浮动它们。

paste

命令格式:
paste(windowName)
粘贴以前复制的文本,包括所有格式代码,如颜色,字体等。在当前用户光标位置。的 copy() 和 paste() 函数可用于将格式化文本从主窗口复制到用户窗口而不丢失颜色E。G.用于聊天窗口、地图窗口等。

pauseMovie

命令格式:
pauseMovie(label name)
暂停标签上的gif动画

prefix

命令格式:
prefix(text, [writingFunction], [foregroundColor], [backgroundColor], [windowName])
在触发器中使用时,在当前行开头添加文本前缀。

print

命令格式:
print(text, some more text, …)
将文本打印到主窗口。

raiseWindow

命令格式:
raiseWindow(labelName)
将引用的标签/控制台提升到所有标签/控制台之上。有关相反的效果,请参见: lowerWindow()

removeCommandLineMenuEvent

命令格式:
removeCommandLineMenuEvent([window,] label)
删除现有命令行菜单事件。

removeMouseEvent

命令格式:
removeMouseEvent(uniqueName)
删除现有鼠标事件。

replace

命令格式:
replace([windowName], with, [keepcolor])
用新文本替换当前选定的文本。要选择文本,请使用 selectString() selectSection() 或类似的功能。
注意事项: 当在触发器上下文之外使用时(例如,在计时器中而不是触发器中),replace()不会触发屏幕刷新。相反,请像insertText()那样使用replace(“”)和insertText(“new text”)。

replaceAll

命令格式:
replaceAll(what, with, [keepcolor])
(当前行? )替换所有出现的 what 用 with

replaceLine

命令格式:
replaceLine ([window], text)
将游戏中的输出行替换为您自己的文本。

replaceWildcard

命令格式:
replaceWildcard(which, replacement, [keepcolor])
用给定的文本替换给定的通配符(作为数字)。相当于做:selectString, replace

resetCmdLineAction

命令格式:
resetCmdLineAction(commandLineName)
重置命令行上的操作,使其行为与主命令行类似。

resetBackgroundImage

命令格式:
resetBackgroundImage([windowName])
重置控制台背景图像

resetFormat

命令格式:
resetFormat([windowName])
重置颜色/粗体/斜体格式。在调整格式时始终使用此函数,因此确保您设置的内容不会影响到其他触发器/别名上。

resetLabelCursor

命令格式:
resetLabelCursor(labelName)
将鼠标光标重置为默认光标。

resetLabelToolTip

命令格式:
resetLabelToolTip(labelName)
重置给定标签上的工具提示。

resetMapWindowTitle

命令格式:
resetMapWindowTitle()
将弹出的地图窗口的标题重置为默认值。

resetUserWindowTitle

命令格式:
resetUserWindowTitle(windowName)
重置UserWindow windowName的标题

resizeWindow

命令格式:
resizeWindow(windowName, width, height)
调整迷你控制台、标签或浮动用户窗口的大小。

saveWindowLayout

命令格式:
saveWindowLayout()
保存用户窗口的布局,可以稍后再次加载它们。

scaleMovie

命令格式:
scaleMovie(label name, [autoscale])
调整gif的大小以填充其标签的完整大小

selectCaptureGroup

命令格式:
selectCaptureGroup(groupNumber)
在Perl正则表达式中选择捕获组编号的内容(从matches[]中)。也适用于命名捕获组。它不适用于多匹配。

selectCmdLineText

命令格式:
selectCmdLineText([commandLine])
选择命令行中的文本。你可以指定哪一个,如果你有很多。

-- First, create an extra commandline with the following lua script:
inputContainer = inputContainer or Adjustable.Container:new({
  x = 0, y = "-4c",
  name = "InputContainer", padding = 2,
  width = "100%", height = "4c",
  autoLoad = false
})
extraCmdLine = extraCmdLine or Geyser.CommandLine:new({
  name = "extraCmdLine",
  x = 0, y = 0, width = "100%", height = "100%"
}, inputContainer)
inputContainer:attachToBorder("bottom")

-- Now you can send the following lua code with your main command line.
-- It will give 2 seconds time to click around, unselect its text, etc. before selecting its text for you:
lua tempTimer(2, function() selectCmdLineText() end)

-- This will instead select the text in the command line named extraCmdLine:
lua selectCmdLineText('extraCmdLine')

-- Same as before, but using the Geyser.CommandLine function instead:
lua extraCmdLine:selectText()

selectCurrentLine

命令格式:
selectCurrentLine([windowName])
选择光标所在的当前行的内容。默认情况下,光标位于触发器正在处理的当前行的开始处,但是您可以使用moveCursor()函数移动它。

selectSection

命令格式:
selectSection( [windowName], fromPosition, length )
选择行部分内容

selectString

命令格式:
selectString([windowName], text, number_of_match)
从用户光标当前所在的行中选择一个子字符串-允许您编辑所选文本(应用颜色、使其成为链接、复制到其他窗口或其他东西)。

setAppStyleSheet

命令格式:
setAppStyleSheet(stylesheet [, tag])
为整个Mudlet应用程序和每个打开的配置文件设置样式表。因为它会影响其他可能与你无关的配置文件,所以最好使用 setProfileStyleSheet() 而不是这个功能。
例子:

local background_color = "#26192f"
local border_color = "#b8731b"

setAppStyleSheet([[
  QMainWindow {
     background: ]]..background_color..[[;
  }
  QToolBar {
     background: ]]..background_color..[[;
  }
  QToolButton {
     background: ]]..background_color..[[;
     border-style: solid;
     border-width: 2px;
     border-color: ]]..border_color..[[;
     border-radius: 5px;
     font-family: BigNoodleTitling;
     color: white;
     margin: 2px;
     font-size: 12pt;
  }
  QToolButton:hover { background-color: grey;}
  QToolButton:focus { background-color: grey;}
]])

setBackgroundColor

命令格式:
setBackgroundColor([windowName], r, g, b, [transparency])
设置给定标签、miniconsole或userwindow的背景。颜色从0到255(0表示黑色),透明度从0到255(0表示完全透明)。

setBackgroundImage

命令格式:
setBackgroundImage(labelName, imageLocation)
setBackgroundImage([windowname], imageLocation, [mode])
加载图像文件(png)作为标签或控制台的背景图像。
注意事项: 您也可以通过setLabelStyleSheet()在标签上加载图像。

setBgColor

命令格式:
setBgColor([windowName], r, g, b, [transparency])
设置主窗口中当前文本的背景颜色,除非指定了windowName参数。如果您在此呼叫之前选择了文本,则该选择将被突出显示,否则当前文本背景颜色将被更改。如果设置了前景色或背景色,则在对所有后续打印命令调用resetFormat()之前将一直使用该颜色。

setBold

命令格式:
setBorderBottom(size)
将当前文本字体设置为粗体(true)或非粗体(false)模式。

setBorderBottom

命令格式:
setBold(windowName, boolean)
以像素为单位设置主窗口底部边框的大小。

setBorderColor

命令格式:
setBorderColor(red, green, blue)
设置主窗口边框的颜色,你可以用lua命令或者通过主窗口设置来创建。

setBorderLeft

命令格式:
setBorderLeft(size)
以像素为单位设置主窗口左边框的大小。边框意味着游戏文本不会放在上面,所以这给了你放置图形元素的空间。

setBorderRight

命令格式:
setBorderRight(size)
以像素为单位设置主窗口右边框的大小。边框意味着游戏文本不会放在上面,所以这给了你放置图形元素的空间。

setBorderSizes

命令格式:
setBorderSizes(top, right, bottom, left)
以像素为单位设置主窗口所有边框的大小。边框意味着游戏文本不会放在上面,所以这给了你放置图形元素的空间。

setBorderTop

命令格式:
setBorderTop(size)
以像素为单位设置主窗口上边框的大小。边框意味着游戏文本不会放在上面,所以这给了你放置图形元素的空间。

setFgColor

命令格式:
setFgColor([windowName], red, green, blue)
设置主窗口中的当前文本前景色,除非指定了windowName参数。

setButtonStyleSheet

命令格式:
setButtonStyleSheet(button, markup)
通过特殊的标记语言将Qt样式格式应用于按钮。

setButtonStyleSheet("my test button", [[
  QWidget {
    background-color: #999999;
    border: 3px #777777;
  }
  QWidget:hover {
    background-color: #bbbbbb;
  }
  QWidget:checked {
    background-color: #77bb77;
    border: 3px #559955;
  }
  QWidget:hover:checked {
    background-color: #99dd99;
  } ]])

setClipboardText

命令格式:
setClipboardText(textContent)
将计算机剪贴板的值设置为提供的字符串数据。

setCmdLineAction

命令格式:
setCmdLineAction(commandLineName, luaFunctionName, [any arguments])
指定用户向命令行发送文本时要调用的Lua函数。此函数可以传递任意数量的字符串或整数值作为附加参数。然后在回调中使用这些参数-因此您可以将数据与命令行操作相关联。此外,此函数传递命令行输入文本作为最终参数。
例子:

function sendTextToMiniConsole(miniConsoleName, cmdLineText)
  echo(miniConsoleName, cmdLineText.."\n")
end
setCmdLineAction("myCmdLine", "sendTextToMiniConsole", "myMiniConsole")

setCmdLineStyleSheet

命令格式:
setCmdLineStyleSheet([commandLineName], markup)
通过特殊的标记语言将Qt样式格式应用于命令行。

-- move the main command line over to the right
setCmdLineStyleSheet("main", [[
  QPlainTextEdit {
    padding-left: 100px; /* change 100 to your number */
    background-color: black; /* change it to your background color */
  }
]])

--only change font-size of your main command line
setCmdLineStyleSheet("main", [[
  QPlainTextEdit {
    font-sizeː20pt; 
  }
]])

--change bg/fg color of your miniconsole command line (name of the miniconsole is 'myMiniconsole'
--the command line in the miniconsole has to be enabled
setCmdLineStyleSheet("myMiniConsole", [[
  QPlainTextEdit {
    background: rgb(0,100,0);
    color: rgb(0,200,255);
    font-size: 10pt;
  }
]])

setFont

命令格式:
setFont(name, font)
设置给定窗口或控制台名称的字体。可用于更改主控制台、迷你和用户窗口的字体。

setFontSize

命令格式:
setFontSize(name, size)
设置给定窗口或控制台名称的字体大小。可用于更改主控制台以及可停靠用户窗口的字体大小。

setGauge

命令格式:
setGauge(gaugeName, currentValue, maxValue, gaugeText)
在仪表上设置CSS样式表-一个在前面(根据仪表上的值调整大小的部分),一个在后面。您可以使用 Qt DesignerQt设计器 to create stylesheets. 创建样式表。

setGaugeStyleSheet("hp_bar", [[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #f04141, stop: 0.1 #ef2929, stop: 0.49 #cc0000, stop: 0.5 #a40000, stop: 1 #cc0000);
border-top: 1px black solid;
border-left: 1px black solid;
border-bottom: 1px black solid;
border-radius: 7;
padding: 3px;]],
[[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #bd3333, stop: 0.1 #bd2020, stop: 0.49 #990000, stop: 0.5 #700000, stop: 1 #990000);
border-width: 1px;
border-color: black;
border-style: solid;
border-radius: 7;
padding: 3px;]])

setGaugeStyleSheet

命令格式:
setGaugeStyleSheet(gaugeName, css, cssback, csstext)
如果要根据值更改仪表外观,请使用此功能。典型的用法是在提示符中显示当前的健康状况或任何值,并抛出一些变量而不是数字。

setGaugeText

命令格式:
setGaugeText(gaugename, css, ccstext )
设置插入的gaugename内部使用的文本格式。可使用html标签

setHexBgColor

命令格式:
setHexBgColor([windowName], hexColorString)
设置主窗口中当前文本的背景颜色,除非指定了windowName参数。此函数允许将颜色指定为6个字符的十六进制字符串。

setHexFgColor

命令格式:
setHexFgColor([windowName], hexColorString)
设置主窗口中当前文本的前景颜色,除非指定了windowName参数。此函数允许将颜色指定为6个字符的十六进制字符串。

setItalics

命令格式:
setItalics(windowName, bool)
将当前文本字体设置为斜体/非斜体模式。如果省略windowName参数,将使用主屏幕。

setLabelToolTip

命令格式:
setLabelToolTip(labelName, text, [duration])
在给定标签上设置工具提示。

setLabelClickCallback

命令格式:
setLabelClickCallback(labelName, luaFunctionName, [any arguments])
指定用户单击标签/图像时要调用的Lua函数。此函数可以传递任意数量的字符串或整数值作为附加参数。然后在回调中使用这些参数-因此您可以将数据与标签/按钮相关联。此外,此函数传递事件表作为最终参数。此表包含有关单击的鼠标按钮、当时按下的其他按钮以及鼠标光标的本地(相对于标签)和全局(相对于Mudlet窗口)位置的信息。调用luaFunctionName中指定的函数

定义了以下鼠标按钮字符串:

“LeftButton” “RightButton” “MidButton”
“BackButton” “ForwardButton” “TaskButton”
“ExtraButton4” “ExtraButton5” “ExtraButton6”
“ExtraButton7” “ExtraButton8” “ExtraButton9”
“ExtraButton10” “ExtraButton11” “ExtraButton12”
“ExtraButton13” “ExtraButton14” “ExtraButton15”
“ExtraButton16” “ExtraButton17” “ExtraButton18”
“ExtraButton19” “ExtraButton20” “ExtraButton21”
“ExtraButton22” “ExtraButton23” “ExtraButton24”

例子:

createLabel("testLabel", 50, 50, 100, 100, 0)

function onClickGoNorth(event)
  if event.button == "LeftButton" then
    send("walk north")
  elseif event.button == "RightButton" then
    send("swim north")
  elseif event.button == "MidButton" then
    send("gallop north")
  end
end

setLabelClickCallback("testLabel", "onClickGoNorth")

-- you can also use them within tables:
mynamespace =
  {
    onClickGoNorth =
      function()
        echo("the north button was clicked!")
      end,
  }
setLabelClickCallback("testLabel", "mynamespace.onClickGoNorth")

-- or by passing the function directly:
setLabelClickCallback("testLabel", onClickGoNorth)

setLabelDoubleClickCallback

命令格式:
setLabelDoubleClickCallback(labelName, luaFunctionName, [any arguments])
指定用户双击标签/图像时要调用的Lua函数。此函数可以传递任意数量的字符串或整数值作为附加参数。然后在回调中使用这些参数-因此您可以将数据与标签/按钮相关联。此外,此函数传递事件表作为最终参数,如 setLabelClickCallback()函数

setLabelMoveCallback

命令格式:
setLabelMoveCallback(labelName, luaFunctionName, [any arguments])
指定当鼠标在指定标签/控制台内移动时调用的Lua函数。此函数可以传递任意数量的字符串或整数值作为附加参数。然后在回调中使用这些参数-因此您可以将数据与标签/按钮相关联。此外,此函数传递事件表作为最终参数,如 setLabelClickCallback()函数

setLabelOnEnter

命令格式:
setLabelOnEnter(labelName, luaFunctionName, [any arguments])
指定鼠标进入标签边框时要调用的Lua函数。此函数可以传递任意数量的字符串或整数值作为附加参数。然后在回调中使用这些参数-因此您可以将数据与标签/按钮相关联。此外,此函数传递事件表作为最终参数,类似于 setLabelClickCallback()函数, 但信息略有不同。

setLabelOnLeave

命令格式:
setLabelOnLeave(labelName, luaFunctionName, [any arguments])
指定鼠标离开标签边框时要调用的Lua函数。此函数可以传递任意数量的字符串或整数值作为附加参数。然后在回调中使用这些参数-因此您可以将数据与标签/按钮相关联。

setLabelReleaseCallback

命令格式:
setLabelReleaseCallback(labelName, luaFunctionName, [any arguments])
指定一个Lua函数,该函数在源自指定标签/控制台的鼠标单击结束时调用。即使在释放单击之前将鼠标拖离标签/控制台,也会调用此函数。此函数可以传递任意数量的字符串或整数值作为附加参数。然后在回调中使用这些参数-因此您可以将数据与标签/按钮相关联。此外,此函数传递事件表作为最终参数,如 setLabelClickCallback()函数

setLabelStyleSheet

命令格式:
setLabelStyleSheet(label, markup)
通过特殊的标记语言将Qt样式格式应用于标签。

setLabelStyleSheet

命令格式:
setLabelStyleSheet(label, markup)
通过特殊的标记语言将Qt样式格式应用于标签。

-- This creates a label with a white background and a green border, with the text "test"
-- inside.
createLabel("test", 50, 50, 100, 100, 0)
setLabelStyleSheet("test", [[
  background-color: white;
  border: 10px solid green;
  font-size: 12px;
  ]])
echo("test", "test")

-- This creates a label with a single image, that will tile or clip depending on the
-- size of the label. To use this example, please supply your own image.
createLabel("test5", 50, 353, 164, 55, 0)
setLabelStyleSheet("test5", [[
  background-image: url("C:/Users/Administrator/.config/mudlet/profiles/Midkemia Online/Vyzor/MkO_logo.png");
  ]])

-- This creates a label with a single image, that can be resized (such as during a
-- sysWindowResizeEvent). To use this example, please supply your own image.
createLabel("test9", 215, 353, 100, 100, 0)
setLabelStyleSheet("test9", [[
  border-image: url("C:/Users/Administrator/.config/mudlet/profiles/Midkemia Online/Vyzor/MkO_logo.png");
  ]])

--This creates a label whose background changes when the users mouse hovers over it.

--putting the styleSheet in a variable allows us to easily change the styleSheet. We also are placing colors in variables that have been preset.  
local labelBackgroundColor = "#123456"
local labelHoverColor = "#654321"
local labelFontSize = 12
local labelName = "HoverLabel"
local ourLabelStyle = [[
QLabel{
	background-color: ]]..labelBackgroundColor..[[;
	font-size: ]]..labelFontSize..[[px;
	qproperty-alignment: 'AlignCenter | AlignCenter';
}
QLabel::hover{
	background-color: ]]..labelHoverColor..[[;
	font-size: ]]..labelFontSize..[[px;
	qproperty-alignment: 'AlignCenter | AlignCenter';
}
]]

--Creating the label using the labelName and ourLabelStyle variables created above.
createLabel(labelName,0,0,400,400,1)
setLabelStyleSheet(labelName, ourLabelStyle)
echo("HoverLabel","This text shows while mouse is or is not over the label.")

--Using QLabel::hover mentioned above. Lets "trick" the label into changing it's text.
--Please keep in mind that the setLabelMoveCallback allows for much more control over not just your label but your entire project.

--putting the styleSheet in a variable allows us to easily change the styleSheet. We also are placing colors in variables that have been preset.  
local labelBackgroundColor = "#123456"
local labelHoverColor = "#654321"
local labelFontSize = 12
local labelName = "HoverLabel"
--Notice we are adding a string returned from a function. In this case, the users profile directory.
local ourLabelStyle = [[
QLabel{
	border-image: url("]]..getMudletHomeDir()..[[/imagewithtext.png");
}
QLabel::hover{
	border-image: url("]]..getMudletHomeDir()..[[/imagewithhovertext.png");
}
]]

--Creating the label using the labelName and ourLabelStyle variables created above.
createLabel(labelName,0,0,400,400,1)
setLabelStyleSheet(labelName, ourLabelStyle)
--This is just to example that echos draw on top of the label. You would not want to echo onto a label you were drawing text on with images, because echos would draw on top of them.
echo("HoverLabel","This text shows while mouse is or is not over the label.")

setLabelCursor

命令格式:
setLabelCursor(labelName, cursorShape)
更改鼠标光标在标签上的外观。

setLabelCustomCursor

命令格式:
setLabelCustomCursor(labelName, custom cursor, [hotX, hotY])
将标签上的鼠标光标形状更改为自定义光标。

setLabelWheelCallback

命令格式:
setLabelWheelCallback(labelName, luaFunctionName, [any arguments])
指定在指定标签/控制台内滚动鼠标滚轮时调用的Lua函数。此函数可以传递任意数量的字符串或整数值作为附加参数。然后在回调中使用这些参数-因此您可以将数据与标签/按钮相关联。此外,此函数传递事件表作为最终参数,类似于 setLabelClickCallback()函数, 但信息略有不同。

命令格式:
setLink([windowName], command, tooltip)
设置文本到一个可点击的链接-点击后,链接将执行命令代码。工具提示是一个字符串,当鼠标在选定的文本上时将显示。

setMainWindowSize

命令格式:
setMainWindowSize(mainWidth, mainHeight)
将主Mudlet窗口的大小更改为给定的值。

setMapWindowTitle

命令格式:
setMapWindowTitle(text)
更改小地图窗口弹出时显示的标题。

setMiniConsoleFontSize

命令格式:
setMiniConsoleFontSize(name, fontSize)
设置迷你控制台的字体大小。

setMovie

命令格式:
setMovie(label name, path to gif)
将gif添加到选定标签并对其设置动画。请注意,gif的播放成本相当高,所以不要一次添加太多。

例子:

-- download & show a gif within mudlet
local saveto = getMudletHomeDir().."/kymip.gif"
-- animation credit to https://opengameart.org/content/kymiball-ii-third-prototype-scraps
local url = "https://opengameart.org/sites/default/files/kymip_0.gif"

if downloadHandler then killAnonymousEventHandler(downloadHandler) end
downloadHandler = registerAnonymousEventHandler("sysDownloadDone",
  function(_, filename)
    if filename ~= saveto then
      return true
    end
    
    local width, height = getImageSize(saveto)

    createLabel("kymip", 300, 300, width, height, 0)
    setMovie("kymip", saveto)
    setLabelReleaseCallback("kymip", function() deleteLabel("kymip") end)
  end, true)

downloadFile(saveto, url)

local gifpath = getMudletHomeDir().."/movie.gif"

local width, height = getImageSize(gifpath)

-- create a label with the name mygif
createLabel("mygif", 0, 0, width, height,0)
-- put the gif on the label and animate it
setMovie("mygif", gifpath)

startMovie("mygif")

pauseMovie("mygif")
setMovieFrame("mygif", 12)
startMovie("mygif")
setMovieSpeed("mygif",150)

setMovieFrame

命令格式:
setMovieFrame(label name, frame nr)
跳转到gif中的特定帧。

setMovieSpeed

命令格式:
setMovieSpeed(label name, speed in percent)
以百分比为单位设置动画速度。

setMovieSpeed

命令格式:
setMovieSpeed(label name, speed in percent)
以百分比为单位设置动画速度。

setOverline

命令格式:
setOverline([windowName], boolean)
将当前文本字体设置为“重叠”(true)或“未重叠”(false)模式。如果省略windowName参数,将使用主屏幕。如果你在Mudlet缓冲区中已经选择了文本,那么选择内容将被覆盖。在后面添加的任何文本 echo()或 insertText()将被覆盖,直到您使用 resetFormat().

setPopup

命令格式:
setPopup([windowName], {lua code}, {hints})
文本到一个可左键单击的链接中,以及一个右键单击的菜单中的更多选项。所选文本在被左键单击时将执行列表中的第一个命令。右键单击后,它将显示一个包含所有可能命令的菜单。菜单将填充提示,每行一个提示。
例子:

selectString("Hello", 1)
setPopup("main", {function() send("bye") end, function() echo("hi!") end}, {"send 'bye' to the MUD", "click to echo 'hi!'"})

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
setPopup("main", {[[send("bye")]], [[echo("hi!")]]}, {"send 'bye' to the MUD", "click to echo 'hi!'"})

setProfileStyleSheet

命令格式:
setProfileStyleSheet(stylesheet)
为当前Mudlet配置文件设置样式表-允许您自定义主窗口之外的内容(配置文件选项卡、滚动条等)。这个函数比setAppStyleSheet()更好,因为它只影响当前配置文件,而不影响其他所有配置文件。
例子:

-- credit to Akaya @ http://forums.mudlet.org/viewtopic.php?f=5&t=4610&start=10#p21770
local background_color = "#26192f"
local border_color = "#b8731b"

setProfileStyleSheet([[
  QMainWindow {
     background: ]]..background_color..[[;
  }
  QToolBar {
     background: ]]..background_color..[[;
  }
  QToolButton {
     background: ]]..background_color..[[;
     border-style: solid;
     border-width: 2px;
     border-color: ]]..border_color..[[;
     border-radius: 5px;
     font-family: BigNoodleTitling;
     color: white;
     margin: 2px;
     font-size: 12pt;
  }
  QToolButton:hover { background-color: grey;}
  QToolButton:focus { background-color: grey;}

  QTreeView {
     background: ]]..background_color..[[;
     color: white;
  }

  QMenuBar{ background-color: ]]..background_color..[[;}

  QMenuBar::item{ background-color: ]]..background_color..[[;}

  QDockWidget::title {
     background: ]]..border_color..[[;
  }
  QStatusBar {
     background: ]]..border_color..[[;
  }
  QScrollBar:vertical {
     background: ]]..background_color..[[;
     width: 15px;
     margin: 22px 0 22px 0;
  }
  QScrollBar::handle:vertical {
     background-color: ]]..background_color..[[;
     min-height: 20px;
     border-width: 2px;
     border-style: solid;
     border-color: ]]..border_color..[[;
     border-radius: 7px;
  }
  QScrollBar::add-line:vertical {
   background-color: ]]..background_color..[[;
   border-width: 2px;
   border-style: solid;
   border-color: ]]..border_color..[[;
   border-bottom-left-radius: 7px;
   border-bottom-right-radius: 7px;
        height: 15px;
        subcontrol-position: bottom;
        subcontrol-origin: margin;
  }
  QScrollBar::sub-line:vertical {
   background-color: ]]..background_color..[[;
   border-width: 2px;
   border-style: solid;
   border-color: ]]..border_color..[[;
   border-top-left-radius: 7px;
   border-top-right-radius: 7px;
        height: 15px;
        subcontrol-position: top;
        subcontrol-origin: margin;
  }
  QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {
     background: white;
     width: 4px;
     height: 3px;
  }
  QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
     background: none;
  }
]])

-- if you'd like to reset it, use:
setProfileStyleSheet("")

-- to only affect scrollbars within the main window and miniconsoles, prefix them with 'TConsole':
setProfileStyleSheet[[
  TConsole QScrollBar:vertical {
      border: 2px solid grey;
      background: #32CC99;
      width: 15px;
      margin: 22px 0 22px 0;
  }
  TConsole QScrollBar::handle:vertical {
      background: white;
      min-height: 20px;
  }
  TConsole QScrollBar::add-line:vertical {
      border: 2px solid grey;
      background: #32CC99;
      height: 20px;
      subcontrol-position: bottom;
      subcontrol-origin: margin;
  }
  TConsole QScrollBar::sub-line:vertical {
      border: 2px solid grey;
      background: #32CC99;
      height: 20px;
      subcontrol-position: top;
      subcontrol-origin: margin;
  }
  TConsole QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {
      border: 2px solid grey;
      width: 3px;
      height: 3px;
      background: white;
  }
  TConsole QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
      background: none;
  }
]]

setReverse

命令格式:
setReverse([windowName], boolean)
将当前文本设置为交换前景色和背景色设置(true)或非(false)模式。

setStrikeOut

命令格式:
setStrikeOut([windowName], boolean)
将当前文本字体设置为删除(true)或不删除(false)模式。

setTextFormat

命令格式:
setTextFormat(windowName, r1, g1, b1, r2, g2, b2, bold, underline, italics, [strikeout], [overline], [reverse])
设置选定窗口的当前文本格式。
例子:

createMiniConsole( "con1", 0,0,300,100);
setTextFormat("con1",0,0,255,255,255,0,true,0,false,1);
echo("con1","This is a test")

setUnderline

命令格式:
setUnderline(windowName, bool)
将当前文本字体设置为下划线/非下划线模式。如果省略windowName参数,将使用主屏幕。

setUserWindowTitle

命令格式:
setUserWindowTitle(windowName, text)
为UserWindow 置新的标题文本windowName

setUserWindowStyleSheet

命令格式:
setUserWindowStyleSheet(windowName, markup)
通过特殊的标记语言将Qt样式格式应用到用户窗口的边框/标题区域。

setWindow

命令格式:
setWindow(windowName, name, [Xpos, Ypos, show])
更改元素的父窗口。

setWindowWrap

命令格式:
setWindowWrap(windowName, wrapAt)
设置在行中的哪个位置开始换行。

setWindowWrapIndent

命令格式:
setWindowWrapIndent(windowName, wrapTo)
设置换行的文本缩进的空格数(当然是在第一行之后)。

showCaptureGroups

命令格式:
showCaptureGroups()
Lua调试函数,在屏幕上以随机颜色突出显示触发正则表达式中的所有捕获组。如果你制作复杂的正则表达式并想看到文本中真正匹配的内容,这是非常方便的。此函数在DebugTools.lua中定义。

showMultimatches

命令格式:
showMultimatches()
Lua帮助函数显示表multimatches[n][m]包含什么。这在调试多行触发器时非常有用–只要在脚本中执行showMultimmatches()就可以让它给予信息。此函数在DebugTools. lua中定义。

showWindow

命令格式:
showWindow(name)
使隐藏窗口(标签或小窗口)再次显示。

startMovie

命令格式:
startMovie(label name)
启动gif动画-如果之前已停止或暂停。

showColors

命令格式:
showColors([columns], [filterColor], [sort])
显示了Mudlet颜色表中当前可用的命名颜色。

showColors

命令格式:
showColors([columns], [filterColor], [sort])
显示了Mudlet颜色表中当前可用的命名颜色。

showGauge

命令格式:
showGauge(gaugeName)
显示给定的仪表,以防它以前被隐藏。

showToolBar

命令格式:
showToolBar(name)
使工具栏(按钮组)出现在屏幕上。

suffix

命令格式:
suffix(text, [writingFunction], [foregroundColor], [backgroundColor], [windowName])
在当前行末尾添加文本后缀。

setCommandBackgroundColor

命令格式:
setCommandBackgroundColor([windowName], r, g, b, [transparency])
设置命令回显的背景色。颜色从0到255(0表示黑色),透明度从0到255(0表示完全透明)。

setCommandForegroundColor

命令格式:
setCommandForegroundColor([windowName], r, g, b, [transparency])
设置命令回显的前景色。颜色从0到255(0表示黑色),透明度从0到255(0表示完全透明)。

scrollDown

命令格式:
scrollDown([windowName,] [lines])
在窗口中向下滚动一定数量的行。

scrollUp

命令格式:
scrollUp([windowName,] [lines])
在窗口中向上滚动一定数量的行。

scrollTo

命令格式:
scrollTo([windowName,] [lineNumber])
将窗口滚动到缓冲区中的特定行。

windowType

命令格式:
typeOfWindow = windowType(windowName)
给定窗口的名称,如果它是标签、miniconsole、userwindow还是命令行,将返回。

testLabel = Geyser.Label:new({name = "testLabel"})
display(windowType(testLabel.name))  -- displays "label"

-- the main console returns "miniconsole" because it uses the same formatting functions
display(windowType("main")) -- displays "miniconsole"

-- check for the existence of a window
local windowName = "this thing does not exist"
local ok, err = windowType(windowName)
if ok then
  -- do things with it, as it does exist.
  -- the ok variable will hold the type of window it is ("label", "commandline", etc)
else
  cecho("<red>ALERT!! window does not exist")
end

wrapLine

命令格式:
wrapLine(windowName, lineNumber)
将指定的行换行 此函数将解释\n字符,应用自动换行并在屏幕上显示新行。如果您使用deleteLine()擦除缓冲区中的整个当前行,那么这个函数可能是必需的,但是您希望在调用deleteLine()之后再执行一些echo()调用。然后,您需要重新包装缓冲区的最后一行,以实际查看您已返回的内容,并将您的\n正确地解释为换行符。使用此函数不是一种良好的编程实践,应该避免使用。有更好的方法来处理你会调用deleteLine()和echo之后的情况

Discord函数

所有功能来自定义Mudlet在Discord丰富的在线界面中显示的信息。要了解所有这些函数如何结合在一起的概述,请参阅Discord脚本概述。

getDiscordDetail

命令格式:
getDiscordDetail()
回用于Discord Rich Presence详细信息字段的文本。看到Discord文档以便于在显示细节的地方提供方便的图像参考。

getDiscordLargeIcon

命令格式:
getDiscordLargeIcon()
返回用于Discord Rich Presence的大图标名称。看到 Discord 文档 以获取有关显示大图标位置的方便图像参考。

getDiscordLargeIconText

命令格式:
getDiscordLargeIconText()

getDiscordParty

命令格式:
getDiscordParty()

getDiscordSmallIcon

命令格式:
getDiscordSmallIcon()

getDiscordSmallIconText

命令格式:
getDiscordSmallIconText()

getDiscordState

命令格式:
getDiscordState()

getDiscordTimeStamps

命令格式:
getDiscordTimeStamps()

resetDiscordData

命令格式:
resetDiscordData()

-- Use 'afk' emote in game, clear Discord party status and estimate return
send("afk")
resetDiscordData()
setDiscordState("Back in 15")
setDiscordRemainingEndTime(os.time(os.date("*t"))+(60 * 15))

setDiscordApplicationID

命令格式:
setDiscordApplicationID(id)

setDiscordDetail

命令格式:
setDiscordDetail(text)
设置要在Discord Rich Presence的详细信息字段中显示的文本。

setDiscordElapsedStartTime

命令格式:
setDiscordElapsedStartTime(time)

setDiscordElapsedStartTime(os.time(os.date("*t")))

setDiscordGame

命令格式:
setDiscordGame(text)

setDiscordGameUrl

命令格式:
setDiscordGameUrl([url], [name])

setDiscordLargeIcon

命令格式:
setDiscordLargeIcon(iconName)
关键字: armor, axe, backpack, bow, coin, dagger, envelope, gem-blue, gem-green, gem-red, hammer, heart, helmet, map, shield, tome, tools, wand, wood-sword 对应如下: 盔甲,斧头,背包,弓,硬币,匕首,信封,宝石蓝色,宝石绿色,宝石红色,锤子,心脏,头盔,地图,盾牌,托姆,工具,魔杖,木剑 等。(Discord限制为150个图标)

setDiscordLargeIconText

命令格式:
setDiscordLargeIconText(text)
设置图标文本提示

setDiscordParty

命令格式:
setDiscordParty(current, max)

setDiscordRemainingEndTime

命令格式:
setDiscordRemainingEndTime(time)

setDiscordSmallIcon

命令格式:
setDiscordSmallIcon(iconName)

setDiscordSmallIconText

命令格式:
setDiscordSmallIconText(text)

setDiscordState

命令格式:
setDiscordState(state)

local currentarea = getRoomArea(getPlayerRoom())
local areaname = getAreaTableSwap()[currentarea]
setDiscordDetail(areaname)

usingMudletsDiscordID

命令格式:
usingMudletsDiscordID()

usingMudletsDiscordID

命令格式:
usingMudletsDiscordID()

mudlet/manual.txt · 最后更改: 2023/11/18 09:53 由 sulryn