【Lua】Lua_Basics
Lua 基础
内容来自 https://learnxinyminutes.com/lua/, 包含部分自己的思考
自用,如果能帮到你,那太好不过了
-- 两个 - 做单行注释 --[[ 这个是奇怪的多行注释 --]] ---------------------------------------------------- -- 1. 变量和控制流 ---------------------------------------------------- --[1.1 数字] num = 123 -- 数字可以是 int 或 float --[1.2 字符串] s = 'this is a test' -- 不可改变的字符串 local s1 = "hello" local s2 = s1 -- s2 现在指向与 s1 相同的内存地址 print("原始地址:", s1) --> hello print("原始地址:", s2) --> hello -- 尝试修改 s1 s1 = s1 .. " world" -- 这里会创建新字符串 print("修改后 s1:", s1) --> hello world print("修改后 s2:", s2) --> hello(仍然保持原值) -- 测试内存地址是否相同 print(s1 == s2) --> false --[1.2.1 字符串在内存中存储为不可变对象] s1[0] = "H" -- lua: main.lua:16: attempt to index a string value (local 's1') -- 1. 字符串在内存中存储为不可变对象 -- 2. 通过索引直接赋值会触发错误 -- 3. 修改字符串的正确方式是创建新字符串: --[1.2.2 字符串可以可使用单引号,也可使用双引号] test1 = "test1" test2 = 'test2' --[1.2.3 多行字符串] test3 = [[ test3 test4 test4 ]] --[1.3 nil] t = nil; -- 定义 `t` --[1.4 域/scope 和操作符] while true do num = num + 1 -- 没有 num++ 或 num--, 或者 += 操作符 end --[1.5 if else] local num = 10 if num > 20 then print("num is greater than 20") elseif num ~= s1 then io.write("num is not ", s1, "\n") else thisIsGlobal = 5; -- 变量默认是全局变量 end --[1.6 局部变量和全局变量] -- 变量默认是全局变量, 使用 local 关键字修饰局部变量 local line = io.read() --[1.7 字符串连接使用 `..` = 操作符 ] s3 = "12" s3 = "12".."3456789" --[1.8 nil AKA null ] foo = anUnknownVariable --[1.9 布尔 false] aBooleanFalse = false anotherBooleanFalse = nil print(" false ----------") print(aBooleanFalse) if anotherBooleanFalse then print(" nil means is true") else print(" nil means is false") end --[1.10 布尔 true] aBooleanTrue = true anotherBooleanTrue = 0 anotherBooleanTrue2 = "" print(" true ----------") print(aBooleanTrue) if anotherBooleanTrue then print(" 0 means is true") end if anotherBooleanTrue2 then print(" Empty string is true") end --[1.11 非 ] if not false then print("it was false") end --[1.12 三目表达式 ] ans = true ans = true and "yes" or "no" --> 'no' print(ans) --[1.13 与 ] if true and not false then print(" true and not false is `true` ") end --[1.14 或 ] if true or false then print(" true or false is `true` ") end --[1.15 循环 ] --[[
C
KarSum =0; for(int i = 1; i <=100; i++) { KarSum+=i; } –]]
– 包含 1 和 100 KarSum = 0 for i = 1, 100 do KarSum = KarSum + i end
print(KarSum)
–[1.16 步长 循环 ] – 在 Lua 的数值 for 循环中,语法结构是固定的三参数形式: for variable = start, end, step do – 循环体 end
– Use “100, 1, -1” as the range to count down: fredSum = 0 for j = 10, 1, -1 do – fredSum = fredSum + j print(j) end
– j 在这里是循环变量名(可任意命名) – 10 是起始值 – 1 是终止条件 – -1 是步长(step)
– Another loop construct: repeat print(‘the way of the future’) num = num - 1 until num == 0
– 2. 函数
–[2.1 函数定义和调用] local function fib(n) if n < 2 then return 1 end return fib(n - 2) + fib(n - 1) end
local fibNumb = fib(10)
print(“fibNumb is “, fibNumb)
–[2.2 函数定义和调用] function createCounter() local count = 0 return function() count = count + 1 – 捕获外部变量 count return count end end
local counter = createCounter() print(counter()) –> 1 print(counter()) –> 2
x, y, z = 1, 2, 3, 4 – Now x = 1, y = 2, z = 3, and 4 is thrown away.
x, y = bar(‘zaphod’) –> prints “zaphod nil nil” – Now x = 4, y = 8, values 15…42 are discarded.
– And so are these: local function g(x) return math.sin(x) end
print(g(0))
– 3. Table 表
– Tables = Lua’s only compound data structure; – they are associative arrays. – Similar to php arrays or js objects, they are – hash-lookup dicts that can also be used as lists.
– Using tables as dictionaries / maps:
– Dict literals have string keys by default: t = { key1 = “value1”, key2 = false } print(t.key1) print(t.key2)
t.key2 = nil – Removes key2 from the table. print(t.newKey) print(t.key2)
– Adding a new key-value pair t.newKey = “newValue” – Using dot notation t[“anotherKey”] = 123 – Using bracket notation
print(t.newKey) –> newValue print(t.anotherKey) –> 123
– Literal notation for any (non-nil) value as key: u = {[‘@!#’] = ‘qbert’, [{}] = 1729, [6.28] = ‘tau’} print(u[6.28]) – prints “tau”
– Key matching is basically by value for numbers – and strings, but by identity for tables. a = u[‘@!#’] – Now a = ‘qbert’. b = u[{}] – We might expect 1729, but it’s nil: – b = nil since the lookup fails. It fails – because the key we used is not the same object – as the one used to store the original value. So – strings & numbers are more portable keys.
– A one-table-param function call needs no parens: function h(x) print(x.key1) end h{key1 = ‘Sonmi~451’} – Prints ‘Sonmi~451’.
for key, val in pairs(u) do – Table iteration. print(key, val) end
– _G is a special table of all globals. print(_G[’_G’] == _G) – Prints ‘true’.
– Using tables as lists / arrays:
– List literals implicitly set up int keys: v = {‘value1’, ‘value2’, 1.21, ‘gigawatts’} for i = 1, #v do – #v is the size of v for lists. print(v[i]) – Indices start at 1 !! SO CRAZY! table 作为 list 使用, 索引从 1 开始,疯了 end
– A ‘list’ is not a real type. v is just a table – with consecutive integer keys, treated as a list.
– 3.1 Metatables and metamethods.
– A table can have a metatable that gives the table – operator-overloadish behavior. Later we’ll see – how metatables support js-prototype behavior.
f1 = {a = 1, b = 2} – Represents the fraction a/b. f2 = {a = 2, b = 3}
– This would fail: – s = f1 + f2 metafraction = {} function metafraction.__add(f1, f2) sum = {} sum.b = f1.b * f2.b sum.a = f1.a * f2.b + f2.a * f1.b return sum end
setmetatable(f1, metafraction) setmetatable(f2, metafraction)
s = f1 + f2 – call __add(f1, f2) on f1’s metatable
```