首页 > 解决方案 > Lua获取该函数附加到的表

问题描述

你好我想得到一个函数所附加的表,我真的找不到一个很好的方法来解释它,但我认为我已经在代码中很好地解释了它。基本上我需要从另一个函数中获取该函数附加到的表,而无需传入该表。

function DrawRect()
    print(debug.getinfo(1).name) -- this gets the name of the function that is invoking DrawRect ('Paint')..
    -- I want to be able to get the table that is attached to this function
    -- So I can do table.x inside this function, and have it print 123
end

local r =  math.random(1, 100)
_G["abc" .. r] = {
    x = 123,
    Paint = function(self)
        DrawRect()
    end
}

_G["abc" .. r]:Paint()

我要解决的问题示例

这是我现在的当前代码

function DrawRect(x,y,w,h)
    draw.DrawRect(x,y,w,h)
end

local Button = {
    Init = function(self)
        self.label = gui.Label("Button")
        self.label:SetPos(10, 5) -- see the position is relative to the Button's position
        self.label:SetColor(255,255,255)
    end,
    
    
    Paint = function(self,x,y,w,h)
        Color(40,40,40)
        DrawRect(x,y,w,h) -- Draws dark background
    end
}

如您所见,paint 有 4 个参数,x,y,w,h。我想取消 x,y 并且只有 w,h。我想像这样实现这一目标。

function DrawRect(x,y,w,h)
    local relative_x = parent_table_of_paint.INTERNAL.draw_x
    local relative_y = parent_table_of_paint.INTERNAL.draw_y

    draw.DrawRect(relative_x + x, relative_y + y,w,h)
end

local Button = {
    Init = function(self)
        self.label = gui.Label("Button")
        self.label:SetPos(10, 5) -- see the position is relative to the Button's position
        self.label:SetColor(255,255,255)
    end,
    
    
    Paint = function(self,w,h)
        Color(40,40,40)
        DrawRect(0,0,w,h) -- Draws dark background
    end
}

我知道您在我的示例中看不到某些属性,但它们确实存在。

编辑2:

我正在重新创建一个框架,“VGUI”。 https://wiki.facepunch.com/gmod/draw.RoundedBox draw.RoundedBox( number cornerRadius, number x, number y, number width, number height, table color )

如您所见,它具有我想要的功能 https://wiki.facepunch.com/gmod/PANEL:Paint

local panel = vgui.Create( "DPanel" )
panel:SetSize( 100, 100 )
panel:SetPos( ScrW() / 2 - 50, ScrH() / 2 - 50 )

function panel:Paint( w, h )
    draw.RoundedBox( 8, 0, 0, w, h, Color( 0, 0, 0 ) )
end

标签: lua

解决方案


函数是第一类值,因此可能有许多表和变量引用同一个函数。该函数无法知道这些表和变量是什么。


推荐阅读