2018年9月30日 星期日

Lua 5.1 __gc

__gc

lua 5.2 開始有 __gc 這個元函數可以知道什麼時候被釋放掉
當 table 被回收時會呼叫這個函數
我們可以在這個函數中處理資源釋放等操作
不過 lua 5.1 中對於 table 并不支援,我們先看一下在 lua 5.2 中
這個 __gc 怎麼使用

-- lua 5.2

local teseTtable = {

name = "test table"

};

local mt = {

__gc = function(tb)

print("gc execute! name => ", tb.name);

end

};

local newTable = setmetatable(teseTtable, mt);

collectgarbage("collect");

上面測試代碼的結果為:

gc execute! name => test table

lua 5.1 如何使用 __gc

[官方文件][id]明確的指出 The __gc metamethod is not called for tables.
__gc 是 UserData 結構的時候會呼叫的
因此我們可以利用這個條件來觸發 __gc 函數
程式碼為:

-- lua 5.1

-- 拿上面的變數來使用

local teseTtable = {

name = "test table"

};

local mt = {

__gc = function(tb)

print("gc execute! name => ", tb.name);

end

};

local function setMetatableByProxy(ourTable, mt)

-- 建立代理,這個 newProxy 就是一個 UserData

local proxy = newproxy(true);

-- 我們利用 UserData 的 metadata 來註冊

getmetatable(proxy).__gc = function()

mt.__gc(ourTable);

end

end

-- 開始測試

setMetatableByProxy(teseTtable, mt);

collectgarbage("collect");

上面測試代碼的結果為:

-- lua 5.1

gc execute! name => test table

沒有留言:

張貼留言

Lua 5.1 __gc

__gc lua 5.2 開始有 __gc 這個元函數可以知道什麼時候被釋放掉 當 table 被回收時會呼叫這個函數 我們可以在這個函數中處理資源釋放等操作 不過 lua 5.1 中對於 table 并不支援,我們先看一下在 lua 5.2 中 這個 __gc 怎...