lua——基础语法

-- test lua: for learning lua grammar

-- line comment
--[[
	block comment
]]--

-- print hello world
print('Hello World\n')

-- 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)


转载于:https://www.cnblogs.com/mfmdaoyou/p/6789313.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值