4

我得到的错误是

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

2 回答 2

5

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

于 2013-09-13T04:13:22.097 回答
0

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

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

于 2013-09-13T06:28:50.580 回答