2016-09-30 74 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