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

时间:2013-09-13 04:10:07

标签: random lua

我得到的错误是

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

2 个答案:

答案 0 :(得分:5)

我看不到_2syltest的分配位置 - 仅syltest。如果_2syltest不是来自其他地方,那可能就是问题,因为这是你使用该值时的条件。

答案 1 :(得分:0)

从您的代码结构来看,似乎您想在syltest < 50if条件中使用elseif,而不是使用_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

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