文章目录
  1. 1. type
    1. 1.1. table
      1. 1.1.1. setmetatable
      2. 1.1.2. __index與__newindex
      3. 1.1.3. __tostring
      4. 1.1.4. operator
    2. 1.2. function
  2. 2. wheel

關於Lua的官方定義

Lua is a powerful, fast, lightweight, embeddable scripting language.
Lua combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting bytecode for a register-based virtual machine, and has automatic memory management with incremental garbage collection, making it ideal for configuration, scripting, and rapid prototyping.

別的我就不多安利了

type

table

table是類似class的hash_map,由data和method兩部分組成。簡而言之,數據和行爲是分離的,後者在Lua中稱爲metatable。
metatable有很多特有的鍵,在此我們粗暴的認爲特有鍵類似c++中的操作符,它們的值一般爲function或table。

setmetatable

我們可以通過setmetatable來賦予table不同的動作。

1
2
3
4
t = {}              -- 普通的table
mt = {} -- metatable
setmetatable(t, mt) -- 设定mt为t的metatable
getmetatable(t) -- 返回mt

以上代碼可以縮略爲:

1
t = setmetatable({}, {})

__index與__newindex

1
2
3
4
5
6
7
8
other = {}
t = setmetatable({}, { __newindex = other })
t.foo = 3
t.foo -- nil
other.foo -- 3
t = setmetatable({}, { __index = other })
t.foo -- 3
other.foo -- 3
  • __index類似於[]操作符
  • __newindex類似於[]=操作符
1
2
3
4
5
6
7
8
9
10
11
12
13
14
t = setmetatable({}, {
__newindex = function(t, key, value)
if type(value) == "number" then
rawset(t, key, value * value)
else
rawset(t, key, value)
end
end
})

t.foo = "foo"
t.foo -- "foo"
t.bar = 4
t.bar -- 16
  • rawgetrawset可以避免調用重載後的操作符(__index和__newindex)

__tostring

1
2
3
4
5
6
7
8
9
t = setmetatable({ 1, 2, 3 }, {
__tostring = function(t)
sum = 0
for _, v in pairs(t) do sum = sum + v end
return "Sum: " .. sum
end
})

print(t) -- prints out "Sum: 6"

operator

運算符只能是函數

  • __add
  • __sub
  • __mul
  • __div
  • __mod
  • __unm
  • __concat
  • __eq
  • __lt
  • __le

function

一個機智的計數器

1
2
3
4
5
6
7
8
9
10
11
12
function InitCounter()
local i = 0
return function()
i = i + 1
return i
end
end
newCounter1 = InitCounter()
print(newCounter1()) -- 1
print(newCounter1()) -- 2
newCounter2 = InitCounter()
print(newCounter2()) -- 1

wheel

德堪邀請我入坑,考慮了一下還是可行的。
現在手頭還沒拿到項目,所以自己造輪子玩。

文章目录
  1. 1. type
    1. 1.1. table
      1. 1.1.1. setmetatable
      2. 1.1.2. __index與__newindex
      3. 1.1.3. __tostring
      4. 1.1.4. operator
    2. 1.2. function
  2. 2. wheel