Lua覆盖包含文件

时间:2018-05-16 09:52:55

标签: class lua include override

对不起,我是LUA脚本的新手,我必须处理其他人编写的代码。 请不要关注代码,我的问题只是关于包含文件和优先级评估必须调用哪个函数,以防覆盖。

假设我有一个Terrain.lua文件,其中包含一个类Terrain,它有一个函数Terrain:generate()和Terrain:generate()调用Terrain:getLatitude()。

Terrain包含在脚本MyScript.lua中,它覆盖了Terrain:getLatitude(),如下所示:

include("Terrain");

    function Terrain:getLatitude()
       new code;
    end

    function myFunction()   
        local myTerrain = Terrain.create();
        myTerrain.generate();
    end

这具有覆盖getLatitude()的效果:当调用myTerrain.generate()时,generate()是包含“Terrain”的代码, getLatitude()是带有新代码的本地函数,即使是由包含的类中的函数调用。

现在假设我想将一些代码放在外部文件Custom.lua中。自定义(而不是MyScript)必须覆盖getLatitude()。 情况就是这样:

Terrain.lua包含Terrain类和这些函数

Terrain.create()
Terrain.generate()
Terrain.getLatitude()

MyScript.lua是正在执行的脚本,包括Custom:

include("Custom");

        function myFunction()   
            return customFunction()
        end

Custom.lua包含:

include("Terrain");

    function Terrain:getLatitude()
       new code;
    end

    function customFunction()   
        local myTerrain = Terrain.create();
        myTerrain.generate();
    end

现在,如果我从MyScript调用customFunction(),则使用来自Terrain的getLatitude(),而不是来自Custom的getLatitude()。我假设ovveride只能在正在执行的currenti文件中?如何在包含文件中实现覆盖?

我希望这个例子足以理解我的问题,而不需要发布大量代码。谢谢。

1 个答案:

答案 0 :(得分:0)

首先,一些更正:你的问题中没有local function; include不属于任何lua标准,功能实际上可能非常重要。

最后,Lua没有实际的类系统,你在问题中使用的只是一个语法糖(在我发现它时误导和混淆)而不是表分配。 Lua是一种解释型语言,所以你看来作为一个类定义,不是从程序执行的最初阶段就知道的静态结构,而是从文件顶部到底部执行的代码。

因此,如果我们假设includerequire类似,那么您的问题代码将等同于以下内容:

do--terrain.lua
 Terrain = {
    create=function() 
        local created_object
        --some code to assign value to created_object
        return created_object
    end
 }

 Terrain.generate = function(self) end

 Terrain.getLatitude = function(this_is_a_self_too) 
    --some code that uses `also_self` as a reference to the object when called as object:generate()
 end

 --do end block is essentially an equivalent of file, its local variables are not seen outside
 --global variables it has assigned (like `terrain`) will stay accessible AFTER its end
 --changes it done to global variables will also remain
end

do--Custom.lua
    Terrain.getLatitude = function(this)--this is the assignment to a field in a table stored in the global variable Terrain
       --this function will replace the one assigned to the `getLatitude` field
    end

    customFunction = function()   
        local myTerrain = Terrain.create();
        myTerrain.generate();--this one probably needs `:` instead of `.`  
        --depends on actual code inside terrain.lua
    end
end

do--MyScript.lua
    myFunction= function()   
        return customFunction() --this line calls the global variable customFunction
    end
end

因此,如果您的实际设置与相关设置相似,则“覆盖”将在执行Custom.lua后生效,并且对Terrain.getLatitude的所有后续调用生效,无论它们是否有效我打电话给文件。 (以后任何文件都可以再次覆盖它,之后的所有调用都将使用新的文件)

在此设置中执行有限覆盖可能更复杂。这又取决于团队如何定义Terrain类和类系统本身的实际细节。

相关问题