tags: programming-language
lua
コメント
-- comment
--[[
multiple line comment
ok.
]]
変数
-- num
x = 10
x = 1.0
x = 10e-1
-- string
s = "AAA"
s = 'AAA\n'
-- function
function square(x)
return x * x
end
-- table
t = {}
-- boolean
b = true
b = false
テーブル
t = {}
t["str"] = "string"
t["boolean"] = false
t["number"] = 1
-- number is accepted as index
-- index should start from 1, lua expects that beginning of index is 1.
t[1] = "one"
t[2] = true
t[3] = 3
t = {}
t["1"] = "one"
t["2"] = "two"
t["3"] = "three"
for i, val in pairs(t) do
print(i, val)
end
t[1] = "one"
t[2] = "two"
t[3] = "three"
for i, val in ipairs(t) do
print(i, val)
end
-- math
1 + 3
1 - 3
1 * 2
1 / 13
1 ^ 0
1 % 2
-- cmp
1 < 2
1 > 4
1 <= 2
1 >= 1
1 == 1
1 ~= 1 -- not equal
-- logical
true and true
true or false
not false
-- string
"str1" .. "str2" -- "str1str2"
if
a = 3
b = 2
if a > b then
print("a")
end
if a > b then
print("a")
elseif a == b then
print("ab")
else
print("b")
end
for
for i = 0, 4, 1 do
print(i)
end
a = 0
b = 4
while a <= b do
print(a)
a = a + 1
end
a = 0
b = 5
repeat
print(a)
a = a + 1
until a == b
while true do
break
end
while true do
do
break
end
a = 10
end
関数
function funcname (arg)
return arg + 1
end
function returnmultival(arg1, arg2)
return arg1, arg2
end
a, b = returnmultival(1, 2)
-- extendable arg
function func(...)
t = {...}
end
-- lambda
f = function(args)
return args
end
f(3)
コルーチン(co-routine)
function col(a, b, c)
sum = 0
sum = sum + a
coroutine.yield(sum)
sum = sum + b
coroutine.yield(sum)
sum = sum + c
return sum
end
local co = ccoroutine.wrap(col)
ret = co(3, 2, 1) -- return a ?
ret = co(3, 2, 1) -- return a + b
ret = co(3, 2, 1) -- return a + b + c