2

我开始在 Lua 中开发一个小型 Game-Dev 项目,但我的这部分代码遇到了问题:

    if genrel == RPG and langl == BASIC and topicl == WAR then
        review = math.random(2, 5)
        review2 = math.random(2, 5)
        review3 = math.random(2, 3)
        money = money + 300
        print("You have earned a total of $300 dollars from your game. Overall not many people enjoyed the game.")

elseif genrel == RPG and langl == BASIC and topicl == "WESTERN" then
        review = math.random(7, 9)
        review2 = math.random(4, 9)
        review3 = math.random(5, 8)
    money = money + 400
    print("You have earned a total of $300 dollars from your game. The game recieved mixed reviews.")

topicl、langl 和genrel 是在代码前面定义的。例子:

topicChoice = io.read()
if topicChoice == 'War' then
topic = "[War]"
topicl = WAR

progLang = io.read()
if progLang == 'Java' then
lang = "[JAVA]"
langl = JAVA

genreChoice = io.read()
if genreChoice == 'ACTION' then
genre = "[ACTION]"
genrel = ACTION

一切都已定义,但是当我运行代码时,无论我输入什么,输出的随机数都是 if 下的第一个。这可能很难理解,所以这是我的完整代码。 http://pastebin.com/XS3aEVFS

摘要:程序通过确定类型、主题和编码语言来决定显示哪些随机数。它没有按类型、主题和编码语言选择数字,而是简单地使用第一个 if 语句。

4

2 回答 2

2

在你的代码早期,你有这个:

if genreChoice == 'ACTION' then
    genre = "[ACTION]"
    genrel = ACTION     
elseif genreChoice == 'RPG' then
    genre = "[RPG]"
    genrel = RPG     
elseif genreChoice == 'SIM' then
    genre = "[SIM]"
    genrel = SIM     
end

并且您分配给genrel变量ACTION,RPG和的值SIM,但是这些变量似乎没有在任何地方定义,因此它们的值是nil. 换句话说,当您执行时:

genrel = ACTION     

就像你做的一样:

genrel = nil     
于 2013-10-06T21:01:40.053 回答
1

Lorenzo 介绍了为什么您的代码没有按预期执行的要点。第二个问题是您正在检查玩家输入的字符串,但您没有规范化大小写。

考虑一下如果玩家输入类似的东西会发生什么WeSTErn。这与WESTERN- 您的变量没有正确设置并且您的程序再次输出错误的结果不同。

在比较之前规范化玩家输入,使用string.upperstring.lower,或者使用不同的数据类型,例如。数字。在处理数据时,并非所有内容都必须表示为字符串。

我应该像 Krister Andersson 所说的那样在 if 语句中加上引号吗?

仅当您希望这些变量包含字符串类型时。您也可以为它们中的每一个分配唯一编号,以便在它们之间进行识别。例如这样的事情:

local ACTION, RPG, SIM = 1, 2, 3
local JAVA, BASIC = 1, 2, 3
local WAR, WESTERN, BLOCKS = 1, 2, 3
-- etc.

最后一点,你真的应该考虑分解你的程序——这就是发明函数的原因。

于 2013-10-06T22:25:19.827 回答