在 Lua 中,else if (elseif) 被跳过了。

我开始使用Lua开发一个小游戏,但是我的代码有问题:

    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语句,而不是根据类型、主题和编程语言选择数字。

点赞
用户2633423
用户2633423

在你的代码中,最初这样写:

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

你将变量 ACTIONRPGSIM 的值分别赋给了 genrel,但是这些变量似乎在任何地方都没有定义,因此它们的值为 nil。换句话说,当你执行:

genrel = ACTION

就相当于执行:

genrel = nil
2013-10-06 21:01:40
用户234175
用户234175

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
--等等。

最后注意,你应该真正考虑分解你的程序--这就是函数被发明的原因。

2013-10-06 22:25:19