2016-09-30 71 views
2

我有一個特殊用戶和普通用戶的列表。特殊用戶有自己特殊的功能,而普通用戶使用標準功能。lua中的內部函數性能

我想出了這個代碼設計,但我覺得這不是最佳的(性能明智)。

所以我的問題是:如何在調用如下例所示的內部函數時獲得最佳性能?

if something then 
    CallFunc(var) 
end 

特殊/正常用戶邏輯

function CallFunc(var) 
    if table[name] then 
    table[name](var) 
    else 
    Standard_Func(var) 
    end 
end 

local table = { 
["name1"] = function(var) Spec_Func1(var) end, 
["name2"] = function(var) Spec_Func2(var) end, 
["name3"] = function(var) Spec_Func3(var) end, 
... 
--40 more different names and different funcs 
} 

特殊用戶funcs中

function Spec_Func1(var) 
--lots of code 
end 

function Spec_Func2(var) 
--lots of code 
end 
... 
--more funcs 

編輯: 看到@ hjpotter92的回答是:

我不能在表中查找用戶。

local function_lookups = { 
    name1 = Spec_Func1, --this doesnt let me find the user 
    --name1 = 1 --this does let me find the user (test) 
} 

if function_lookups[name] then --this fails to find the user 
    --do something 
end 
+0

大概'Spec_Func1'是在查找表之後定義的? – hjpotter92

+0

facepalm .......... –

+0

特殊用戶是否都提到相同的功能?普通用戶是否都被稱爲相同的功能?這些功能是否在同一行動中被調用?如果這些條件成立,你的工作變得更容易。 – warspyking

回答

1

您不需要另一個匿名函數。只需使用查找表如下:

local function_lookups = { 
    name1 = Spec_Func1, 
    name2 = Spec_Func2, 
    name3 = Spec_Func3, 
    ... 
    --40 more different names and different funcs 
} 

不要使用變量名table。這是Lua本身的library available,你正在覆蓋它。

+0

看我的編輯。爲什麼不能找到解決方案的用戶? –

0

根本不需要特殊功能!您可以使用行爲取決於調用者的通用函數!讓我和一段代碼解釋:

local Special = {Peter=function(caller)end} --Put the special users' functions in here 
function Action(caller) 
    if Special[caller] then 
     Special[caller](caller) 
    else 
     print("Normal Action!") 
    end 
end 

所以每當一個用戶做了一定的作用,可以觸發此功能,並通過呼叫方的說法,該函數然後做幕後決定背後的工作,如果來電者是特殊,如果是的話該怎麼辦。

這使得你的代碼乾淨。它還使添加2個以上用戶狀態變得更加容易!

+0

這看起來像一個不錯的解決方案,但如果我想根據調用者是否特殊(例如action =「SpecialFunc _」.. caller)從字符串動態創建特殊操作funcNames。名稱),這將需要我在全局名稱空間中調用該函數,如:_G [action](),這不是性能友好的。所以最後我仍然需要一個包含所有特殊func名稱的表,或者將所有邏輯放在代碼塊中(例如,如果caller.name ==「Peter」,那麼specialFunc_Peter()end ..etc)。 –

+0

@richard更新,但我覺得有一個更優雅的解決方案。普通用戶和每個特殊用戶的狀態有什麼不同? – warspyking