Toluapp 類別存取標籤

lua-users home
wiki

從 1.0.7 版開始,tolua++ 包含 2 個新功能,讓您可以在類別(或任何容器,包括名稱空間、模組,甚至主套件)中輕鬆實作 `public`、`protected` 和 `private` 標籤。

物件存取

每個 tolua++ 物件都有 `access` 標記,用於判斷物件在容器內的存取權。容器物件也有稱為 `curr_member_access` 的成員,用於判斷每個子物件在加入該容器時的 `access`。

當 `access` 值為 `nil`、`false` 或 `0` 時,物件即視為公開。其他任何值都表示非公開,而 tolua++ 都不在乎。所有物件的預設存取值為 `nil`,所以這個新功能並不會影響目前的使用者。

parser_hook

parser_hook 是一個在主剖析函式開頭呼叫的空函式,並以待剖析的文字作為參數。可以在自訂 lua 檔案中重新實作這個函式,並使用 `-L` 選項在 tolua++ 中執行。剖析函式通常會在字串開頭搜尋代碼,如果找到任何內容,則傳回不含該代碼的字串(執行與代碼相關的所有操作後)。`parser_hook` 可以安全地傳回 `nil`。

實作存取標籤

這個範例會實作 'parser_hook',以尋找標籤,並將 `curr_member_access` 設為目前的存取權。它也會將 `curr_member_access` 設為私人(根據 `curr_member_access` 的預設值 `nil`)。標籤仍然能在其他容器(模組、名稱空間和主套件)中作用,但預設會是公開。

-- access_hook.lua

local access = {public = 0, protected = 1, private = 2}

function preparse_hook(p)
	-- we need to make all structs 'public' by default
	p.code = string.gsub(p.code, "(struct[^;]*{)", "%1\npublic:\n")
end


function parser_hook(s)

        local container = classContainer.curr -- get the current container
        if not container.curr_member_access and container.classtype == 'class' then
                -- default access for classes is private
                container.curr_member_access = access.private
        end

        -- try labels (public, private, etc)
        do
                local b,e,label = string.find(s, "^%s*(%w*)%s*:[^:]") -- we need to check for [^:], otherwise it would match 'namespace::type'
                if b then

                        -- found a label, get the new access value from the global 'access' table
                        if access[label] then
                                container.curr_member_access = access[label]
                        end -- else ?

                        return strsub(s, e) -- normally we would use 'e+1', but we need to preserve the [^:]
                end
        end

end

用法

$ tolua++ -L access-hook.lua package.pkg


最新異動 · 喜好設定
編輯 · 歷程
上次編輯:2006 年 1 月 26 日 凌晨 1:09 GMT (diff)