首页 > 解决方案 > JSON.Lua json.encode 返回 nil

问题描述

我是 LUA 的新手,并尝试使用 Garrys Mod 学习这种语言的编码。

我想从 Garrys Mod 聊天中获取消息,并将它们发送到带有 webhook 的 Discord 频道。

它有效,但我尝试使用嵌入消息扩展这个项目。我需要 JSON 并使用 json.lua 作为库。

但是,一旦我发送消息,我就会检索以下错误消息:

尝试索引全局“json”(零值)

导致错误的代码如下:

json.encode({ { 
        ["embeds"] = { 
            ["description"] = text, 
            ["author"] = { 
                ["name"] = ply:Nick()
            }, 
        }, 
    } }),

完整代码:

AddCSLuaFile()
json = require("json")

webhookURL = "https://discordapp.com/api/webhooks/XXX"
local DiscordWebhook = DiscordWebhook or {}

hook.Add( "PlayerSay", "SendMsg", function( ply, text )
    t_post = {
        content = json.encode({ { 
            ["embeds"] = { 
                ["description"] = text, 
                ["author"] = { 
                    ["name"] = ply:Nick()
                }, 
            }, 
        } }),
        username = "Log",
    } 
    http.Post(webhookURL, t_post)
end )

我希望有人能帮助我

标签: jsonluanulldiscordgarrys-mod

解决方案


Garry's Mod 确实提供了两个使用 json 的函数。

他们是:

util.TableToJSON( table table, boolean prettyPrint=false )

util.JSONToTable( string json )

无需导入json,如果我没记错的话,这甚至是不可能的。

对于您想要做的事情,您需要将您的论点构建为如下表格:

local arguments = {
["key"] = "Some value",
["42"] = "Not always the answer",
["deeper"] = {
  ["my_age"] = 22,
  ["my_name"] = getMyName()
},
["even more"] = from_some_variable

然后打电话

local args_as_json = util.TableToJSON(arguments)

现在你可以传递args_as_json给你的

http.Post( string url, table parameters, function onSuccess=nil, function onFailure=nil, table headers={} )

推荐阅读