You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua代码报错:尝试索引全局变量'INV'(nil值)求助

修复Garry's Mod Lua中INV全局表未定义的错误

错误原因

第23行报错是因为全局表INV在使用前没有被初始化,Lua默认会把未定义的全局变量视为nil,当你尝试给INV.Open赋值时,就是在索引nil值,自然触发错误。

修复步骤

  1. 初始化INV全局表
    在代码最开头(或者定义INV.Open函数之前的任意位置),添加一行代码创建空表:
INV = INV or {}  -- 确保INV是一个表,避免nil错误

这行代码的作用是:如果INV已经存在就用原来的,不存在就创建新的空表,兼容后续可能的扩展。

  1. 完善物品面板的显示(可选但必要)
    原代码中创建的itemPanel没有设置高度和内容,运行后看不到任何物品。可以给每个物品面板添加高度和显示文本:
for k,v in pairs(plyinv) do
    local itemPanel = scroll:Add("DPanel")
    itemPanel:Dock(TOP)
    itemPanel:SetTall(60)  -- 设置面板高度
    itemPanel:DockMargin(5,5,5,0)  -- 增加间距

    -- 添加物品名称显示
    local itemLabel = itemPanel:Add("DLabel")
    itemLabel:SetText(v)
    itemLabel:Dock(FILL)
    itemLabel:SetFont("DermaLarge")
    itemLabel:SetContentAlignment(5)  -- 居中显示

    scroll.panels[itemPanel] = true
end
  1. 增强空背包的判断
    如果玩家还没收到inv_init的网络消息,ply.inv会是nil,原代码里的判断可以加上提示:
local plyinv = ply.inv
if not plyinv then
    print("背包未初始化!")
    return
end

修改后的完整代码

print("cl_inv wurde geladen!")

-- 初始化INV全局表,修复nil错误
INV = INV or {}

concommand.Add("inv_model", function(ply)
    local wep = ply:GetActiveWeapon()
    if not IsValid(wep) then return end
    print(wep:GetWeaponWorldModel())
end)

net.Receive("inv_init", function()
    LocalPlayer().inv = {}
end)

net.Receive("inv_give", function()
    local classname = net.ReadString()
    table.insert(LocalPlayer().inv, classname)
end)

function INV.Open()
    local ply = LocalPlayer()
    local plyinv = ply.inv
    if not plyinv then
        print("背包未初始化!")
        return
    end

    local scrw, scrh = ScrW(), ScrH()

    INV.Menu = vgui.Create("DFrame")
    local inv = INV.Menu
    inv:SetSize(scrw * .4, scrh * .6)
    inv:Center()
    inv:SetTitle("")
    inv:MakePopup()

    inv.Paint = function(me,w,h)
        surface.SetDrawColor(0,0,0,200)
        surface.DrawRect(0,0,w,h)
    end

    local scroll = inv:Add("DScrollPanel")
    scroll:Dock(FILL)
    scroll.panels = {}
    for k,v in pairs(plyinv) do
        local itemPanel = scroll:Add("DPanel")
        itemPanel:Dock(TOP)
        itemPanel:SetTall(60)
        itemPanel:DockMargin(5,5,5,0)

        local itemLabel = itemPanel:Add("DLabel")
        itemLabel:SetText(v)
        itemLabel:Dock(FILL)
        itemLabel:SetFont("DermaLarge")
        itemLabel:SetContentAlignment(5)

        scroll.panels[itemPanel] = true
    end
end

hook.Add( "OnPlayerChat", "InvOpen", function( ply, strText, bTeam, bDead )
    if ( ply != LocalPlayer() ) then return end
    if string.lower(strText) != "!inv" then return end
    INV.Open()
end )

内容的提问来源于stack exchange,提问作者TR0PS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 19:15:31