我目前正在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)坐标的反向查找。任何人都对如何建立一个更灵活的系统有想法,玩家可以通过输入其中一个变量来找到桌子?预先感谢!
-blockchainporter
这并不能按照您的要求直接回答您的问题,但是我认为这将达到您想要做的目的。我创建了一个名为“ loot”的表,该表可以容纳许多对象,玩家可以通过键入名称将其中的任何一个放置在“ bag”中。
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
关于积分,您可以检查'bag'以查看玩家是否已经有一些物品,然后更新数量...
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