【问题标题】:Lua attempt to call field 'PlayFile' (a nil value)Lua 尝试调用字段“PlayFile”(零值)
【发布时间】:2015-01-12 08:12:37
【问题描述】:

我正在尝试为 Garry's Mod 创建一个 Lua 插件,但我的代码中不断出现错误。 这是我的代码:

function say (Player, text, ent)
    s = "/misc/custom/"..text
    s2 = s..".mp3"
    sound.PlayFile(s2)
end
hook.Add("PlayerSay", "Say", say)

这是由此产生的错误。

[saysoundtest25] lua/autorun/chatsounds.lua:4: attempt to call field 'PlayFile' (a nil value)
1. v - lua/autorun/chatsounds.lua:4
2. unknown - lua/includes/modules/hook.lua:84

有什么想法吗?

【问题讨论】:

  • 这意味着sound作为一个对象存在,但它没有一个名为PlayFile的成员。我从来没有使用过 gmod,所以从你所展示的情况来看,你在其他地方运行的某些代码是否有“声音 = 某些东西”?或者,不太可能(因为 Lua 没有抱怨 sound 不存在,只是它没有 PlayFile 作为字段),可能是您需要在 gmod UI 或配置中激活某些东西来制作声音模块可用?

标签: lua garrys-mod


【解决方案1】:

Facepunch 上的用户 Robotboy655 帮我解决了这个问题!最终代码:

hook.Add( "PlayerSay", "Say", function( ply, text, team )
BroadcastLua( 'surface.PlaySound("misc/custom/' .. text .. '.mp3")' )
end )

感谢大家的帮助!

【讨论】:

    【解决方案2】:

    /lua/autorun 文件是服务器端的,并且有一个变量sound 服务器端 Lua,但是只有在客户端有 sound.PlayFile 存在。

    if SERVER then
        AddCSLuaFile() -- We're the server running this code! Let's send it to the client
    else -- We're a client!
    -- Your code here, only ran by the client!
    end
    

    请参阅the Garry's Mod wiki 了解更多信息,并注意页面上的橙色框,表示它是客户端。

    请记得检查函数还需要什么:

    sound.PlayFile( string path, string flags, function callback )

    示例(取自维基)

    sound.PlayFile( "sound/music/vlvx_song22.mp3", "", function( station )
        if ( IsValid( station ) ) then station:Play() end
    end )
    

    还有更简单的文档搜索方式:

    http://glua.me/

    http://glua.me/docs/#?q=sound.PlayFile

    DarkRP 如何处理这个问题:

    https://github.com/FPtje/DarkRP/blob/master/gamemode/modules/chatsounds.lua#L275

    【讨论】:

    • @Schollii 这是一个游戏,只有服务器端功能和客户端功能......在这种情况下,sound.PlayFile 只是客户端,自动运行文件夹纯粹是服务器端。跨度>
    • 我看到了使用surface.PlaySound 的建议。代码:BroadcastLua('surface.PlaySound(s2)') 几乎可以工作,但我最终会得到一个错误 'PlaySound' (string expected, got nil) 如果我知道要播放的确切文件,例如“hello.mp3”,那么代码 BroadcastLua('surface.PlaySound("/misc/custom/hello.mp3")') 将在文本出现时播放声音进入聊天室。棘手的部分是让它为不同的输入动态
    • 这意味着s2 不是一个字符串,但是这应该解决了第一个问题......虽然这不是一个支持表单。它说s2nil 尝试添加一些东西来调试,比如打印等等,它应该会有所帮助......
    • 啊,你忘记了文件的路径,看看你之前有“/misc/custom/”..s2..“.mp3”吗?是的,抱歉刚刚注意到。 编辑 当我发布该评论时,您的答案也出现了!哈,Robotboy 是 gmod 的开发者,所以我想说他可以提供比我更多的帮助,我建议使用表格或数组来表示带有空格的单词,例如“hi there”等。
    猜你喜欢
    • 2023-03-16
    • 2015-04-28
    • 2011-11-05
    • 1970-01-01
    • 2016-06-21
    • 2014-04-04
    • 2021-05-15
    • 1970-01-01
    • 2020-05-05
    相关资源
    最近更新 更多