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

我得到的错误是:

[string“function NameGen()...”]:14:尝试将nil与数字进行比较
堆栈回溯:
  [string“function NameGen()...”]:14:在函数“NameGen”中
  [string“function NameGen()...”]:23:在主块中
  [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;

  如果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);
点赞
用户368361
用户368361

我找不到 _2syltest 被分配的地方 —— 只有 syltest。如果 _2syltest 不是来自别处,那可能是问题所在,因为你的 if 语句使用了这个值。 ```

2013-09-13 04:13:22
用户2633423
用户2633423

从你的代码结构来看,似乎你想在ifelseif条件中都使用syltest < 50,但你实际上使用了_2sylchoice < 50。此外,你可能想表达的是_2sylchoice = _2syl1(那里打错了吗?)。

看看这是否是你想要的:

function NameGen()
  local preftest = math.random(100)
  local syltest = math.random(100)
  local sufftest = math.random(100)
  local pref1 = "New "
  local _1syl1 = "Lon"
  local _2syl1 = "Don";
  local suff1 = " City"
  local prefchoice = pref1
  local _1sylchoice = _1syl1
  local _2sylchoice = _2syl1
  local 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-13 06:28:50