【问题标题】:Can't set the data to a comboBox choice无法将数据设置为组合框选项
【发布时间】:2021-05-04 22:15:24
【问题描述】:

这几天我一直在尝试创建一个包含所有可用模型的组合框。 代码是这样的

for name , models in SortedPairs( player_manager.AllValidModels() ) do
   print("name: "..name.." model: "..models)
   custCbox:AddChoice(name , models , false)
end

我尝试打印每个名称和模型以了解我是否错了,但这没关系:name 打印显示名称,models 打印路径。 OnSelect 函数是这样的:

custCbox.OnSelect = function( index, value, data )
   modelPanel:SetModel( data )
   print("Data " .. data)
   print("Value " .. value)
end

Data 给出显示名称,value 给出一个数字。 为什么?

【问题讨论】:

    标签: lua garrys-mod


    【解决方案1】:

    来自DComboBox documentation:

    local cbox = vgui.Create( "DComboBox", BGPanel )
    

    ...

    cbox:AddChoice( "Pink", Color( 255, 0, 255 ) )
    
    function cbox:OnSelect( index, text, data )
    
        -- Set background panel color
        BGPanel:SetBackgroundColor( data )
    
    end
    

    注意与您的区别

    custCbox.OnSelect = function( index, value, data )
       modelPanel:SetModel( data )
       print("Data " .. data)
       print("Value " .. value)
    end
    

    相当于

    function custCbox.onSelect(index, value, data)
    -- ...
    end
    

    以及使用冒号语法的示例。

    function cbox:OnSelect(index, text, data)
    end
    

    等价于

    function cbox.OnSelect(self, index, text, data)
    end
    

    这种差异会导致参数偏移 1。所以你认为index 实际上是你的组合框,text 是选定的索引,data 是选择文本。

    请阅读

    Lua 5.4 Reference Manual: 3.4.10 Function Calls

    Lua 5.4 Reference Manual: 3.4.11 Function Definitions

    这是初学者中很常见的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-05
      • 2011-06-24
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 2018-09-12
      相关资源
      最近更新 更多