zoukankan      html  css  js  c++  java
  • lua——基础语法

    -- test lua: for learning lua grammar
    
    -- line comment
    --[[
    	block comment
    ]]--
    
    -- print hello world
    print('Hello World
    ')
    
    -- control structure
    -- if
    if 1+1 == 2 then print('1+1=2') end
    if 1+1 == 2 then
    	print('1+1=2')
    elseif 1+1 == 3  then
    	print('1+1=3')
    else
    	print('1+1=?')
    end
    
    -- while
    local n = 2
    while n > 0 do
    	print('while ' .. n)
    	n = n - 1
    end
    
    -- repeat
    n = 2
    repeat
    	print('repeat ' .. n)
    	n = n - 1
    until n <= 0
    
    -- for
    for i = 1, 2, 1 do
    	print('for ' .. i)
    end
    
    -- for array
    arr = {1, 2}
    for i, v in ipairs(arr) do
    	print('arr ' .. i .. ' ' .. v)
    end
    
    -- for table
    t = {
    	name = 'adfan',
    	age = 20,
    	[2] = 30,
    }
    for k, v in pairs(t) do
    	print('table ' .. k .. ' = ' .. v)
    end
    
    -- assign
    a, b, c, d = 1, 2, 3, 4
    print(a, b, c, d)
    -- exchange a, b
    a, b = b, a
    print(a, b)
    
    -- math
    print(2 ^ 4)	-- 2 power 4 = 16
    
    -- compare
    print(1 ~= 2)	-- not equal
    
    -- logic
    --[[
    	Note: only false or nil are false, others are true (0 is alse true!)
    		a and b: if a is false, return a; else return b (return the first false)
    		a or b: if a is true, return a; else return b (return the first true)
    ]]--
    print(true and 5)		-- 5
    print(false and true)	-- false
    print(true and 5 and 1)	-- 1
    
    print(false or 0)		-- 0
    print(nil or 1)			-- 1
    
    print(not nil)			-- true
    print(not 0)			-- false: as 0 is true
    
    a, b, c = 1, nil, 3
    x = a and b or c		-- not means a ?

    b : c, as when b is false, x equals c.. print(x) x = x or a -- means if not x then x = v end print(x) -- opr inc order: --[[ or and < > <= >= ~= == ..(string plus) + - * / % not #(get length) - ^ ]]-- -- var type print('type nil ' .. type(nil)) print('type true ' .. type(true)) print('type 1 ' .. type(1)) print('type str ' .. type('adfan')) print('type table ' .. type({1, 2, 3})) print('type function ' .. type(function () end)) -- user data -- local means local var, without local means global var -- table t = { 10, -- means [1] = 10 [100] = 40, John = { age = 27, gender = male, }, 20 -- means [2] = 20 } -- function function add(a, b) return a + b end function sum(a, b, ...) c, d = ... print(...) print(a, b, c, d) return 14, 13, 12, 11 end a, b, c, d = sum(1, 2, 3, 4) print(a, b, c, d)


  • 相关阅读:
    svn的revert、checkout、clean up、setting
    jsonp跨域原理
    王亚伟北大演讲:一切通胀问题都是货币问题(全文)
    string <-> wstring
    点在多边形内 经典算法(转)
    不可不表的OSG智能指针之强指针与弱指针 《转载》
    一个shell脚本给客户使用服务器生成一个序列号
    Rsync(远程同步): linux中Rsync命令的实际示例
    一个 rsync同步文件脚本
    用UltraISO制作CentOS U盘安装盘
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6789313.html
Copyright © 2011-2022 走看看