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