如何在lua中传递一个对象到json,用php?

我有几个.lua文件,它们有这个结构,我应该如何通过php将其传递给json?

local monster = {}

monster.description = "a toad"
monster.experience = 60
monster.outfit = {
    lookType = 222,
    lookHead = 0,
    lookBody = 0,
    lookLegs = 0,
    lookFeet = 0,
    lookAddons = 0,
    lookMount = 0
}

monster.raceId = 262
monster.Bestiary = {
    class = "Amphibic",
    race = BESTY_RACE_AMPHIBIC,
    toKill = 500,
    FirstUnlock = 25,
    SecondUnlock = 250,
    CharmsPoints = 15,
    Stars = 2,
    Occurrence = 0,
    Locations = "The Laguna Islands, Arena and Zoo Quarter, Tiquanda/Tarantula Caves, \z
        Shadowthorn Bog God Temple, Northern Zao Plantations, Northern Brimstone Bug Cave."
    }

monster.health = 135
monster.maxHealth = 135

monster.changeTarget = {
    interval = 4000,
    chance = 10
}

monster.voices = {
    interval = 5000,
    chance = 10,
    {text = "Ribbit! Ribbit!", yell = false},
    {text = "Ribbit!", yell = false}
}

monster.loot = {
    {name = "gold coin", chance = 80000, maxCount = 20},
    {name = "war hammer", chance = 148},
    {name = "mace", chance = 2854},
    {id = 3578, chance = 20000},
    {name = "poisonous slime", chance = 4761}
}

monster.attacks = {
    {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -30, effect = CONST_ME_DRAWBLOOD, condition = {type = CONDITION_POISON, totalDamage = 20, interval = 4000}},
    {name ="combat", interval = 2000, chance = 20, type = COMBAT_PHYSICALDAMAGE, minDamage = -8, maxDamage = -17, range = 7, shootEffect = CONST_ANI_POISON, effect = CONST_ME_GREEN_RINGS, target = false}
}

monster.defenses = {
    defense = 6,
    armor = 6,
    {name ="speed", interval = 2000, chance = 15, speedChange = 200, effect = CONST_ME_MAGIC_RED, target = false, duration = 5000}
}

我考虑过制作一个解析器类来组装这个结构,因为它跟json结构不是太远了。有人有什么想法或者可以提取这些数据吗?

原文链接 https://stackoverflow.com/questions/71311286

点赞
stackoverflow用户7185318
stackoverflow用户7185318

你可以使用类似 lunajson 的库将 Lua 的值(在你这个例子中是一个表)转换为 JSON 字符串。

为了提取数据,你可以简单地执行文件 - 例如使用 loadfile - 然后获取变量的值:

  • 如果变量是全局的,只需索引全局表;
  • 如果变量是本地的 - 就像你的例子一样 - 你需要在脚本末尾添加 return var(如果没有)或使用 Lua 的内置 debug 库来提取它。

你的代码让我感到有些奇怪,因为局部变量没有被导出(所以代码将不起作用)。

如果你担心安全问题,只需为文件设置一个空环境,以确保它们无法调用任何函数。如果你不想让字符串函数可调用,则可以进一步清除字符串元表。

将所有东西放在一起(使用 Lua 5.1,它提供了 setfenv 来设置函数环境),并假设文件以 return monster 结尾:

local lunajson = require"lunajson"
local path_to_file = ...
local chunk = assert(loadfile(path_to_file))
setfenv(chunk, {}) -- set empty environment
local str_mt = getmetatable""
local str_mt_idx = str_mt.__index
str_mt.__index = nil
local status, val_or_err = pcall(chunk) -- execute file
str_mt.__index = str_mt_idx
if not status then error(val_or_err) end -- error after restoring the string metatable
print(lunajson.encode(val_or_err)) -- print the encoded JSON

现在你可以将其作为 shell 实用程序使用:lua5.1 myutil.lua file_to_convert.lua >> output.json

2022-03-01 19:39:14