首页 > 解决方案 > LUA:通过变量查找特定表

问题描述

我目前正在用 Lua 开发一款文字冒险游戏——没有插件,我的第一个项目只是纯 Lua。本质上,这是我的问题;我试图找出如何使用其中一个变量对表进行“反向查找”。这是我尝试做的一个例子:

print("What are you trying to take?")
bag = {}
gold = {name="Gold",ap=3}
x = io.read("*l")
if x == "Gold" then
     table.insert(bag,gold)
     print("You took the " .. gold.name .. ".")
end

显然,用游戏中的每一个对象写出这样的一行会非常……令人筋疲力尽——尤其是因为我认为我可以使用这个解决方案不仅可以拿走物品,还可以使用反向从一个房间移动到另一个房间查找每个房间的 (x,y) 坐标。任何人都对如何制作一个更灵活的系统有任何想法,该系统可以通过玩家输入其中一个变量来找到一张桌子?提前致谢!

-区块链搬运工

标签: luainventoryitemstake

解决方案


这并没有像您提出的那样直接回答您的问题,但我认为这将有助于您尝试做的事情。我创建了一个名为“loot”的表格,它可以容纳许多物品,玩家可以通过输入名称将其中任何物品放入他们的“包”中。

bag = {}
loot = {
    {name="Gold", qty=3},
    {name="Axe", qty=1},
}

print("What are you trying to take?")
x = io.read("*l")
i = 1
while loot[i] do
    if (x == loot[i].name) then
        table.insert(bag, table.remove(loot,i))
    else
        i = i + 1
    end
end

对于奖励积分,您可以检查“包”以查看玩家是否已经拥有一些该物品,然后只需更新数量...

while loot[i] do
    if (x == loot[i].name) then
        j, found = 1, nil
        while bag[j] do
            if (x == bag[j].name) then
                found = true
                bag[j].qty = bag[j].qty + loot[i].qty
                table.remove(loot,i)
            end
            j = j + 1
        end
        if (not found) then
            table.insert(bag, table.remove(loot,i))
        end
    else
        i = i + 1
    end
end

同样,这不是您要求的“反向查找”解决方案......但我认为它更接近您通过让用户选择掠夺某些东西来尝试做的事情。

我的免责声明是我在自己的 lua 用法中不使用 IO 函数,所以我必须假设你的 x = io.read("*l") 是正确的。


PS。如果您只希望对象具有名称和数量,而不希望有任何其他属性(例如条件、附魔或其他),那么您还可以通过使用键/值对来简化我的解决方案:

bag = {}
loot = { ["Gold"] = 3, ["Axe"] = 1 }

print("What are you trying to take?")
x = io.read("*l")
for name, qty in pairs(loot) do
    if x == name then
        bag.name = (bag.name or 0) + qty
        loot.name = nil
    end
end

推荐阅读