• lua基础知识笔记


    一、lua中的数据类型
    1、数值

    a = 1
    b = 1.2
    

    2、字符串

    c = "hello world"
    

    3、布尔

    d = true
    f = false
    

    4、表(Table) = 数组+映射
    4.1、数组

    a = {}
    a[1] = 10
    a[2] = "hello"
    a[3] = true
    
    --or
    
    a = {10, "hello", true}
    

    4.2、映射

    a = {}
    a["hello"] = 1
    a[3] = false
    
    --or
    
    a = {
    	["hello"] = 1,
    	[3] = false
    }
    

    二、函数
    单返回值示例:

    function add(a, b)
    	local c = 1
    	return a + b + c
    end
    

    其中的 c 只在函数内部有效

    多返回值示例:

    function addTwo(a, b)
            c = 1
    	return a + b, a - b
    end
    --调用
    a, b = addTwo(1, 2)
    

    其中的 c 全局有效(应尽量避免这种写法)

    三、表达式
    and、or、not、..用法示例:

    a = true and false
    b = true or false
    c = not true
    d = "a".."b"
    

    四、if语句
    格式为:

    if 表达式 then
    	代码块一
    elseif 表达式 then
    	代码块二
    else
    	代友块三
    end
    

    五、while语句
    格式为:

    while 表达式 do
    	循环体
    end
    

    六、for语句
    1、循环

    for i = 10, 1, -1 do
    	print(i)
    end
    

    2、遍历

    a = {
    	['foo'] = 1,
    	[100] = true
    }
    for k, v in pairs(a) do
    	print(k, v)
    end
    

    其中pairs()为迭代器,类似的还有 ipairs() 迭代器,ipairs()只迭代Table中的数组部分

    七、包(package)
    示例:
    foo.lua文件:

    local class = {}
    
    function class.foo(a, b) 
    	return a + b
    end
    
    return class
    

    调用这个包:

    local c = require("foo")
    print(c.foo(1, 2))
    

    注:这两个文件要在同一目录下

    八、系统库
    1、取对象长度:#t
    2、table系列方法:

    table.insert(t, index)
    table.remove(t, index)
    table.sort
    table.move
    table.pack
    table.uppack
    table.concat
    

    3、字符串格式化:string.format("hi %d", 2)
    4、数值转为字符串:tostring(3.14)
    5、字符串转数值:tonumber("3.14")
    6、删除映射:

    local t = {}
    t.a = 1
    t.b = 2
    --删除t.a用
    t.a = nil
    

    7、判断对象类型:type(t)

  • 相关阅读:
    Notepad++的ftp远程编辑功能
    Scapy脚本执行出现警告WARNING解决办法
    在文本域textarea里添加含换行的字符串
    Python打包成exe工具
    SQL字段数据类型集锦
    解决Python扩展: Unable to find vcvarsall.bat
    解决安装python第三方模块 'mnocygwin'报错的问题
    python安装wmi模块
    ubuntu设置本地软件安装源【DVD版】
    linux下expect安装
  • 原文地址:https://www.cnblogs.com/lurenjiashuo/p/lua-learn-note.html
Copyright © 2020-2023  润新知