Forward define a function in Lua?

前端 未结 6 1272
终归单人心
终归单人心 2020-12-17 09:03

How do I call a function that needs to be called from above its creation? I read something about forward declarations, but Google isn\'t being helpful in this case. What is

6条回答
  •  情歌与酒
    2020-12-17 09:48

    If you use OOP you can call any function member prior its "definition".

    local myClass = {}
    local myClass_mt = { __index = myClass }
    
    local function f1 (self)
    
        print("f1")
        self:later() --not yet "delared" local function
    end
    
    local function f2 (self)
    
        print("f2")
        self:later() --not yet "declared" local function   
    end
    --...
    --later in your source declare the "later" function:
    local function later (self)
    
        print("later")   
    end
    
    function myClass.new()    -- constructor
        local this = {}
    
        this = {
            f1 = f1,
            f2 = f2,
            later = later,  --you can access the "later" function through "self"
        }
    
        setmetatable(this, myClass_mt)
    
        return this
    end
    
    local instance = myClass.new()
    
    instance:f1()
    instance:f2()
    

    Program output:

    f1
    later
    f2
    later
    

提交回复
热议问题