簡體   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