Lua 获取附加函数的表

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

function DrawRect()
    print(debug.getinfo(1).name) -- 这获取了调用 DrawRect ('Paint') 的函数的名称..
    -- 我想能够获取附加到此函数的表
    -- 这样我就可以在函数内部使用 table.x,并打印出 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) -- 请注意位置相对于按钮的位置
        self.label:SetColor(255,255,255)
    end,


    Paint = function(self,x,y,w,h)
        Color(40,40,40)
        DrawRect(x,y,w,h) -- 画黑色背景
    end
}

正如你所看到的,paint有四个参数,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) -- 请注意位置相对于按钮的位置
        self.label:SetColor(255,255,255)
    end,


    Paint = function(self,w,h)
        Color(40,40,40)
        DrawRect(0,0,w,h) -- 画黑色背景
    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
点赞
用户3574628
用户3574628

翻译结果:

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

2021-05-06 12:44:26
用户2858170
用户2858170

这不是你应该实现类似这样的东西的方式。你不应该实现一个函数,通过一些魔法获取其调用者的容器,以便访问其它值。

DrawRect 应该只是画一个矩形。如果你想在其他地方画一个矩形,你应该通过参数提供偏移量给 DrawRect

我修改了你的按钮,所以它只会把它的 xy 坐标(如果存在)放入 DrawRect

local Button = {
    Init = function(self)
        self.label = gui.Label("Button")
        self.label:SetPos(10, 5) -- 见位置是相对于按钮的位置
        self.label:SetColor(255,255,255)
    end,

    Paint = function(self,w,h)
        Color(40,40,40)
        local x = self.x or 0
        local y = self.y or 0
        DrawRect(x,y,w,h) -- 画暗背景
    end
}

这样你就可以调用 Button:Paint(20,30) 在按钮的坐标处画一个 20 x 30 的矩形。如果你想添加一个偏移量,在 DrawRect 之外添加即可。

@ Edit 2:

这是一个不同的东西。主程序将调用 Paint 函数。

vgui.Create( "DPanel" ) 将返回一个新的面板实例,游戏将把一个引用添加到列表中。每次GUI更新时,它将调用该列表中所有面板的 Paint 函数。这就是函数如何知道面板的宽度和高度。

2021-05-07 12:53:17