json - 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 )
我希望有人能帮助我
解决方案
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={} )
推荐阅读
- php - MPDF 8+ google 字体未注册
- python-3.x - 为什么一个属性有效而另一个无效?
- python - 变量是未定义的烧瓶mysql
- docker-compose - 使用 Amazon Keyspaces 存储后端运行 JanusGraph
- rundeck - .NET 代码如何在 RunDeck 软件中使用?
- python - 如何使用 Seaborn 创建 FacetGrid 堆叠条形图?
- qt - Qt 样式表中允许哪些字符串表示颜色?
- c++ - 复制矩阵的一部分并粘贴到另一个 C++
- swift - 在控制台中打印预操作脚本
- python - 从python中的字典计算蛋白质组的开始和结束位置