JSON.Lua json.encode 返回为 nil

我是 LUA 的新手,在 Garrys Mod 中尝试学习这种语言的编程。

我想要获取 Garrys Mod 聊天室中的消息,并使用 Webhook 将它们发送到 Discord 频道。

它可以工作,但我尝试使用嵌入式消息扩展此项目。我需要使用 JSON,并使用 json.lua 作为库。

但是,一旦我发送消息,我会获得以下错误消息:

尝试对全局 'json' 进行索引(值为 nil)

导致错误的代码如下:

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 )

希望有人可以帮助我

点赞
用户4273199
用户4273199

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={} )
2018-09-01 14:04:01