LUA各种库
LUAstring库详解

LUAstring库详解1. string库中所有的字符索引从前往后是1,2,...;从后往前是-1,-2,...2. string库中所有的function都不会直接操作字符串,⽽是返回⼀个结果s = "[abc]"string.len(s) <==返回5string.rep("abc", 2) <==返回"abcabc"string.lower("ABC") <==返回"abc"string.upper("abc") <==返回"ABC"string.sub(s, 2) <==返回"abc]"string.sub(s, -2) <==返回"c]"string.sub(s, 2, -2) <==返回"abc"string.format(fmt, ...)返回⼀个类似printf的格式化字符串string.find(s, pattern, pos)第1个参数:源字符串第2个参数:待搜索之模式串第3个参数:A hint, 从pos位置开始搜索找到匹配返回:匹配串开始和结束的位置,否则返回nil简单的模式串s = "hello world"i, j = string.find(s, "hello")print(i, j) --> 1 5print(string.sub(s, i, j)) --> helloprint(string.find(s, "world")) --> 7 11i, j = string.find(s, "l")print(i, j) --> 3 3print(string.find(s, "lll")) --> nil格式化的模式串s = "Deadline is 30/05/1999, firm"date = "%d%d/%d%d/%d%d%d%d"print(string.sub(s, string.find(s, date))) --> 30/05/1999下⾯的表列出了Lua⽀持的所有字符类:. 任意字符%s 空⽩符%p 标点字符%c 控制字符%d 数字%x ⼗六进制数字%z 代表0的字符%a 字母%l ⼩写字母%u ⼤写字母%w 字母和数字上⾯字符类的⼤写形式表⽰⼩写所代表的集合的补集。
Lua中的string库(字符串函数库)总结

Lua中的string库(字符串函数库)总结Lua解释器对字符串的⽀持很有限。
⼀个程序可以创建字符串并连接字符串,但不能截取⼦串,检查字符串的⼤⼩,检测字符串的内容。
在Lua中操纵字符串的功能基本来⾃于string库。
字符串库中的⼀些函数是⾮常简单的:string.len(s) 返回字符串s的长度;string.rep(s, n) 返回重复n次字符串s的串;你使⽤string.rep("a", 2^20)可以创建⼀个1M bytes的字符串(⽐如,为了测试需要);string.lower(s) 将s中的⼤写字母转换成⼩写(string.upper将⼩写转换成⼤写)。
如果你想不关⼼⼤⼩写对⼀个数组进⾏排序的话,你可以这样:复制代码代码如下:table.sort(a, function (a, b) return string.lower(a) < string.lower(b) end)string.upper(s) 将s中的⼩写字母转换成⼤写string.upper和string.lower都依赖于本地环境变量。
所以,如果你在 European Latin-1环境下,表达式:复制代码代码如下:string.upper("a??o") --> "A??O"string.sub(s,i,j) 函数截取字符串s的从第i个字符到第j个字符之间的串。
Lua中,字符串的第⼀个字符索引从1开始。
你也可以使⽤负索引,负索引从字符串的结尾向前计数:-1指向最后⼀个字符,-2指向倒数第⼆个,以此类推。
所以, string.sub(s, 1, j)返回字符串s的长度为j的前缀;string.sub(s, j, -1)返回从第j个字符开始的后缀。
如果不提供第3个参数,默认为-1,因此我们将最后⼀个调⽤写为string.sub(s, j);string.sub(s, 2, -2)返回去除第⼀个和最后⼀个字符后的⼦串。
lua5.2中的base库

