繁体   English   中英

函数NameGen():尝试将nil与数字进行比较

[英]Function NameGen(): attempt to compare nil with number

我得到的错误是

[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);

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

从你的代码的结构看来,你想用syltest < 50ifelseif条件,而不是你使用_2sylchoice < 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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM