lua - 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
解决方案
函数是第一类值,因此可能有许多表和变量引用同一个函数。该函数无法知道这些表和变量是什么。
推荐阅读
- php - 基于php中的点击生成热图颜色
- javascript - 为某事修改程序然后将其改回
- wordpress - Htaccess url 映射到同一域根目录的子文件夹
- laravel - 如何暂时关闭 laravel 垃圾过滤器?
- android - 未在异步函数中调用 Kotlin 回调
- angular - Angular:如何获取 Google 访问令牌
- javascript - 设置从 axios 到 state 的响应
- excel - VBA - 避免循环
- r - 我们如何在 R 中添加两个具有不同行和列的矩阵?
- typescript - ts-loader:从其他 Yarn 工作区导入 .ts 模块