Lua5.2中的base库(转)Lua中base库里面的接口都是全局可见的,我在全局环境一篇里面已经谈到了。
在lua5.2中base库增加了2个全局变量和23个函数,这些都可以在lbaselib.c里面找到。
首先增加了两个变量:_G = 当前lua中的全局环境_VERSION = LUA_VERSION其中LUA_VERSION是一个宏,在每个版本的Lua中都不一样,定义在lua.h中可以看到如果我用print(_VERSION) 打印出来,那么显示的应该是Lua 5.2。
下面按照字典序来解释这23个函数,点击下面的函数名跳转到对应的位置:assertcollectgarbagedofileerrorgetmetatableipairsloadloadfileloadstringnextpairspcallprintrawequalrawlenrawgetrawsetselectsetmetatabletonumbertostringtypexpcallassert(v, [message])功能:抛出一个错误,当参数v 的值为nil 或者false 时,否则就返回assert 的所有参数。
用法:1、local a = assert(false, "this is a error") --引发一个错误,执行后会报一个错误,并打印出this is a error,如下:2、local a, b = assert(true, "this is a error") print(a, b)--不引发错误,返回assert 的所有参数,如下:collectgarbage(opt, [arg])功能:根据opt选项来操作垃圾收集器。
用法:opt有11个选项:stop:停止自动执行的垃圾收集器,直到下次显示调用restart 选项restart:重新启动自动执行的垃圾收集器collect:执行一次完整的垃圾收集循环count:返回lua使用的总内存大小,第一个返回值为内存大小(KB),第二个值为这个大小(BYTE)对1024取模的值step:执行指定步数的垃圾收集,步数由arg参数指定setpause:设置arg为当前垃圾收集器pause数,并返回设置前的值setstepmul:设置arg为当前垃圾收集器step multiplier的值,并返回设置前的值setmajorinc:设置arg为当前垃圾收集器setmajorinc的值,并返回设置前的值isrunning:返回垃圾收集器当前的状态,start状态为true,stop状态为falsegenerational:把垃圾收集器转换为generational模式incremental:把垃圾收集器转换为incremental模式dofile([fllename])功能:打开filename文件,并将其内容当做一个lua块来执行,如果filename缺省,则执行当前标准输入。
lua sqlite cursor 中文列名 使用方法

lua sqlite cursor 中文列名使用方法Lua SQLite库提供了一种方便的方法来操作SQLite数据库,其中包括了对游标的支持。
游标是一种用于遍历数据库表中的数据的对象。
在SQLite中,游标可以用于检索和处理表中的数据。
一、游标概述Lua SQLite库中的游标允许您在表中检索数据,并对数据进行各种操作。
游标提供了一种迭代数据集的方式,可以在遍历数据时执行各种命令和操作。
二、使用游标检索数据要使用Lua SQLite库中的游标检索数据,您需要先打开一个数据库连接,然后创建一个游标对象。
接下来,您可以使用`SELECT`语句从表中检索数据,并将结果绑定到游标的变量中。
以下是一个简单的示例代码,演示了如何使用游标检索数据:```lua-- 打开数据库连接local db, err = sqlite.open("example.db")if db == nil thenprint("无法打开数据库: " .. err)returnend-- 创建游标对象local cursor, err = db:cursor("my_table")if cursor == nil thenprint("创建游标失败: " .. err)db:close()returnend-- 使用SELECT语句检索数据local rows, err = cursor:execute("SELECT * FROM my_table") if rows == nil thenprint("检索数据失败: " .. err)cursor:close()db:close()returnend-- 遍历数据并处理结果for row in rows dolocal column1 = row["column1"] -- 使用中文列名获取数据 local column2 = row["列二"] -- 可以使用其他中文列名获取数据-- 对获取的数据进行操作或输出print("列一值: " .. column1)print("列二值: " .. column2)end-- 关闭游标和数据库连接cursor:close()db:close()```在上面的示例中,我们首先打开了一个数据库连接,并创建了一个游标对象。
lua扩展库V1.4

