Lua 语言基础示例

Eddy 发布于2019-5-15 9:49:55 分类: 技术心得 已浏览loading 网友评论0条 我要评论

Lua是一个强大的、高效的、轻量级的、嵌入式的动态脚本语言。它支持面向过程编程、面向对象编程、函数式编程、数据驱动编程。

--[[
    变量定义
    lua 中有全局变量、局部变量之分,默认为全局变量,局部变量用 local 关键词定义
    变量申明、初始化可同时也可分开进行,未初始化的变量值为 nil
    lua 中有以下变量类型
    string
    number
    boolean
    function
    thread
    userdata
    table
    nil
]]
local a, b = "hello", "world"
--[[ 不等于操作符 ~= --]]
print(a ~= b)
--[[ 字符串连接 .. --]]
print(a..b)
--[[ length of string or table # --]]
print(#a)

--[[ 三种循环控制结构 --]]
local k = 10
while (k < 100)
do
    print(k)
    k = k + 1
end

for i = 10, 100, 5
do
    print(i)
end

local j = 1
repeat
    print(j)
    j = j * 2
until (j > 1000)

--[[判断控制结构--]]
local m = true
if (m == true)
then
    print("yes")
else
    print("no")
end

--[[函数定义和调用--]]
function max(a, b)
    if (a > b)
    then
        return a
    else
        return b
    end
end
print(max(1, 3))

--[[字符串变量3种形式--]]
string1 = "Lua"
print("String 1 is", string1)

string2 = 'Tutorial'
print("String 2 is", string2)

string3 = [["Lua Tutorial"]]
print("String 3 is", string3)

--[[ 数组。默认索引从1开始 ]]
arr1 = {"php", "java"}
--[[ 输出 nil php ]]
print(arr1[0], arr1[1])

--[[ 迭代器 ipairs ]]
array = {"Lua", "Tutorial"}

for key,value in ipairs(array)
do
   print(key, value)
end

--[[
    lua 协程 resume 恢复协程(从上次暂停处继续运行) yield 暂停协程
    输出结果:
    coroutine section 1	3	2	10
    main	true	4	3
    coroutine section 2	12	nil	13
    main	true	5	1
    coroutine section 3	5	6	16
    main	true	2	end
    main	false	cannot resume dead coroutine
]]
co = coroutine.create(function (value1,value2)
    local tempvar3 = 10
    print("coroutine section 1", value1, value2, tempvar3)

    local tempvar1 = coroutine.yield(value1+1,value2+1)
    tempvar3 = tempvar3 + value1
    print("coroutine section 2",tempvar1 ,tempvar2, tempvar3)

    local tempvar1, tempvar2= coroutine.yield(value1+value2, value1-value2)
    tempvar3 = tempvar3 + value1
    print("coroutine section 3",tempvar1,tempvar2, tempvar3)
    return value2, "end"

end)

print("main", coroutine.resume(co, 3, 2))
print("main", coroutine.resume(co, 12,14))
print("main", coroutine.resume(co, 5, 6))
print("main", coroutine.resume(co, 10, 20))


--[[
    错误处理 pcall and xpcall
    pcall 调用函数,出错不抛出错误,只返回错误
    xpcall 调用函数,出错不抛出错误,会调用自定义的错误处理函数
]]
local function add(a,b)
   assert(type(a) == "number", "a is not a number")
   assert(type(b) == "number", "b is not a number")
   return a+b
end

add(10)

function myfunction()
   n = n/nil
end

function myerrorhandler(err)
   print("ERROR:", err)
end

status = xpcall(myfunction, myerrorhandler)
print(status)

已经有(0)位网友发表了评论,你也评一评吧!
原创文章如转载,请注明:转载自Eddy Blog
原文地址:http://www.rrgod.com/technique/916.html     欢迎订阅Eddy Blog

关于 Lua  的相关文章

记住我的信息,下次不用再输入 欢迎给Eddy Blog留言