【Lua】入门
来源:互联网 发布:udp端口号是多少 编辑:程序博客网 时间:2024/05/15 02:18
Lua的值和类型
Table:
a={}a[1] = 12.4a["hello"] = 20a[12.4] = "aaa"print(a.hello,a[1],a[a[1]])
结果:
20 12.4 aaa
还可以这样定义:
a={ ["name"] = 2, [5] = true,}print(a.name,a[5])
结果:
2 true
注意:
Lua的数组从1开始。a[1]是第一个
函数
1.函数类型值
--传统定义function add( a,b ) return a + bend--函数类型值 定义plus = function ( a,b ) return a + bendap = plusprint(add(1,2),plus(3,4),ap(5,6))
结果:
3 7 11
2.多返回值以及多变量赋值
a,b = 1,2,3b,a = a,bfunction cal( a,b ) return a,b,a*bendprint(cal(a,b))
结果:
2 1 2
表达式
与或非分别对应:
and
or
not字符串拼接
print("Hey".."Boy")
结果HeyBoy
尽量使用local
function f1( ) a = 10endfunction f2( ) b = 100endfunction f3( ) local c = 1000endf1()f2()f3()print(a,b,c)
结果:
10 100 nil
注意:
Lua没有自增所以没a++这种表达式
流程控制
- if语句
function com( a,b ) if a>b then return a elseif a==b then return "equal" else return b endend
- while语句
local i=0while i<10 do print(i) i = i+1end
- for语句
--等价 for i=0,5,1 dofor i=0,5 do print(i)end
结果:
0
1
2
3
4
5
a = { ["small"] = 1, [10] = false, [1] = 20, [2] = 30,}print("pairs")--pairs迭代器:遍历所有for k,v in pairs(a) do print(k,v)endprint("ipairs")--ipairs迭代器:遍历数组部分不遍历映射for k,v in ipairs(a) do print(k,v)end--以上遍历都是随机顺序
结果:
pairs
2 30
small 1
10 false
1 20
ipairs
1 20
2 30
包
文件一:foo.lua
local class={}function class.foo(a,b) return a + bendreturn class
文件二:
--加载foo.lualocal c = require("foo")print(c.foo(1,2))
结果:3
Lua的系统库
- table的方法:
local t={}for i=1,3 do table.insert(t,i)endtable.remove(t,2)for k,v in pairs(t) do print(k,v)end
结果:
1 1
2 3
映射的删除:
local t={}t.a = 1t.b = 2t.a = nilfor k,v in pairs(t) do print(k,v)end
结果:
b 2- 查看数组长度
local t1 = {5,1,3,4}local t2 = {"hello"}print(#t1.."\n"..#t2)
结果:
4
1
- 其他系统库函数
local a = tonumber("3.14")local b = tostring(120)print(a,type(a))print(b,type(b))print(string.format("hi %d",2))
结果:
3.14 number
120 string
hi 2
0 0
- Lua入门
- Lua入门
- Lua入门
- Lua入门
- Lua入门
- Lua入门
- Lua入门
- lua 入门
- Lua入门
- Lua入门
- lua 入门
- lua入门
- 【Lua】入门
- Lua 入门
- Lua入门
- Lua 入门
- Lua入门
- [cocos2dx lua]cocos2dx lua入门
- Go Web编程:http包分析
- ID收费查找(街或方向)
- 2017网易秋招编程题7
- 编码之JSP乱码涉及问题
- 设计模式复习笔记 (1) 设计模式概述
- 【Lua】入门
- python 学习笔记(2) 条件语句与循环语句
- 1613-3-傅溥衍 总结《2016年10月3日》【连续第三天总结】
- C - 数据结构 - 线性表 - 链式实现
- |洛谷|模拟|P1203 [USACO1.1]坏掉的项链Broken Necklace
- 欢迎使用CSDN-markdown编辑器
- 1055. The World's Richest (25)
- OpenLayers+Geoserver 简单入坑
- codeforces 722C. Destroying Array map+multiset