lua扩展库V1.4目录扩展库 (2)1. bit (2)2. cpu (6)3. i2c (7)4. pack (9)5. pio (11)6. pmd (14)7. rtos (16)8. uart (21)9. adc (24)10. iconv (25)11. audiocore (26)12. apn (29)扩展库1.bit位操作库Functionsbit.bit bit.isset bit.isclear bit.set bit.clear bit.bnot bit.band bit.bor bit.bxor bit.lshift bit.rshift bit.arshiftnumber = bit.bit( position )Generate a number with a 1 bit (used for mask generation). Equivalent to 1 << position in C.Arguments: position - position of the bit that will be set to 1.Returns: number - a number with only one 1 bit at position (the rest are set to 0).flag = bit.isset( value, position )Test if a given bit is set.Arguments:∙value - the value to test.∙position - bit position to test.Returns: boolean - true if the bit at the given position is 1, false otherwise.flag = bit.isclear( value, position )Test if a given bit is cleared.Arguments:∙value - the value to test.∙position - bit position to test.Returns: boolean - true if the bit at the given position is 0, false othewise. number = bit.set( value, pos1, pos2, ..., posn )Set bits in a number.Arguments:∙value - the base number.∙pos1 - position of the first bit to set.∙pos2 - position of the second bit to set.∙posn - position of the nth bit to set.Returns: number - the number with the bit(s) set in the given position(s). number = bit.clear( value, pos1, pos2, ..., posn ) Clear bits in a number.Arguments:∙value - the base number.∙pos1 - position of the first bit to clear.∙pos2 - position of the second bit to clear.∙posn - position of thet nth bit to clear.Returns: number - the number with the bit(s) cleared in the given position(s). number = bit.bnot( value )Bitwise negation, equivalent to ~value in C.Arguments: value - the number to negate.Returns: number - the bitwise negated value of the number.number = bit.band( val1, val2, ... valn )Bitwise AND, equivalent to val1 & val2 & ... & valn in C.Arguments:∙val1 - first AND argument.∙val2 - second AND argument.∙valn - nth AND argument.Returns: number - the bitwise AND of all the arguments.number = bit.bor( val1, val2, ... valn )Bitwise OR, equivalent to val1 | val2 | ... | valn in C.Arguments:∙val1 - first OR argument.∙val2 - second OR argument.∙valn - nth OR argument.Returns: number - the bitwise OR of all the arguments. number = bit.bxor( val1, val2, ... valn )Bitwise exclusive OR (XOR), equivalent to val1 ^ val2 ^ ... ^ valn in C. Arguments:∙val1 - first XOR argument.∙val2 - second XOR argument.∙valn - nth XOR argument.Returns: number - the bitwise exclusive OR of all the arguments. number = bit.lshift( value, shift )Left-shift a number, equivalent to value < shift in C.Arguments:∙value - the value to shift.∙shift - positions to shift.Returns: number - the number shifted leftnumber = bit.rshift( value, shift )Logical right shift a number, equivalent to ( unsigned )value >> shift in C. Arguments:∙value - the value to shift.∙shift - positions to shift.Returns: number - the number shifted right (logically).number = bit.arshift( value, shift )Arithmetic right shift a number equivalent to value >> shift in C. Arguments:∙value - the value to shift.∙shift - positions to shift.Returns: number - the number shifted right (arithmetically).2.cpu包含cpu中断id定义Data structures, constants and typescpu.INT_GPIO_POSEDGEcpu.INT_GPIO_NEGEDGE中断id:INT_GPIO_POSEDGE GPIO上升沿中断INT_GPIO_NEGEDGE GPIO下降沿中断FunctionsNull3.i2ci2c操作接口Functionsi2c.setup i2c.write i2c.readspeed = i2c.setup( id, speed, slave )打开I2C接口Arguments:∙id - i2c接口id,目前支持i2c id=1即模块的I2C2∙speed - i2c.FAST (400KHz), i2c.SLOW (100KHz)∙slave - i2c外设地址0x00-0x7fReturns: 可以根据返回的频率值判断是否成功打开i2c wrote = i2c.write( id, reg, data )往指定的寄存器地址reg传输数据Arguments:∙id - i2c接口id∙reg - 写入i2c从设备的寄存器起始地址∙data - number / string / table,自动根据参数类型写数据,num只写1个字节,string/table 自动根据输入的长度传输相应字节Returns: 传输成功的字节数data = i2c.read( id, reg, num )读取指定寄存器地址reg的数据内容Arguments:∙id - i2c接口id∙reg - 读取i2c从设备的寄存器起始地址∙num - 读取数据字节数Returns: 返回读取的数据,二进制数据会包含非可见字符,请使用string.byte打印数据流speed = i2c.close( id )关闭I2C接口Arguments:∙id - i2c接口id,目前支持i2c id=1即模块的I2C2Returns: nothing4.packpack库支持将一系列数据按照格式字符转化为lua字符串或者将lua字符串按照格式字符转化成一系列值∙endianness is an optional endian flags that specifies how the numbers that are to be packed/unpacked are stored in memory. It can be either:1.'<' for little endian.2.'>' for big endian.3.'=' for native endian (the platform's endian order, default).∙format specifier describes what kind of variable will be packed/unpacked. The format specifier is case-sensitive. The possible values of this parameter are summarized in the table below:∙count is an optional counter for the format specifier. For example, i5 instructs the code to pack/unpack 5 integer variables, as opposed to i that specifies a single integer variable. Functionspack.pack pack.unpackpacked = pack.pack( format, val1, val2, ..., valn )Packs variables in a string.Arguments:∙∙val1 - first variable to pack.∙val2 - second variable to pack.∙valn - nth variable to pack.Returns: packed - a string containing the packed representation of all variables according to the format.nextpos, val1, val2, ..., valn = pack.unpack( string, format, [ init ] )Unpacks a stringArguments:∙string - the string to unpack.∙∙init - (optional) marks where in string the unpacking should start (1 if not specified).Returns:∙nextpos - the position in the string after unpacking.∙val1 - the first unpacked value.∙val2 - the second unpacked value.∙valn - the nth unpacked value.5.piopio.P0_0 - pio.P0_31表示GPIO_0 - GPIO_31pio.P1_0 - pio.P1_9表示GPO_0 - GPO_9GPIO工作方式有三种,通过pio.pin.setdir设置: pio.INPUT pio.OUTPUT pio.INTpio.INT中断方式来中断时通过rtos.MSG_INT消息通知,可以根据消息数据域来判断中断id与中断的pin脚:id - 中断idresnum - 中断pinFunctionspio.pin.setdir pio.pin.setval pio.pin.getval pio.pin.sethigh pio.pin.setlow pio.decodepio.pin.setdir( direction, pin1, pin2, ..., pinn )Set pin(s) directionArguments:∙direction - the pin direction, can be either pio.INPUT or pio.OUTPUT or pio.INT∙pin1 - the first pin∙pin2 (optional) - the second pin∙pinn (optional) - the n-th pinReturns: nothing.pio.pin.setval( value, pin1, pin2, ..., pinn )Set pin(s) valueArguments:∙value - pin value, can be either 0 or 1∙pin1 - the first pin∙pin2 (optional) - the second pin∙pinn (optional) - the n-th pinReturns: nothing.val1, val2, ..., valn = pio.pin.getval( pin1, pin2, ..., pinn ) Get value of pin(s)Arguments:∙pin1 - the first pin∙pin2 (optional) - the second pin∙pinn (optional) - the n-th pinReturns: The value(s) of the pin(s), either 0 or 1pio.pin.sethigh( pin1, pin2, ..., pinn )Set pin(s) to 1 (high)Arguments:∙pin1 - the first pin∙pin2 (optional) - the second pin∙pinn (optional) - the n-th pinReturns: nothing.pio.pin.setlow( pin1, pin2, ..., pinn )Set pin(s) to 0 (low)Arguments:∙pin1 - the first pin∙pin2 (optional) - the second pin∙pinn (optional) - the n-th pinReturns: nothing.port, pin = pio.decode( resnum )Convert a PIO resource number to the corresponding port and pin. This is most commonly used in GPIO edge interrupt routines to convert the Lua interrupt routine's argument to the port and pin that caused the interrupt but it can also be used on the values returned by the pin names pio.PA_0, pio.P2_15 and so on.Arguments: resnum - the resource number of the pinReturns:∙port - the index of the port, starting from 0 (so port A is 0, port B is 1 and so on)∙pin - the pin number, usually from 0 to 316.pmd电源管理接口:ldo控制,省电管理Data structures, constants and typespmd.LDO_KEYPADpmd.LDO_LCD--控制LED0-LED4pmd.KP_LEDRpmd.KP_LEDGpmd.KP_LEDBpmd.LDO_VIBpmd.LDO_VLCD--控制POWER_VLCDpmd.LDO_VASW -- V_ASWpmd.LDO_VMMC -- V_MMCldo id值Functionspmd.init pmd.ldoset pmd.sleepresult = pmd.init( param )设置电源管理参数电池充电控制,3阶段电流充电:一阶段:电压低于battlevelFirst 充电电流为currentFirst二阶段:电压高于battlevelFirst 低于battlevelSecond 充电电流为currentSecond三阶段:电压高于battlevelSecond至充满 4.25v 充电电流为currentThirdArguments:∙param - 参数表,电流有效值:50,100,150,200,300,400,500,600,700,800 电压值以mV为单位∙param.currentFirst - 电池电压小于一阶段电压值时的充电电流∙param.battlevelFirst - 一阶段电压值节点∙param.currentSecond - 电池电压大于一阶段电压值小于二阶段电压值时的充电电流∙param.battlevelSecond - 二阶段电压值节点∙param.currentThird - 电池电压大于二阶段电压值时的充电电流Returns: result - 1:成功0:失败pmd.ldoset( level, id1, [id2], ..., [idn] )ldo控制Arguments:∙level - ldo亮度0 - 7级0级关闭∙id1 - 要设置的第一个ldo∙id2 (optional) - 要设置的第2个ldo∙idn (optional) - 要设置的第n个ldoReturns: nothing.pmd.sleep( value )省电控制Arguments: value - 1 - 进入睡眠,0 - 退出睡眠Returns: nothing.7.rtos嵌入式系统接口:接收消息,软件定时器Functionsrtos.init_module rtos.receive rtos.timer_start rtos.timer_stop rtos.poweron_reason rtos.poweron rtos.poweroff rtos.restart rtos.tick rtos.sleepPercentage=rtos.get_env_usagertos.init_module(module, [param1], ..., [paramn] )初始化模块Arguments:module - 按键功能rtos.MOD_KEYPAD,按键功能参数表:rtos.init_module(rtos.MOD_KEYPAD, type, [inmask, outmask])type: 键盘类型目前只有矩阵键盘(type = 0)inmask outmask: 矩阵键盘有效行列标记比如某矩阵键盘由keyin0 keyin3 keyout1 keyout4组成,inmask=1<0|1<3=0x09 outmask = 1<1|1<4=0x12Returns: nothing.msg,msgpara = rtos.receive(timeout)接收消息Arguments: timeout - timeout 超时返回以毫秒为单位,可以用#rtos.INF_TIMEOUT#表示阻塞等待消息Returns:如果msg为table类型,msg根据不同的消息msg.id会有不同的数据:如果msg为number类型,msg根据不同的消息msg会有不同的数据1.rtos.MSG_TIMER定时器超时消息msg.timer_id 或者msgpara为超时的定时器id2.rtos.MSG_UART_RXDATA串口ATC数据提醒msg.uart_id 或者msgpara为收到的数据的串口id或者atc,收到该消息后可以通过uart.read 接口读取数据3.rtos.MSG_KEYPAD键盘消息,必须初始化按键(#rtos.init_module#)后才会有键盘消息msg.pressed 按键按下/弹起msg.key_matrix_row 按键所在行值msg.key_matrix_col 按键所在列值4.rtos.WAIT_MSG_TIMEOUT等待消息超时5.rtos.MSG_INT中断消息msg.int_id 中断idmsg.int_resnum 中断pin脚编号6.rtos.MSG_PMD电源管理消息msg.present 电池在位状态msg.level 百分比0-100msg.voltage 电池电压msg.charger 充电器在位状态msg.state 充电状态:0-不在充电1-充电中2-充电停止rtos.timer_start( timer_id, timeout )启动定时器Arguments:∙timer_id - 定时器id,可以是任意整数,定时器到时msg.timer_id值为启动时定时器∙timeout - 定时器延时时间以毫秒为单位Returns: nothing.rtos.timer_stop(timer_id)停止定时器Arguments: timer_id - 输入与启动定时器时定义的id即可停止定时器Returns: nothing.reason=rtos.poweronreason()读取开机原因值Arguments: nothingReturns: 开机原因值,取值范围如下:rtos. POWERON_KEY:按键开机rtos. POWERON_CHARGER:充电开机rtos. POWERON_ALARM:闹钟开机rtos. POWERON_RESTART:软件重启开机rtos. POWERON_EXCEPTION:异常开机rtos. POWERON_HOST:HOST工具控制重启开机rtos. POWERON_WATCHDOG:软件看门狗开机rtos.poweron( flag )是否启动GSM开机Arguments:flag- 0表示不启动系统;1表示启动系统Returns: nothing.rtos.poweroff()软件关机Arguments: nothingReturns: nothing.rtos.restart()软件重启Arguments: nothingReturns: nothing.ticks=rtos.tick()获取系统开机运行时间总计数Arguments: nothingReturns: ticks,时间计数,每tick时长:Air200或Air202是1/16384秒,Air810是4.615毫秒。
lua库函数

Lua 是一种轻量级的脚本语言,常用于嵌入到其他应用程序中。
Lua 提供了很多内置的库函数,用于进行各种操作。
下面是一些常见的Lua 库函数:1.print(): 用于输出信息到控制台。
2.type(): 返回值的类型。
3.tonumber(): 将字符串转换为数字。
4.tostring(): 将值转换为字符串。
5.len(): 返回字符串的长度。
6.pairs(): 遍历表中的所有键值对。
7.ipairs(): 遍历表中的所有索引和对应的值。
8.next(): 返回下一个表中的键值对。
9.math.abs(): 返回数的绝对值。
10.math.floor(): 返回不大于给定数的最大整数。
11.math.ceil(): 返回不小于给定数的最小整数。
12.math.sqrt(): 返回数的平方根。
13.math.random(): 生成随机数。
14.math.randomseed(): 设置随机数种子。
15.string.find(): 在字符串中查找子串。
16.string.match(): 在字符串中查找匹配的模式。
17.string.gsub(): 在字符串中替换匹配的模式。
18.table.insert(): 在表中插入一个元素。
19.table.remove(): 从表中删除一个元素。
20.table.concat(): 将多个表或数组连接成一个表或数组。
以上只是一部分常见的Lua 库函数,Lua 还提供了很多其他的库函数和模块,可以用于进行各种复杂的操作和处理。
Lua的table库函数insert、remove、concat、sort详细介绍

Lua的table库函数insert、remove、concat、sort详细介绍函数列表:table.insert(table,[ pos,] value)table.remove(table[, pos])table.concat(table[, sep[, i[, j]]])table.sort(table[, comp])1. insert 和 remove 只能⽤于数组元素的插⼊和移出,进⾏插⼊和移出时,会将后⾯的元素对齐起来。
所以在 for 循环中进⾏ insert 和 remove 的时候要注意插⼊和移除时是否漏掉了某些项:复制代码代码如下:local t = {1,2,3,3,5,3,6}for i,v in ipairs(t) doif v == 3 thentable.remove(t,i)endend-- 错误,第四个 3 没有被移除,ipairs 内部会维护⼀个变量记录遍历的位置,remove 掉第三个数字 3 之后,ipairs 下⼀个返回的值是 5 ⽽不是 3local t = {1,2,3,3,5,3,6}for i=1, #t doif t[i] == 3 thentable.remove(t,i)i = i-1endend-- 错误,i=i-1 这段代码没有⽤,i 的值始终是从 1 到 #t,for 循环⾥修改 i 的值不起作⽤local t = {1,2,3,3,5,3,6}for i=#t, 1, -1 doif t[i] == 3 thentable.remove(t,i)endend-- 正确,从后往前遍历local t = {1,2,3,3,5,3,6}local i = 1while t[i] doif t[i] == 3 thentable.remove(t,i)elsei = i+1endend-- 正确,⾃⼰控制 i 的值是否增加2. concat 可以将 table 的数组部分拼接成⼀个字符串,中间⽤ seq 分隔。
Lua字符串库(string库)学习笔记 电脑资料

Lua字符串库(string库)学习笔记电脑资料这篇文章主要介绍了Lua字符串库(string库)学习笔记,本文列举了一些常用的Lua字符串库函数,如byte、char、dump、find等,需要的朋友可以参考下Lua 最强大的特性之一就是它的字符串处理能力,它支持字符格式化输出,具有可扩展的模式匹配查找功能,以及一些实用的字符操作,例如查询、截取、替换和删除等字符串操作,这些字符串操作函数都封装在一个名为 string 的模块里,Lua 里的字符索引是从 1 开始,索引值也可以是负数,这种情况将被解释成向后索引,从字符串末尾开始算起。
下面是 Lua 5.2 提供的字符串操作函数:函数 string.byte 把字符串里的第 i 个字符转为 ASCII 编码,默认是输出第一个字符的编码(只有一个参数的话),用法:代码如下:string.byte (s [, i [, j]])例子:代码如下:print(string.byte("abc")) //echo:97print(string.byte("abc", 2))//echo:98函数 string.char 是把一个 ASCII 编码转换为对应的字符,用法:代码如下:string.char (asc1, ...)例子:代码如下:print(string.char(97)) //echo aprint(string.char(99, 100, 101)) //echo cde函数 string.dump 返回一个函数二进制形式的字符串,用法:代码如下:string.dump (function)参数 function 是一个 Lua 函数:代码如下:function test()print("just a test")endprint(string.dump(test))函数 string.dump 实现了函数的序列化,函数可以很轻松的传递,并在其他作用域调用。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1.math库函数名描述示例结果pi圆周率math.pi 3.1415926535898abs取绝对值math.abs(-2012)2012ceil向上取整math.ceil(9.1)10floor向下取整math.floor(9.9)9max取参数最大值math.max(2,4,6,8)8min取参数最小值math.min(2,4,6,8)2pow计算x的y次幂math.pow(2,16)65536sqrt开平方math.sqrt(65536)256mod取模math.mod(65535,2)1modf取整数和小数部分math.modf(20.12)200.12randomseed设随机数种子math.randomseed(os.time())random取随机数math.random(5,90)5~90rad角度转弧度math.rad(180) 3.1415926535898deg弧度转角度math.deg(math.pi)180exp e的x次方math.exp(4)54.598150033144log计算x的自然对数math.log(54.598150033144)4log10计算10为底,x的对数math.log10(1000)3frexp将参数拆成x*(2^y)的形式math.frexp(160)0.6258ldexp计算x*(2^y)math.ldexp(0.625,8)160sin正弦math.sin(math.rad(30))0.5cos余弦math.cos(math.rad(60))0.5tan正切math.tan(math.rad(45))1asin反正弦math.deg(math.asin(0.5))30acos反余弦math.deg(math.acos(0.5))60atan正切math.deg(math.atan(1))452、lua table库table.concat(table,sep,start,end)concat是concatenate(连锁,连接)的缩写.table.concat()函数列出参数中指定table的数组部分从start位置到end位置的所有元素,元素间以指定的分隔符(sep)隔开。
除了table外,其他的参数都不是必须的,分隔符的默认值是空字符,start的默认值是1,end的默认值是数组部分的总长.sep,start,end这三个参数是顺序读入的,所以虽然它们都不是必须参数,但如果要指定靠后的参数,必须同时指定前面的参数.>tbl={"alpha","beta","gamma"}>print(table.concat(tbl,":"))alpha:beta:gamma>print(table.concat(tbl,nil,1,2))alphabeta>print(table.concat(tbl,"\n",2,3))betagammatable.insert(table,pos,value)table.insert()函数在table的数组部分指定位置(pos)插入值为value的一个元素.pos参数可选,默认为数组部分末尾.>tbl={"alpha","beta","gamma"}>table.insert(tbl,"delta")>table.insert(tbl,"epsilon")>print(table.concat(tbl,",")alpha,beta,gamma,delta,epsilon>table.insert(tbl,3,"zeta")>print(table.concat(tbl,",")alpha,beta,zeta,gamma,delta,epsilontable.maxn(table)table.maxn()函数返回指定table中所有正数key值中最大的key值.如果不存在key值为正数的元素,则返回0.此函数不限于table的数组部分.>tbl={[1]="a",[2]="b",[3]="c",[26]="z"}>print(#tbl)3--因为26和之前的数字不连续,所以不算在数组部分内>print(table.maxn(tbl))26>tbl[91.32]=true>print(table.maxn(tbl))91.32table.remove(table,pos)table.remove()函数删除并返回table数组部分位于pos位置的元素.其后的元素会被前移.pos参数可选,默认为table长度,即从最后一个元素删起. table.sort(table,comp)table.sort()函数对给定的table进行升序排序.>tbl={"alpha","beta","gamma","delta"}>table.sort(tbl)>print(table.concat(tbl,","))alpha,beta,delta,gammacomp是一个可选的参数,此参数是一个外部函数,可以用来自定义sort函数的排序标准.此函数应满足以下条件:接受两个参数(依次为a,b),并返回一个布尔型的值,当a应该排在b前面时,返回true,反之返回false.例如,当我们需要降序排序时,可以这样写:>sortFunc=function(a,b)return b<a end>table.sort(tbl,sortFunc)>print(table.concat(tbl,","))gamma,delta,beta,alpha用类似的原理还可以写出更加复杂的排序函数.例如,有一个table存有工会三名成员的姓名及等级信息:guild={}table.insert(guild,{name="Cladhaire",class="Rogue",level=70,})table.insert(guild,{name="Sagart",class="Priest",level=70,})table.insert(guild,{name="Mallaithe",class="Warlock",level=40,})对这个table进行排序时,应用以下的规则:按等级升序排序,在等级相同时,按姓名升序排序.可以写出这样的排序函数:function sortLevelNameAsc(a,b)if a.level==b.level thenreturn <elsereturn a.level<b.levelendend测试功能如下:>table.sort(guild,sortLevelNameAsc)>for idx,value in ipairs(guild)do print(idx,)end1,Mallaithe2,Cladhaire3,Sagarttable.foreachi(table,function(i,v))会期望一个从1(数字1)开始的连续整数范围,遍历table中的key和value逐对进行function(i,v)操作t1={2,4,6,language="Lua",version="5",8,10,12,web="hello lua"};table.foreachi(t1,function(i,v)print(i,v)end);--等价于foreachi(t1,print)输出结果:12243648510612table.foreach(table,function(i,v))与foreachi不同的是,foreach会对整个表进行迭代t1={2,4,6,language="Lua",version="5",8,10,12,web="hello lua"};table.foreach(t1,function(i,v)print(i,v)end);输出结果:12243648510612web hello lualanguage Luaversion5table.getn(table)返回table中元素的个数t1={1,2,3,5};print(getn(t1))->4table.setn(table,nSize)设置table中的元素个数table.nums(table)table中键值对的个数3.Lua String库函数描述示例结果len计算字符串长度string.len("abcd")4rep返回字符串s的n个拷贝string.rep("abcd",2)abcdabcd lower返回字符串全部字母大写string.lower("AbcD")abcd upper返回字符串全部字母小写string.upper("AbcD")ABCD format返回一个类似printf的格式化字符串string.format("the value is:%d",4)the value is:4 sub returns substring from index i to j of sstring.sub("abcd",2)bcdstring.sub("abcd",-2)cdstring.sub("abcd",2,-2)bcstring.sub("abcd",2,3)bcfind在字符串中查找string.find("cdcdcdcd","ab")nilstring.find("cdcdcdcd","cd")12string.find("cdcdcdcd","cd",7)78gsub在字符串中替换string.gsub("abcdabcd","a","z");zbcdzbcd2string.gsub("aaaa","a","z",3);zzza3byte返回字符的整数形式string.byte("ABCD",4)68char将整型数字转成字符并连接string.char(97,98,99,100)abcd【基本模式串】字符类描述示例结果.任意字符string.find("",".")nil%s空白符string.find("ab cd","%s%s")34%S非空白符string.find("ab cd","%S%S")12%p标点字符string.find("ab,.cd","%p%p")34%P非标点字符string.find("ab,.cd","%P%P")12%c控制字符string.find("abcd\t\n","%c%c")56%C非控制字符string.find("\t\nabcd","%C%C")34%d数字string.find("abcd12","%d%d")56%D非数字string.find("12abcd","%D%D")34%x十六进制数字string.find("efgh","%x%x")12%X非十六进制数字string.find("efgh","%X%X")34%a字母string.find("AB12","%a%a")12%A非字母string.find("AB12","%A%A")34%l小写字母string.find("ABab","%l%l")34%L大写字母string.find("ABab","%L%L")12%u大写字母string.find("ABab","%u%u")12%U非大写字母string.find("ABab","%U%U")34%w字母和数字string.find("a1()","%w%w")12%W非字母非数字string.find("a1()","%W%W")34--------------------------------------------------------------------------------------------------【转义字符%】字符类描述示例结果%转义字符string.find("abc%..","%%")44string.find("abc..d","%.%.")45--------------------------------------------------------------------------------------------------【用[]创建字符集,"-"为连字符,"^"表示字符集的补集】字符类描述示例结果[01]匹配二进制数string.find("32123","[01]")33 [AB][CD]匹配AC、AD、BC、BD string.find("ABCDEF","[AB][CD]")23 [[]]匹配一对方括号[]string.find("ABC[]D","[[]]")45 [1-3]匹配数字1-3string.find("312","[1-3][1-3][1-3]")13 [b-d]匹配字母b-d string.find("dbc","[b-d][b-d][b-d]")13 [^%s]匹配任意非空字符string.find("a","[^%s]")33 [^%d]匹配任意非数字字符string.find("123a","[^%d]")44 [^%a]匹配任意非字母字符string.find("abc1","[^%a]")44--------------------------------------------------------------------------------------------------【用"()"进行捕获】字符类描述示例结果()捕获字符串string.find("12ab","(%a%a)")34abstring.find("ab12","(%d%d)")3412 --------------------------------------------------------------------------------------------------【模式修饰符】修饰符描述示例结果+表示1个或多个,匹配最多个string.find("aaabbb","(a+b)")14aaabstring.find("cccbbb","(a+b)")nil-表示0个或多个,匹配最少个string.find("zzxyyy","(xy-)")33xstring.find("zzzyyy","(x-y)")44y*表示0个或多个,匹配最多个string.find("mmmnnn","(m*n)")14mmmbstring.find("lllnnn","(m*n)")44n 表示0个或1个string.find("aaabbb","(a?b)")34abstring.find("cccbbb","(a?b)")44b。