【问题标题】:Function NameGen(): attempt to compare nil with number函数 NameGen():尝试将 nil 与数字进行比较
【发布时间】:2013-10-10 19:52:43
【问题描述】:

我得到的错误是

[string "function NameGen()..."]:14: attempt to compare nil with number
stack traceback:
    [string "function NameGen()..."]:14: in function 'NameGen'
    [string "function NameGen()..."]:23: in main chunk
    [C]: ?

我的代码:

function NameGen()
  preftest = math.random(100) ;
  syltest = math.random(100) ;
  sufftest = math.random(100) ;
  pref1 = "New ";
  _1syl1 = "Lon";
  _2syl1 = "Don";
  suff1 = " City";
  prefchoice = pref1;
  _1sylchoice = _1syl1;
  _2sylchoice = _2syl;
  suffchoice = suff1;

  if preftest < 50 and _2syltest < 50 and sufftest < 50 then 
    cityname = prefchoice .. _1sylchoice .. _2sylchoice .. suffchoice;
  elseif preftest < 50 and _2syltest < 50 then
    cityname = prefchoice .. _1sylchoice .. _2sylchoice;
  else
    cityname = _1sylchoice;
  end
end
NameGen();
print(cityname);

【问题讨论】:

  • 请修正你的缩进
  • 快速提示,您不需要所有这些分号。这不是 C。
  • if you.need_sleep then sleep() end
  • bugs = not sleep and more_bugs or maybe_less_bugs
  • (作为电视广告商)请不要在睡眠不足的影响下驾驶或操作 Stack Overflow。

标签: random lua


【解决方案1】:

我看不到_2syltest 被分配到哪里——只有syltest。如果_2syltest 不是来自其他地方,那可能就是问题所在,因为这是您的 if 使用该值的条件。

【讨论】:

  • 所以这是睡眠。非常感谢!
【解决方案2】:

从您的代码结构看来,您似乎想在ifelseif 条件中使用syltest &lt; 50,而不是使用_2sylchoice &lt; 50。此外,您的意思可能是_2sylchoice = _2syl1(那里有错字?)。

看看是不是你的意思:

function NameGen()
  preftest = math.random(100) 
  syltest = math.random(100) 
  sufftest = math.random(100)
  pref1 = "New "
  _1syl1 = "Lon"
  _2syl1 = "Don";
  suff1 = " City"
  prefchoice = pref1
  _1sylchoice = _1syl1
  _2sylchoice = _2syl1
  suffchoice = suff1

  if preftest < 50 and syltest < 50 and sufftest < 50 then
    cityname = prefchoice .. _1sylchoice .. _2sylchoice .. suffchoice
  elseif preftest < 50 and syltest < 50 then
    cityname = prefchoice .. _1sylchoice .. _2sylchoice
  else
    cityname = _1sylchoice
  end
end

for i = 1, 100 do
    NameGen()
    print(cityname)
end

顺便说一句,您使用了太多的全局变量。您使用的所有变量都应该是本地变量,除非您有充分的理由不这样做(尽管我没有更改代码的这方面,以免在您不知道我在说什么的情况下混淆您大约)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 2017-03-19
    • 2021-10-13
    • 2018-07-31
    • 2016-04-22
    相关资源
    最近更新 更多