Table index is nil ошибка

What I’m currently trying to do is make a table of email addresses (as keys) that hold person_records (as values). Where the person_record holds 6 or so things in it. The problem I’m getting is that when I try to assign the email address as a key to a table it complains and says table index is nil… This is what I have so far:

random_record = split(line, ",")
person_record = {first_name = random_record[1], last_name = random_record[2], email_address = random_record[3], street_address = random_record[4], city = random_record[5], state = random_record[6]}
email_table[person_record.email_address] = person_record

I wrote my own split function that basically takes a line of input and pulls out the 6 comma seperated values and stores them in a table (random_record)

I get an error when I try to say email_table[person_record.email_address] = person_record.
But when I print out person_record.email_address it’s NOT nil, it prints out the string I stored in it.. I’m so confused.

function split(str, pat)
   local t = {}  -- NOTE: use {n = 0} in Lua-5.0
   local fpat = "(.-)" .. pat
   local last_end = 1
   local s, e, cap = str:find(fpat, 1)
   while s do
      if s ~= 1 or cap ~= "" then
     table.insert(t,cap)
      end
      last_end = e+1
      s, e, cap = str:find(fpat, last_end)
   end
   if last_end <= #str then
      cap = str:sub(last_end)
      table.insert(t, cap)
   end
   return t
end

According to the fontspec package’s user manual (2017/03/31 v2.6a, Section 5.1, p. 12)

Fonts known to LuaTEX […] may be loaded by their standard names as you’d speak them out loud, such as Times New Roman or Adobe Garamond. […]
The simplest example might be something like
setmainfont{Cambria}[...]
[…] The ‘font name’ can be found in various ways, such as by looking in the name listed in a application like Font Book on Mac OS X.

My operating system is Mac OS X. The following screenshot shows the Times New Roman font in in my Font Book application.

The Times New Roman font in Font Book

The following screenshot shows the Avenir font name in my Font Book application.

The Avenir font in Font Book

The following LaTeX document sets the main font of the document to Times New Roman.

documentclass{report}
usepackage{fontspec}
setmainfont{Times New Roman}
begin{document}
Hello, world!
end{document}

Processing this document with the LuaLaTeX format (i.e. with the LuaLaTeX «engine») results in the following pdf, as expected:

Hello, world!

However, replacing ‘Times New Roman’ with ‘Avenir’ and reprocessing the document with the LuaLaTeX format results in no pdf, and the following error message:

ERROR: table index is nil.

— TeX said —

scan_stop:
l.3 setmainfont{Avenir}

— HELP —
From the .log file…

The lua interpreter ran into a problem, so the remainder of this lua chunk will be ignored.

What’s the problem? Why doesn’t the Avenir example work whereas the Times New Roman one does?


Operating System: macOS Sierra Version 10.12.5
MacTex distribution: MacTeX-2017
LuaTeX: Version 1.0.4

Neon

  • #1

В этой теме я научу читать и понимать ошибки, возникающие в коде

от криворукости

из-за невнимательности.
1. Разбор структуры ошибок. Структура у всех ошибок одинаковая и состоит из названия файла, строки, описания ошибки и трассировки ошибки.
Рассмотрим на примере

Код:

[ERROR] addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:119: Tried to use a NULL entity!
1. SetModel - [C]:-1
2. SpawnEntity - addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:119
3. LeftClick - addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:142
4. unknown - gamemodes/sandbox/entities/weapons/gmod_tool/shared.lua:251

Название файла — где произошла ошибка:

Код:

addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua

Строка ошибки: 119
Описание ошибки: Tried to use a NULL entity!
Трассировка — показывает какие функции и в каких файлах предшествуют нашей ошибке:

Код:

1. SetModel - [C]:-1
2. SpawnEntity - addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:119
3. LeftClick - addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:142
4. unknown - gamemodes/sandbox/entities/weapons/gmod_tool/shared.lua:251

2. Описания ошибок. Чтобы понять как решить задачу, нам надо понять что произошло. В этом нам всегда помогает описание ошибки. Ниже я привожу типичные описания ошибок, наиболее часто встречающихся при разработке. (Список не полный и я буду рад вашим дополнениям)

  • Tried to use a NULL entity! — означает, что пытаешься использовать несуществующую энтити. Проверь что у тебя в переменной.
  • Tried to use a NULL physics object! — вызванная энтити пытается быть физичной, но у неё нет модели.
  • attempt to index global ‘MutantSpawns’ (a nil value) — попытка использовать в коде неинициализированную переменную. Проще говоря, переменная пуста, а к ней происходит обращение.
  • bad argument #1 to ‘FindByClass’ (string expected, got userdata) — неверный аргумент №1. Там должна быть строка, а получена userdata.
  • bad argument #1 to ‘pairs’ (table expected, got nil) — тоже неверный аргумент, должна быть таблица, а получено нулевое значение.
  • bad argument #1 to ‘JSONToTable’ (string expected, got no value) — ещё одна похожая херня, должна быть строка, а получено нулевое значение.
  • attempt to compare nil with number — сравнение числа и нулевой переменной.
  • table index is nil — попытка обращения к нулевому элементу.
  • Couldn’t include file ‘shared.lua’ (File not found) — не найден файл shared.lua
  • Calling net.Start with unpooled message name! [http://goo.gl/qcx0y] — попытка вызвать функцию net.Start с неизвестным идентификатором. Решается строкой util.AddNetworkString(«ваш идентификатор»)

3. Отсутствие ошибок.
Бывают случаи, когда не понятно почему не запускается сам мод. Такое случается когда в коде происходит фатальная ошибка и мод вообще не загружается. Это можно определить по такой строке:

Код:

Couldn't Load Init Script: 'darkrp/gamemode/init.lua'

В этом случае необходимо проверить последние изменения в коде и отменить их при необходимости. Скорее всего дело в пропущенных скобках, нарушающих синтаксис.

Если же сам мод работает, а не запускается определённые аддоны, то это может быть следствием:

  • перекрытия кода (переопределение переменных, функций и пр. в этом или другом файле)
  • файл со скриптом не был подключен
  • нефатальное нарушение синтаксиса

Последнее редактирование: 7 Янв 2019

  
  
-- FUNCTIONS / METHODS -- 
  
local cFunc = {};       -- Local Functions  
local cSetting = {};    -- Local Settings 
  
MainMenu_Newgame = {}; 
MainMenu_Newgame.__index = MainMenu_Newgame; 
  
--[[ 
  
]] 
  
-- /////////////////////////////// 
-- ///// New                ////// 
-- ///// Returns: Object    ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:New(...) 
    local obj = setmetatable({}, {__index = self}); 
    if obj.Constructor then 
        obj:Constructor(...); 
    end 
    return obj; 
end 
  
-- /////////////////////////////// 
-- ///// Render             ////// 
-- ///// Returns: Object    ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:Render() 
    if(self.enabled) then 
        self.rm:dxDrawRectangle(439, 254, 1102, 356, tocolor(0, 0, 0, 194), falses) 
        self.rm:dxDrawText(strings.mainmenu.newgame.lobbyname, 449, 264, 536, 295, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawRectangle(439, 227, 1102, 27, tocolor(0, 245, 201, 127), true) 
        self.rm:dxDrawText(strings.mainmenu.newgame.newlobby, 439, 227, 1540, 254, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.password, 449, 313, 536, 344, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.playercount, 797, 264, 884, 295, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.rounds, 449, 407, 536, 438, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.roundlenght, 661, 409, 748, 440, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.seconds, 852, 414, 866, 435, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.map, 1000, 268, 1069, 295, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.preview, 894, 305, 976, 473, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
         
        local map = guiGetText(self.guiele.combobox4) 
         
        if(fileExists("files/images/maps/"..map..".jpg")) then 
            self.rm:dxDrawImage(1015, 305, 264, 165, "files/images/maps/"..map..".jpg", 0, 0, 0, tocolor(255, 255, 255, 255), true) 
         
        end 
  
        self.rm:dxDrawRectangle(1279, 553, 246, 48, tocolor(255, 255, 255, 73), true) 
        self.rm:dxDrawText(strings.mainmenu.newgame.startgame, 1282, 553, 1530, 601, getColorFromBool(getElementData(self.guiele.startgame, "hover"), 255, 255, 255, 255, 255, 255, 255, 150), 0.4, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
    end 
end 
  
-- /////////////////////////////// 
-- ///// AddEvents          ////// 
-- ///// Returns: void      ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:AddEvents() 
    self.startGameFunc = function() 
        local sLobbyName    = guiGetText(self.guiele.edit1); 
        local sPassword     = guiGetText(self.guiele.edit2); 
         
        local iPlayers      = tonumber(guiGetText(self.guiele.combobox1)); 
        local iRounds       = tonumber(guiGetText(self.guiele.combobox2)); 
        local iRoundLenght  = tonumber(guiGetText(self.guiele.combobox3)); 
     
        local sMap          = guiGetText(self.guiele.combobox4); 
         
        local bFriendlyFire = guiCheckBoxGetSelected(self.guiele.checkbox1); 
         
        if(#sLobbyName > 3 and #sPassword > 3 and (iPlayers) and (iRounds) and (iRoundLenght) and #sMap > 1) then 
            triggerServerEvent("onPlayerLobbyCreate", getLocalPlayer(), sLobbyName, sha256(sPassword), iPlayers, iRounds, iRoundLenght, sMap, bFriendlyFire); 
        else 
            messageBox:Show(strings.messagebox.newgame.failTitle, strings.messagebox.newgame.failMessage, strings.messagebox.newgame.failButton, "error", false); 
        end 
     
    end 
     
     
    addEventHandler("onClientGUIClick", self.guiele.startgame, self.startGameFunc) 
     
end 
  
-- /////////////////////////////// 
-- ///// BuildGui           ////// 
-- ///// Returns: void      ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:BuildGui() 
    self.guiele.checkbox1   = self.rm:guiCreateCheckBox(449, 457, 152, 34, "Friendly fire", true, false) 
    self.guiele.edit1       = self.rm:guiCreateEdit(553, 264, 205, 35, "", false) 
    self.guiele.edit2       = self.rm:guiCreateEdit(553, 309, 205, 35, "", false) 
     
    self.guiele.startgame   = self.rm:guiCreateButton(1279, 553, 1530-1279, 601-553, "", false, nil, true, rstrings.sounds.buttons.hover, rstrings.sounds.buttons.click); 
    guiSetAlpha(self.guiele.startgame, 0) 
     
    self.guiele.combobox1   = self.rm:guiCreateComboBox(894, 271, 77, 212, "", false) 
    for index, val in ipairs(self.players) do guiComboBoxAddItem(self.guiele.combobox1, val) end; 
     
     
    self.guiele.combobox2   = self.rm:guiCreateComboBox(553, 413, 79, 211, "", false) 
    for index, val in ipairs(self.rounds) do guiComboBoxAddItem(self.guiele.combobox2, val) end; 
     
     
    self.guiele.combobox3   = self.rm:guiCreateComboBox(768, 414, 79, 215, "", false) 
     
    for index, val in ipairs(self.roundLenght) do guiComboBoxAddItem(self.guiele.combobox3, val) end; 
     
     
    self.guiele.combobox4   = self.rm:guiCreateComboBox(1069, 272, 156, 271, "", false) 
    for index, val in ipairs(self.maps) do guiComboBoxAddItem(self.guiele.combobox4, val) end; 
     
    self:AddEvents(); 
     
    for index, ele in pairs(self.guiele) do 
        if(self.guitext[index]) then 
            guiSetText(ele, self.guitext[index]) 
        end 
     
        guiSetFont(ele, fontManager.guiFonts.agency) 
    end 
end 
  
-- /////////////////////////////// 
-- ///// DestroyGui         ////// 
-- ///// Returns: void      ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:DestroyGui() 
    for index, ele in pairs(self.guiele) do 
        self.guitext[index] = (guiGetText(ele) or false) 
        destroyElement(ele); 
    end 
end 
-- /////////////////////////////// 
-- ///// Toggle             ////// 
-- ///// Returns: void      ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:Toggle() 
    if(self.enabled) then 
        self.enabled = false; 
        self:DestroyGui(); 
    else 
        self.enabled = true; 
        self:BuildGui(); 
    end 
end 
  
  
-- /////////////////////////////// 
-- ///// Constructor        ////// 
-- ///// Returns: void      ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:Constructor(...) 
    -- Instanzen 
    self.guiele         = {}; 
    self.guitext        = {}; 
    self.enabled        = false; 
    self.rm             = RenderManager:New(g.aesx, g.aesy); 
     
    self.players        = {2, 4, 6, 8, 10, 12, 14, 16, 32, 64, 128, 256}; 
    self.rounds         = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 40, 80, 160, 240}; 
    self.roundLenght    = {30, 60, 90, 120, 240, 480}; 
    self.maps           = {"prophunt-airport"}; 
  
     
    -- Funktionen 
  
     
    -- Events 
     
    outputDebugString("[CALLING] MainMenu_Newgame: Constructor"); 
end 
  
-- EVENT HANDLER -- 
  
  
  
-- FUNCTIONS / METHODS -- 
  
local cFunc = {};       -- Local Functions  
local cSetting = {};    -- Local Settings 
  
MainMenu_Newgame = {}; 
MainMenu_Newgame.__index = MainMenu_Newgame; 
  
--[[ 
  
]] 
  
-- /////////////////////////////// 
-- ///// New                ////// 
-- ///// Returns: Object    ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:New(...) 
    local obj = setmetatable({}, {__index = self}); 
    if obj.Constructor then 
        obj:Constructor(...); 
    end 
    return obj; 
end 
  
-- /////////////////////////////// 
-- ///// Render             ////// 
-- ///// Returns: Object    ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:Render() 
    if(self.enabled) then 
        self.rm:dxDrawRectangle(439, 254, 1102, 356, tocolor(0, 0, 0, 194), falses) 
        self.rm:dxDrawText(strings.mainmenu.newgame.lobbyname, 449, 264, 536, 295, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawRectangle(439, 227, 1102, 27, tocolor(0, 245, 201, 127), true) 
        self.rm:dxDrawText(strings.mainmenu.newgame.newlobby, 439, 227, 1540, 254, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.password, 449, 313, 536, 344, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.playercount, 797, 264, 884, 295, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.rounds, 449, 407, 536, 438, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.roundlenght, 661, 409, 748, 440, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.seconds, 852, 414, 866, 435, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.map, 1000, 268, 1069, 295, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
        self.rm:dxDrawText(strings.mainmenu.newgame.preview, 894, 305, 976, 473, tocolor(255, 255, 255, 255), 0.2, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
         
        local map = guiGetText(self.guiele.combobox4) 
         
        if(fileExists("files/images/maps/"..map..".jpg")) then 
            self.rm:dxDrawImage(1015, 305, 264, 165, "files/images/maps/"..map..".jpg", 0, 0, 0, tocolor(255, 255, 255, 255), true) 
         
        end 
  
        self.rm:dxDrawRectangle(1279, 553, 246, 48, tocolor(255, 255, 255, 73), true) 
        self.rm:dxDrawText(strings.mainmenu.newgame.startgame, 1282, 553, 1530, 601, getColorFromBool(getElementData(self.guiele.startgame, "hover"), 255, 255, 255, 255, 255, 255, 255, 150), 0.4, fontManager.fonts.agency, "center", "center", false, false, true, false, false) 
    end 
end 
  
-- /////////////////////////////// 
-- ///// AddEvents          ////// 
-- ///// Returns: void      ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:AddEvents() 
    self.startGameFunc = function() 
        local sLobbyName    = guiGetText(self.guiele.edit1); 
        local sPassword     = guiGetText(self.guiele.edit2); 
         
        local iPlayers      = tonumber(guiGetText(self.guiele.combobox1)); 
        local iRounds       = tonumber(guiGetText(self.guiele.combobox2)); 
        local iRoundLenght  = tonumber(guiGetText(self.guiele.combobox3)); 
     
        local sMap          = guiGetText(self.guiele.combobox4); 
         
        local bFriendlyFire = guiCheckBoxGetSelected(self.guiele.checkbox1); 
         
        if(#sLobbyName > 3 and #sPassword > 3 and (iPlayers) and (iRounds) and (iRoundLenght) and #sMap > 1) then 
            triggerServerEvent("onPlayerLobbyCreate", getLocalPlayer(), sLobbyName, sha256(sPassword), iPlayers, iRounds, iRoundLenght, sMap, bFriendlyFire); 
        else 
            messageBox:Show(strings.messagebox.newgame.failTitle, strings.messagebox.newgame.failMessage, strings.messagebox.newgame.failButton, "error", false); 
        end 
     
    end 
     
     
    addEventHandler("onClientGUIClick", self.guiele.startgame, self.startGameFunc) 
     
end 
  
-- /////////////////////////////// 
-- ///// BuildGui           ////// 
-- ///// Returns: void      ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:BuildGui() 
    self.guiele.checkbox1   = self.rm:guiCreateCheckBox(449, 457, 152, 34, "Friendly fire", true, false) 
    self.guiele.edit1       = self.rm:guiCreateEdit(553, 264, 205, 35, "", false) 
    self.guiele.edit2       = self.rm:guiCreateEdit(553, 309, 205, 35, "", false) 
     
    self.guiele.startgame   = self.rm:guiCreateButton(1279, 553, 1530-1279, 601-553, "", false, nil, true, rstrings.sounds.buttons.hover, rstrings.sounds.buttons.click); 
    guiSetAlpha(self.guiele.startgame, 0) 
     
    self.guiele.combobox1   = self.rm:guiCreateComboBox(894, 271, 77, 212, "", false) 
    for index, val in ipairs(self.players) do guiComboBoxAddItem(self.guiele.combobox1, val) end; 
     
     
    self.guiele.combobox2   = self.rm:guiCreateComboBox(553, 413, 79, 211, "", false) 
    for index, val in ipairs(self.rounds) do guiComboBoxAddItem(self.guiele.combobox2, val) end; 
     
     
    self.guiele.combobox3   = self.rm:guiCreateComboBox(768, 414, 79, 215, "", false) 
     
    for index, val in ipairs(self.roundLenght) do guiComboBoxAddItem(self.guiele.combobox3, val) end; 
     
     
    self.guiele.combobox4   = self.rm:guiCreateComboBox(1069, 272, 156, 271, "", false) 
    for index, val in ipairs(self.maps) do guiComboBoxAddItem(self.guiele.combobox4, val) end; 
     
    self:AddEvents(); 
     
    for index, ele in pairs(self.guiele) do 
        if(self.guitext[index]) then 
            guiSetText(ele, self.guitext[index]) 
        end 
     
        guiSetFont(ele, fontManager.guiFonts.agency) 
    end 
end 
  
-- /////////////////////////////// 
-- ///// DestroyGui         ////// 
-- ///// Returns: void      ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:DestroyGui() 
    for index, ele in pairs(self.guiele) do 
        self.guitext[index] = (guiGetText(ele) or false) 
        destroyElement(ele); 
    end 
end 
-- /////////////////////////////// 
-- ///// Toggle             ////// 
-- ///// Returns: void      ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:Toggle() 
    if(self.enabled) then 
        self.enabled = false; 
        self:DestroyGui(); 
    else 
        self.enabled = true; 
        self:BuildGui(); 
    end 
end 
  
  
-- /////////////////////////////// 
-- ///// Constructor        ////// 
-- ///// Returns: void      ////// 
-- /////////////////////////////// 
  
function MainMenu_Newgame:Constructor(...) 
    -- Instanzen 
    self.guiele         = {}; 
    self.guitext        = {}; 
    self.enabled        = false; 
    self.rm             = RenderManager:New(g.aesx, g.aesy); 
     
    self.players        = {2, 4, 6, 8, 10, 12, 14, 16, 32, 64, 128, 256}; 
    self.rounds         = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 40, 80, 160, 240}; 
    self.roundLenght    = {30, 60, 90, 120, 240, 480}; 
    self.maps           = {"prophunt-airport"}; 
  
     
    -- Funktionen 
  
     
    -- Events 
     
    outputDebugString("[CALLING] MainMenu_Newgame: Constructor"); 
end 
  
-- EVENT HANDLER -- 
  

Are you having trouble to understand the error that Lua (CS2D console) gives to you? Fear not because user Dousea is here for you! This thread is going to explain what errors you’d expect while scripting. Note that maybe not all errors have been identified by me so please.. contact if you find anything. Enough with the useless chit-chat, let’s go to the fun part.

Just a note, use CTRL+F to find your error here.

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

General Syntax
These are the errors that are commonly given for general syntax error.

Keep in mind

that you either forgot or accidentally inserted a word or a symbol that doesn’t match with Lua’s syntax.

Quote:

‘X’ expected near ‘Y’

X

: a word or a symbol.

Y

: a word or a symbol.

Lua is expecting

X

near

Y

.

Code:

if (not a)
     a = {true} — ‘then’ expected near ‘a’
end

print(a][1]) — ‘)’ expected near ‘]’

Quote:

‘X’ expected (to close ‘Z’ at line W) near ‘Y’

W

: line that contains

Z

.

X

: a word or a symbol.

Y

: a word or a symbol.

Z

: a word or a symbol.

Lua is expecting

X

near

Y

to close

Z

at line

W

.

Code:

if (true) then
     print(«it’s true!») — ‘end’ expected (to close ‘if’ at line 1) near ‘<eof>’

Quote:

unexpected symbol near ‘X’

X

: a word or a symbol.

Lua is not expecting any symbol near

X

.

Code:

print(«a»)) — unexpected symbol near ‘)’

Quote:

malformed number near ‘X’

X

: a word or a symbol.

There’s malformed number near

X

. You either try to concatenate a literal number with strings without brackets or accidentally inserted a word or a symbol after a number.

Code:

print(1..»st») — malformed number near ‘1..’

Quote:

unfinished string near ‘X’

X

: a word or a symbol.

You forgot to finish a string near

X

.

Code:

print(«I forgot to close this string) — unfinished string near ‘<eof>’

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Arithmetic
Arithmetic operation is a weakness for some scripters. These are the errors for arithmetic operations failures.

Keep in mind

that Lua provides automatic conversion for strings to numbers whenever a number is expected. Arithmetic only can be performed with numbers, and strings with following condition: only numerical constant inside the string, no other char.

Quote:

attempt to perform arithmetic on Y ‘X’ (a Z value)

X

: variable that is attempted to be performed with arithmetic.

Y

: either

local

,

global

, or

field

, based on

X

.

Z

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

, based on

X

.

You’re trying to perform arithmetic on

X

, while

X

is a

Z

value that couldn’t perform any arithmetic.

Code:

a = {}
b = «b»

print(a — 0) — attempt to perform arithmetic on global ‘a’ (a table value)
print(4 / b) — attempt to perform arithmetic on global ‘b’ (a string value)

Quote:

attempt to perform arithmetic on a X value

X

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

.

You’re trying to perform arithmetic on a literal or table value that couldn’t perform any arithmetic.

Code:

a = {}
a[10] = «string»

print(a[10] — 1) — attempt to perform arithmetic on a string value
print(«1» % {}) — attempt to perform arithmetic on a table value

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Concatenation
These are the errors that given when a concatenation error occured. Concatenation is only for strings and numbers.

Keep in mind

that Lua automatically converts numbers to strings whenever a string expected. Therefore, string concatenation accepts numbers besides strings.

Quote:

attempt to concatenate Y ‘X’ (a Z value)

X

: variable that is attempted to be concatenated.

Y

: either

local

,

global

, or

field

, based on

X

.

Z

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

, based on

X

.

You’re trying to concatenate

X

, while

X

is a

Z

value that is unconcatenatable.

Code:

a = {}

print(a .. » is a table») — attempt to concatenate global ‘a’ (a table value)
print(«a.b = » .. a.b) — attempt to concatenate field ‘b’ (a nil value)

Quote:

attempt to concatenate a X value

X

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

.

You’re trying to concatenate a literal or table value that is unconcatenatable.

Code:

a = {}

print(«Can I concatenate » .. true .. «?») — attempt to concatenate a boolean value
print(«a[1] = » .. a[1]) — attempt to concatenate a nil value

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Length Operator
Errors of these are given because you’re messing with length operator that’s denoted by

#

tag.

Keep in mind

that values that have length are strings and tables. The length of a string is its number of bytes (each character is one byte), while the length of a table is only permitted if the table is a sequence, a set of its keys are all numeric and equal to {1..n} where n is a non-negative integer (n is its length).

Quote:

attempt to get length of Y ‘X’ (a Z value)

X

: variable that is attempted to get its length.

Y

: either

local

,

global

, or

field

, based on

X

.

Z

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

, based on

X

.

You’re trying to get the length of

X

, while

X

is a

Z

value that doesn’t have any sort of length.

Code:

print(#a) — attempt to get length of global ‘a’ (a nil value)

Quote:

attempt to get length of a X value

X

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

.

You’re trying to get length of a literal or table value that doesn’t have any sort of length.

Code:

a = {}
a[97] = false

print(#nil) — attempt to get length of a nil value
print(#a[1]) — attempt to get length of a boolean value

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Table Index
These are the errors for table indexing.

Keep in mind

that all variables can act as keys in tables, but only two literal values can act as ones, number and string.

Quote:

attempt to index Y ‘X’ (a Z value)

X

: variable that is attempted to be indexed.

Y

: either

local

,

global

, or

field

, based on

X

.

Z

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

, based on

X

.

You’re trying to index

X

, while

X

is a

Z

value that couldn’t be indexed.

Code:

a = io.open(«test.txt»)

print(a[1]) — attempt to index global ‘a’ (a userdata value)
print(b.b) — attempt to index global ‘b’ (a nil value)

Quote:

attempt to index a X value

X

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

.

You’re trying to index a literal or table value that couldn’t be indexed.

Code:

a = {}
a[98] = true

print(a[1].index) — attempt to index a boolean value
print((«a»)[1]) — attempt to index a string value

You’re trying to set a value to nil index of a table.

Code:

a[nil] = true — table index is nil

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Function Calls
These errors are given to you if you’re doing something weird with function calls.

Keep in mind

that function calls are only for, well, functions. Built-in functions give you an error if you’re trying to send invalid arguments.

Quote:

attempt to call Y ‘X’ (a Z value)

X

: variable that is attempted to be called.

Y

: either

local

,

global

, or

field

, based on

X

.

Z

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

, based on

X

.

You’re trying to call

X

, while

X

is a

Z

value that couldn’t be called.

Code:

print(a()) — attempt to call global ‘a’ (a nil value)

Quote:

attempt to call a X value

X

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

.

You’re trying to call a literal or table value that couldn’t be called.

Code:

a = {}
a.ortimh = «user»

a.ortimh() — attempt to call a string value
io.openfile(«file») — attempt to call a nil value

Quote:

bad argument #X to ‘Z’ (Y expected)

X

: position of the argument.

Y

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

,

table

, or

value

.

Z

: a word or a symbol.

You’re trying to send an invalid value at argument position #

X

to

Z

function while argument #

X

of the function is expecting

Y

.

Code:

a = {}
b = setmetatable(a, «__add») — bad argument #2 to ‘setmetatable’ (nil or table expected)

Quote:

bad argument #X to ‘W’ (Y expected, got Z)

W

: a word or a symbol.

X

: position of the argument.

Y

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

,

table

, or

value

.

Z

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

,

table

, or

no value

.

You’re trying to send

Z

at argument position #

X

to

W

function while argument #

X

of the function is expecting

Y

.

Code:

print(table.concat()) — bad argument #1 to ‘concat’ (table expected, got no value)

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

You’ve read one, or some, or all of the errors meanings. These are several statements/questions that may lurk in your head currently.

I don’t understand these errors meanings.
Sorry for the inconvenience. I’m trying to give the best-short explanation for you to understand it better without useless words being used. Errors that Lua give are pretty explanatory.

I always get «attempt to concatenate a boolean value» error while I don’t have any boolean value?
Maybe you’re trying to send invalid arguments to CS2D functions such as cs2d lua cmd player, thus resulting a false value.

user Flacko has written:

Some cs2d functions such as player() return false on error (wrong parameter or invalid player ID)

Here’s an example of how this error can occur:

Code:

function joinhook(id)
     msg2(id, «Welcome, » .. player(id — 1, «name») .. «!@C») — attempt to concatenate a boolean value, if id = 1
end

addhook(«join», «joinhook»)

I’m getting «attempt to call a nil value» every X, without giving me which file that causes the error!
Maybe that’s because you’re adding a hook while the function you add to the hook is nil or not exist. You either need to delete the «adding hook» part or create a function for that hook. Here’s an example of how this error can occur:

Code:

function joinhook(id)
     msg2(id, «Welcome, » .. player(id, «name») .. «!@C»)
end

addhook(«join», «welcomehook») — attempt to call a nil value

What do ?, <eof> and <name> mean?
? means unknown, <eof> means end of file, and <name> could mean a lot such as identifier.

Let’s hope that you find your solutions to your problems!

edited 11×, last 07.07.16 01:41:40 pm

I’m awesome … and I really like cookies.

@vinceallenvince

I can train and sample files just fine on OS X. However, on a machine running Ubuntu 14.04, when trying to sample (ie. th sample.lua…), I get the following error. I’ve tried installing Torch w both luajit and plain lua (ie. TORCH_LUA_VERSION=LUA51 ./install.sh). But I still get the error. Any ideas? Thx.

/root/torch/install/bin/lua: /root/torch/install/share/lua/5.1/torch/File.lua:283: table index is nil
stack traceback:
/root/torch/install/share/lua/5.1/torch/File.lua:283: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:268: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:268: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:268: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’

/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:268: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:305: in function ‘load’
sample.lua:67: in main chunk
[C]: in function ‘dofile’
…/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:131: in main chunk
[C]: ?

@hughperkins

Not saying it will fix the problem, but seems like you are using a fairly old version of char-rnn?

@EricZeiberg

@hughperkins

becuaase line 67 of karpathy/master doesnt call File:load :-P

@vinceallenvince

Thx, pulled the latest but still get the error on another line.
sample.lua:86: in main chunk

@hughperkins

Ok. Are you sampling from a cv file created using the same version of char-rnn, or a different version?

@vinceallenvince

I’m sampling from a file created using an earlier version. I’ll train a file with the new version and sample and see what happens.

@vinceallenvince

Wow, ok.. I trained until I got one checkpoint file and sampled it and it worked! Thx.

@EricZeiberg

If the issue has been fixed, please close this.

@vinceallenvince

One more question.. I notice if I’m on my Ubuntu machine and try to sample checkpoints trained on OS X, I get the error. Is that expected? In other words, i should only try to sample from checkpoints trained on the same environment? Thx.

@hughperkins

Are you using the same versoin on each?

@vinceallenvince

Yes, just tested training on OS X and sampling a checkpoint from the training on Ubuntu. Same error.

@hughperkins

Interesting. I suppose it is to do with endian-ness plausibly. Does your Mac have an intel x86 processor, or some kind of 68000 type non-Intel processor?

@soumith

if you want to have cross-platform checkpoints, torch.save in ascii mode. torch.save(‘checkpoint.t7’, net, ‘ascii’)

@soumith

if you do 64-bit OSX and 64-bit Ubuntu, both on x64 processors. they should be fully compatible in terms of serialization. they only start getting weird when the processor endianness changes:

torch/torch7#5

@EricZeiberg

Also, be wary of saving the checkpoint under the same name every time, iirc
it will override the previous one.
On Aug 15, 2015 10:21 PM, «Soumith Chintala» notifications@github.com
wrote:

if you do 64-bit OSX and 64-bit Ubuntu, both on x64 processors. they
should be fully compatible in terms of serialization. they only start
getting weird when the processor endianness changes:

torch/torch7#5 torch/torch7#5


Reply to this email directly or view it on GitHub
#83 (comment).

Neon

  • #1

В этой теме я научу читать и понимать ошибки, возникающие в коде

от криворукости

из-за невнимательности.
1. Разбор структуры ошибок. Структура у всех ошибок одинаковая и состоит из названия файла, строки, описания ошибки и трассировки ошибки.
Рассмотрим на примере

Код:

[ERROR] addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:119: Tried to use a NULL entity!
1. SetModel - [C]:-1
2. SpawnEntity - addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:119
3. LeftClick - addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:142
4. unknown - gamemodes/sandbox/entities/weapons/gmod_tool/shared.lua:251

Название файла — где произошла ошибка:

Код:

addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua

Строка ошибки: 119
Описание ошибки: Tried to use a NULL entity!
Трассировка — показывает какие функции и в каких файлах предшествуют нашей ошибке:

Код:

1. SetModel - [C]:-1
2. SpawnEntity - addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:119
3. LeftClick - addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:142
4. unknown - gamemodes/sandbox/entities/weapons/gmod_tool/shared.lua:251

2. Описания ошибок. Чтобы понять как решить задачу, нам надо понять что произошло. В этом нам всегда помогает описание ошибки. Ниже я привожу типичные описания ошибок, наиболее часто встречающихся при разработке. (Список не полный и я буду рад вашим дополнениям)

  • Tried to use a NULL entity! — означает, что пытаешься использовать несуществующую энтити. Проверь что у тебя в переменной.
  • Tried to use a NULL physics object! — вызванная энтити пытается быть физичной, но у неё нет модели.
  • attempt to index global ‘MutantSpawns’ (a nil value) — попытка использовать в коде неинициализированную переменную. Проще говоря, переменная пуста, а к ней происходит обращение.
  • bad argument #1 to ‘FindByClass’ (string expected, got userdata) — неверный аргумент №1. Там должна быть строка, а получена userdata.
  • bad argument #1 to ‘pairs’ (table expected, got nil) — тоже неверный аргумент, должна быть таблица, а получено нулевое значение.
  • bad argument #1 to ‘JSONToTable’ (string expected, got no value) — ещё одна похожая херня, должна быть строка, а получено нулевое значение.
  • attempt to compare nil with number — сравнение числа и нулевой переменной.
  • table index is nil — попытка обращения к нулевому элементу.
  • Couldn’t include file ‘shared.lua’ (File not found) — не найден файл shared.lua
  • Calling net.Start with unpooled message name! [http://goo.gl/qcx0y] — попытка вызвать функцию net.Start с неизвестным идентификатором. Решается строкой util.AddNetworkString(«ваш идентификатор»)

3. Отсутствие ошибок.
Бывают случаи, когда не понятно почему не запускается сам мод. Такое случается когда в коде происходит фатальная ошибка и мод вообще не загружается. Это можно определить по такой строке:

Код:

Couldn't Load Init Script: 'darkrp/gamemode/init.lua'

В этом случае необходимо проверить последние изменения в коде и отменить их при необходимости. Скорее всего дело в пропущенных скобках, нарушающих синтаксис.

Если же сам мод работает, а не запускается определённые аддоны, то это может быть следствием:

  • перекрытия кода (переопределение переменных, функций и пр. в этом или другом файле)
  • файл со скриптом не был подключен
  • нефатальное нарушение синтаксиса

Последнее редактирование: 7 Янв 2019

@vinceallenvince

I can train and sample files just fine on OS X. However, on a machine running Ubuntu 14.04, when trying to sample (ie. th sample.lua…), I get the following error. I’ve tried installing Torch w both luajit and plain lua (ie. TORCH_LUA_VERSION=LUA51 ./install.sh). But I still get the error. Any ideas? Thx.

/root/torch/install/bin/lua: /root/torch/install/share/lua/5.1/torch/File.lua:283: table index is nil
stack traceback:
/root/torch/install/share/lua/5.1/torch/File.lua:283: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:268: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:268: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:268: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’

/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:268: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:282: in function ‘readObject’
/root/torch/install/share/lua/5.1/torch/File.lua:305: in function ‘load’
sample.lua:67: in main chunk
[C]: in function ‘dofile’
…/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:131: in main chunk
[C]: ?

@hughperkins

Not saying it will fix the problem, but seems like you are using a fairly old version of char-rnn?

@EricZeiberg

@hughperkins

becuaase line 67 of karpathy/master doesnt call File:load :-P

@vinceallenvince

Thx, pulled the latest but still get the error on another line.
sample.lua:86: in main chunk

@hughperkins

Ok. Are you sampling from a cv file created using the same version of char-rnn, or a different version?

@vinceallenvince

I’m sampling from a file created using an earlier version. I’ll train a file with the new version and sample and see what happens.

@vinceallenvince

Wow, ok.. I trained until I got one checkpoint file and sampled it and it worked! Thx.

@EricZeiberg

If the issue has been fixed, please close this.

@vinceallenvince

One more question.. I notice if I’m on my Ubuntu machine and try to sample checkpoints trained on OS X, I get the error. Is that expected? In other words, i should only try to sample from checkpoints trained on the same environment? Thx.

@hughperkins

Are you using the same versoin on each?

@vinceallenvince

Yes, just tested training on OS X and sampling a checkpoint from the training on Ubuntu. Same error.

@hughperkins

Interesting. I suppose it is to do with endian-ness plausibly. Does your Mac have an intel x86 processor, or some kind of 68000 type non-Intel processor?

@soumith

if you want to have cross-platform checkpoints, torch.save in ascii mode. torch.save(‘checkpoint.t7’, net, ‘ascii’)

@soumith

if you do 64-bit OSX and 64-bit Ubuntu, both on x64 processors. they should be fully compatible in terms of serialization. they only start getting weird when the processor endianness changes:

torch/torch7#5

@EricZeiberg

Also, be wary of saving the checkpoint under the same name every time, iirc
it will override the previous one.
On Aug 15, 2015 10:21 PM, «Soumith Chintala» notifications@github.com
wrote:

if you do 64-bit OSX and 64-bit Ubuntu, both on x64 processors. they
should be fully compatible in terms of serialization. they only start
getting weird when the processor endianness changes:

torch/torch7#5 torch/torch7#5


Reply to this email directly or view it on GitHub
#83 (comment).

Are you having trouble to understand the error that Lua (CS2D console) gives to you? Fear not because user Dousea is here for you! This thread is going to explain what errors you’d expect while scripting. Note that maybe not all errors have been identified by me so please.. contact if you find anything. Enough with the useless chit-chat, let’s go to the fun part.

Just a note, use CTRL+F to find your error here.

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

General Syntax
These are the errors that are commonly given for general syntax error.

Keep in mind

that you either forgot or accidentally inserted a word or a symbol that doesn’t match with Lua’s syntax.

Quote:

‘X’ expected near ‘Y’

X

: a word or a symbol.

Y

: a word or a symbol.

Lua is expecting

X

near

Y

.

Code:

if (not a)
     a = {true} — ‘then’ expected near ‘a’
end

print(a][1]) — ‘)’ expected near ‘]’

Quote:

‘X’ expected (to close ‘Z’ at line W) near ‘Y’

W

: line that contains

Z

.

X

: a word or a symbol.

Y

: a word or a symbol.

Z

: a word or a symbol.

Lua is expecting

X

near

Y

to close

Z

at line

W

.

Code:

if (true) then
     print(«it’s true!») — ‘end’ expected (to close ‘if’ at line 1) near ‘<eof>’

Quote:

unexpected symbol near ‘X’

X

: a word or a symbol.

Lua is not expecting any symbol near

X

.

Code:

print(«a»)) — unexpected symbol near ‘)’

Quote:

malformed number near ‘X’

X

: a word or a symbol.

There’s malformed number near

X

. You either try to concatenate a literal number with strings without brackets or accidentally inserted a word or a symbol after a number.

Code:

print(1..»st») — malformed number near ‘1..’

Quote:

unfinished string near ‘X’

X

: a word or a symbol.

You forgot to finish a string near

X

.

Code:

print(«I forgot to close this string) — unfinished string near ‘<eof>’

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Arithmetic
Arithmetic operation is a weakness for some scripters. These are the errors for arithmetic operations failures.

Keep in mind

that Lua provides automatic conversion for strings to numbers whenever a number is expected. Arithmetic only can be performed with numbers, and strings with following condition: only numerical constant inside the string, no other char.

Quote:

attempt to perform arithmetic on Y ‘X’ (a Z value)

X

: variable that is attempted to be performed with arithmetic.

Y

: either

local

,

global

, or

field

, based on

X

.

Z

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

, based on

X

.

You’re trying to perform arithmetic on

X

, while

X

is a

Z

value that couldn’t perform any arithmetic.

Code:

a = {}
b = «b»

print(a — 0) — attempt to perform arithmetic on global ‘a’ (a table value)
print(4 / b) — attempt to perform arithmetic on global ‘b’ (a string value)

Quote:

attempt to perform arithmetic on a X value

X

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

.

You’re trying to perform arithmetic on a literal or table value that couldn’t perform any arithmetic.

Code:

a = {}
a[10] = «string»

print(a[10] — 1) — attempt to perform arithmetic on a string value
print(«1» % {}) — attempt to perform arithmetic on a table value

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Concatenation
These are the errors that given when a concatenation error occured. Concatenation is only for strings and numbers.

Keep in mind

that Lua automatically converts numbers to strings whenever a string expected. Therefore, string concatenation accepts numbers besides strings.

Quote:

attempt to concatenate Y ‘X’ (a Z value)

X

: variable that is attempted to be concatenated.

Y

: either

local

,

global

, or

field

, based on

X

.

Z

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

, based on

X

.

You’re trying to concatenate

X

, while

X

is a

Z

value that is unconcatenatable.

Code:

a = {}

print(a .. » is a table») — attempt to concatenate global ‘a’ (a table value)
print(«a.b = » .. a.b) — attempt to concatenate field ‘b’ (a nil value)

Quote:

attempt to concatenate a X value

X

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

.

You’re trying to concatenate a literal or table value that is unconcatenatable.

Code:

a = {}

print(«Can I concatenate » .. true .. «?») — attempt to concatenate a boolean value
print(«a[1] = » .. a[1]) — attempt to concatenate a nil value

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Length Operator
Errors of these are given because you’re messing with length operator that’s denoted by

#

tag.

Keep in mind

that values that have length are strings and tables. The length of a string is its number of bytes (each character is one byte), while the length of a table is only permitted if the table is a sequence, a set of its keys are all numeric and equal to {1..n} where n is a non-negative integer (n is its length).

Quote:

attempt to get length of Y ‘X’ (a Z value)

X

: variable that is attempted to get its length.

Y

: either

local

,

global

, or

field

, based on

X

.

Z

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

, based on

X

.

You’re trying to get the length of

X

, while

X

is a

Z

value that doesn’t have any sort of length.

Code:

print(#a) — attempt to get length of global ‘a’ (a nil value)

Quote:

attempt to get length of a X value

X

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

.

You’re trying to get length of a literal or table value that doesn’t have any sort of length.

Code:

a = {}
a[97] = false

print(#nil) — attempt to get length of a nil value
print(#a[1]) — attempt to get length of a boolean value

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Table Index
These are the errors for table indexing.

Keep in mind

that all variables can act as keys in tables, but only two literal values can act as ones, number and string.

Quote:

attempt to index Y ‘X’ (a Z value)

X

: variable that is attempted to be indexed.

Y

: either

local

,

global

, or

field

, based on

X

.

Z

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

, based on

X

.

You’re trying to index

X

, while

X

is a

Z

value that couldn’t be indexed.

Code:

a = io.open(«test.txt»)

print(a[1]) — attempt to index global ‘a’ (a userdata value)
print(b.b) — attempt to index global ‘b’ (a nil value)

Quote:

attempt to index a X value

X

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

.

You’re trying to index a literal or table value that couldn’t be indexed.

Code:

a = {}
a[98] = true

print(a[1].index) — attempt to index a boolean value
print((«a»)[1]) — attempt to index a string value

You’re trying to set a value to nil index of a table.

Code:

a[nil] = true — table index is nil

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Function Calls
These errors are given to you if you’re doing something weird with function calls.

Keep in mind

that function calls are only for, well, functions. Built-in functions give you an error if you’re trying to send invalid arguments.

Quote:

attempt to call Y ‘X’ (a Z value)

X

: variable that is attempted to be called.

Y

: either

local

,

global

, or

field

, based on

X

.

Z

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

, based on

X

.

You’re trying to call

X

, while

X

is a

Z

value that couldn’t be called.

Code:

print(a()) — attempt to call global ‘a’ (a nil value)

Quote:

attempt to call a X value

X

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

, or

table

.

You’re trying to call a literal or table value that couldn’t be called.

Code:

a = {}
a.ortimh = «user»

a.ortimh() — attempt to call a string value
io.openfile(«file») — attempt to call a nil value

Quote:

bad argument #X to ‘Z’ (Y expected)

X

: position of the argument.

Y

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

,

table

, or

value

.

Z

: a word or a symbol.

You’re trying to send an invalid value at argument position #

X

to

Z

function while argument #

X

of the function is expecting

Y

.

Code:

a = {}
b = setmetatable(a, «__add») — bad argument #2 to ‘setmetatable’ (nil or table expected)

Quote:

bad argument #X to ‘W’ (Y expected, got Z)

W

: a word or a symbol.

X

: position of the argument.

Y

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

,

table

, or

value

.

Z

: either

nil

,

boolean

,

number

,

string

,

function

,

userdata

,

thread

,

table

, or

no value

.

You’re trying to send

Z

at argument position #

X

to

W

function while argument #

X

of the function is expecting

Y

.

Code:

print(table.concat()) — bad argument #1 to ‘concat’ (table expected, got no value)

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

You’ve read one, or some, or all of the errors meanings. These are several statements/questions that may lurk in your head currently.

I don’t understand these errors meanings.
Sorry for the inconvenience. I’m trying to give the best-short explanation for you to understand it better without useless words being used. Errors that Lua give are pretty explanatory.

I always get «attempt to concatenate a boolean value» error while I don’t have any boolean value?
Maybe you’re trying to send invalid arguments to CS2D functions such as cs2d lua cmd player, thus resulting a false value.

user Flacko has written:

Some cs2d functions such as player() return false on error (wrong parameter or invalid player ID)

Here’s an example of how this error can occur:

Code:

function joinhook(id)
     msg2(id, «Welcome, » .. player(id — 1, «name») .. «!@C») — attempt to concatenate a boolean value, if id = 1
end

addhook(«join», «joinhook»)

I’m getting «attempt to call a nil value» every X, without giving me which file that causes the error!
Maybe that’s because you’re adding a hook while the function you add to the hook is nil or not exist. You either need to delete the «adding hook» part or create a function for that hook. Here’s an example of how this error can occur:

Code:

function joinhook(id)
     msg2(id, «Welcome, » .. player(id, «name») .. «!@C»)
end

addhook(«join», «welcomehook») — attempt to call a nil value

What do ?, <eof> and <name> mean?
? means unknown, <eof> means end of file, and <name> could mean a lot such as identifier.

Let’s hope that you find your solutions to your problems!

edited 11×, last 07.07.16 01:41:40 pm

I’m awesome … and I really like cookies.

Я не знаю lua, хотя неплохо разбираюсь в нескольких других языках, так что я не совсем невежда в отношении таблиц и тому подобного.

Я нашел этот код в Интернете и пытался использовать его, но он продолжает выдавать table index is nil ошибка.

Я просматривал несколько других вопросов и проблем в Интернете с тем же сообщением об ошибке, но все еще не могу его решить.

Я обратился к автору за помощью, но он тоже не может понять. Видимо ошибка не у него.

Вот код:

local RolePoints = {
    [ROLE_DETECTIVE] = {[ROLE_DETECTIVE] = -250,--Killed Detective as Detective
                        [ROLE_INNOCENT] = -50,--Killed Innocent as Detective
                        [ROLE_TRAITOR] = 20
                    },
    [ROLE_INNOCENT] = {[ROLE_DETECTIVE] = -250,
                        [ROLE_INNOCENT] = -20,
                        [ROLE_TRAITOR] = 20
                    },
    [ROLE_TRAITOR] = {[ROLE_DETECTIVE] = 30,
                        [ROLE_INNOCENT] = 10,
                        [ROLE_TRAITOR] = -500
                    }
    }

В частности, толкователь утверждает, что виновником является эта строчка:

[ROLE_DETECTIVE] = {[ROLE_DETECTIVE] = -250,--Killed Detective as Detective

Есть идеи?

Спасибо

EDIT: Я обнаружил, что это работает, если я ставлю его на свой собственный клиент (хотя он все еще получает ошибки), но не будет работать на моем сервере.


11-21-20, 07:04 PM

 
#1

A Murloc Raider

Join Date: Nov 2020

Posts: 7

table index is nil


Hi, I have been trying to fix this addon and my knowledge of lua is limited at best. It still works, but throws an error first time it’s called then is fine. It started throwing the error in pre-patch shadowlands. And thank you in advance for help to fix this.

This is the lua error …

Date: 2020-10-12 12:58:10
ID: 1
Error occured in: Global
Count: 1
Message: ..AddOnsBattleDexBattleDex.lua line 69:
table index is nil
Debug:
[string «@BattleDexBattleDex.lua»]:69: RecordPet()
[string «@BattleDexBattleDex.lua»]:61: RecordBattle()
[string «@BattleDexBattleDex.lua»]:34:
BattleDexBattleDex.lua:23
Locals:
species = nil
level = 1
quality = 1
primary = 379
(*temporary) = <table> {
440 = <table> {
}
441 = <table> {
}
442 = <table> {
}
387 = <table> {
}
417 = <table> {
}
419 = <table> {
}
1162 = <table> {
}
675 = <table> {
}
437 = <table> {
}
378 = <table> {
}
424 = <table> {
}
379 = <table> {
}
}
(*temporary) = <table> {
}
(*temporary) = nil
(*temporary) = nil
(*temporary) = nil
(*temporary) = «table index is nil»

It only has 2 files, a TOC and Lua file
TOC file — The only thing I’ve changed in here is the Interface number

Code:

## Interface: 90001
## Title : BattleDex
## Notes: Track Pet Battles
## Author: Cal Henderson (Bees on Hyjal-US)
## Version: 1.1
## Dependencies: 
## SavedVariablesPerCharacter: BattleDexPrefs
## SavedVariables: BattleDexDB

BattleDex.lua

Lua file

Code:

BattleDex = {};
BattleDex.default_options = {
};

function BattleDex.OnReady()

	-- init database
	_G.BattleDexDB = _G.BattleDexDB or {};
	_G.BattleDexDB.pets = _G.BattleDexDB.pets or {};

	-- set up default options
	_G.BattleDexPrefs = _G.BattleDexPrefs or {};
	local k,v;
	for k,v in pairs(BattleDex.default_options) do
		if (not _G.BattleDexPrefs[k]) then
			_G.BattleDexPrefs[k] = v;
		end
	end

	GameTooltip:HookScript("OnTooltipSetUnit", BattleDex.AlterTooltip);
end

function BattleDex.OnEvent(frame, event, ...)

	if (event == 'ADDON_LOADED') then
		local name = ...;
		if name == 'BattleDex' then
			BattleDex.OnReady();
		end
		return;
	end

	if (event == 'PET_BATTLE_OPENING_DONE') then
		BattleDex.RecordBattle();
	end
end

function BattleDex.RecordBattle()

	if (not C_PetBattles.IsWildBattle()) then
		return;
	end

	-- get pet info

	local s1 = C_PetBattles.GetPetSpeciesID(2, 1);
	local s2 = C_PetBattles.GetPetSpeciesID(2, 2);
	local s3 = C_PetBattles.GetPetSpeciesID(2, 3);

	local l1 = C_PetBattles.GetLevel(2, 1);
	local l2 = C_PetBattles.GetLevel(2, 2);
	local l3 = C_PetBattles.GetLevel(2, 3);

	local r1 = C_PetBattles.GetBreedQuality(2, 1);
	local r2 = C_PetBattles.GetBreedQuality(2, 2);
	local r3 = C_PetBattles.GetBreedQuality(2, 3);

	-- record each pet

	BattleDex.RecordPet(s1, l1, r1, 0);
	BattleDex.RecordPet(s2, l2, r2, s1);
	BattleDex.RecordPet(s3, l3, r3, s1);
end

function BattleDex.RecordPet(species, level, quality, primary)

	--print(string.format("s=%d, l=%d, q=%d, p=%d", species, level, quality, primary));

	_G.BattleDexDB.pets[species] = _G.BattleDexDB.pets[species] or {};

	local key = primary.."_"..level.."_"..quality;

	_G.BattleDexDB.pets[species][key] = _G.BattleDexDB.pets[species][key] or 0;
	_G.BattleDexDB.pets[species][key] = _G.BattleDexDB.pets[species][key] + 1;
end

function BattleDex.AlterTooltip()

	local _, unit = GameTooltip:GetUnit();
        if (not unit) then return; end;
	if (not UnitIsWildBattlePet(unit)) then return; end;

	local species = UnitBattlePetSpeciesID(unit);

	-- is this pet in our DB at all?
	if (not _G.BattleDexDB.pets[species]) then
		GameTooltip:AddLine("|cFF9999FFNever battled");
		GameTooltip:Show();
		return;
	end

	-- make a new data structure of [primary -> {quality: count, quality:count}]
	local counts = {};
	local k,v;
	for k,v in pairs(_G.BattleDexDB.pets[species]) do
		local itr = string.gmatch(k, "%d+");
		local pri = tonumber(itr());
		local lvl = tonumber(itr());
		local qul = tonumber(itr());

		--GameTooltip:AddLine(string.format("%d / %d / %d", pri, qul, v));

		counts[pri] = counts[pri] or {};
		counts[pri][qul] = counts[pri][qul] or 0;
		counts[pri][qul] = counts[pri][qul] + v;
	end

	-- colors
	local _, _, _, col0 = GetItemQualityColor(0);
	local _, _, _, col1 = GetItemQualityColor(1);
	local _, _, _, col2 = GetItemQualityColor(2);
	local _, _, _, col3 = GetItemQualityColor(3);

	-- output
	for k,v in pairs(counts) do
		local pri = k;
		local num1 = v[1] or 0;
		local num2 = v[2] or 0;
		local num3 = v[3] or 0;
		local num4 = v[4] or 0;

		local nums = string.format("|c%s%d|r/|c%s%d|r/|c%s%d|r/|c%s%d|r", col0,num1,col1,num2,col2,num3,col3,num4);

		if (pri == 0) then
			GameTooltip:AddLine("Primary: "..nums);
		else
			local name = C_PetJournal.GetPetInfoBySpeciesID(pri);
			GameTooltip:AddLine(name..": "..nums);
		end
	end

	GameTooltip:Show();
end


-- ############################# Slash Commands #############################

SLASH_BattleDex1 = '/bd';
SLASH_BattleDex2 = '/battledex';

function SlashCmdList.BattleDex(msg, editBox)
end

-- ############################# Event Frame #############################

BattleDex.EventFrame = CreateFrame("Frame");
BattleDex.EventFrame:Show();
BattleDex.EventFrame:SetScript("OnEvent", BattleDex.OnEvent);
BattleDex.EventFrame:SetScript("OnUpdate", BattleDex.OnUpdate);
BattleDex.EventFrame:RegisterEvent("ADDON_LOADED");
BattleDex.EventFrame:RegisterEvent("PET_BATTLE_OPENING_DONE");

 

Reply With Quote


11-21-20, 07:16 PM

 
#2

I did that?

 

Fizzlemizz's Avatar

Premium Member

AddOn Author - Click to view addons

Join Date: Dec 2011

Posts: 1,679

Try moving OnReady from ADDON_LOADED to PLAYER_LOGIN. Your SavedVariables will have been loaded by the game when this event fires and it only fires once.

Don’t forget to remove your old SV .lua file(s) before trying.

Lua Code:

  1. function BattleDex.OnReady()

  2. -- init database

  3. if not BattleDexDB then

  4.         BattleDexDB = {

  5.             pets = {},

  6. }

  7. end

  8. if not BattleDexPrefs then

  9.         BattleDexPrefs = {}

  10. for k,v in pairs(BattleDex.default_options) do

  11. if not BattleDexPrefs[k] then

  12.                 BattleDexPrefs[k] = v

  13. end

  14. end

  15. end

  16.     GameTooltip:HookScript("OnTooltipSetUnit", BattleDex.AlterTooltip);

  17. end

  18. function BattleDex.OnEvent(frame, event, ...)

  19. if (event == 'PLAYER_LOGIN') then

  20.         BattleDex.OnReady();

  21. end

  22. if (event == 'PET_BATTLE_OPENING_DONE') then

  23.         BattleDex.RecordBattle();

  24. end

  25. end

  26. -- ...

  27. BattleDex.EventFrame:RegisterEvent("PLAYER_LOGIN");

  28. BattleDex.EventFrame:RegisterEvent("PET_BATTLE_OPENING_DONE");



Last edited by Fizzlemizz : 11-21-20 at 07:43 PM.


 

Reply With Quote


11-21-20, 09:00 PM

 
#3

A Pyroguard Emberseer

 

SDPhantom's Avatar

AddOn Author - Click to view addons

Join Date: Jul 2006

Posts: 2,253

SavedVars should be ready by the time ADDON_LOADED fires. It’s part of the addon loading process. The error isn’t complaining about the table itself being nil, there’s a different error for that. The problem is when you use nil as a key.

The code only works if the opponent has 3 battle pets. If they don’t have a full team, this error occurs. One or more empty spots causes species in BattleDex.RecordPet() (along with most of the other arguments) to be nil. This is what the error means by «table index is nil».

Again, if this was a load issue with the SavedVar, this would be «attempt to index nil» instead. It’s a common mistake to confuse these two.

__________________
WoWInterface AddOns

«All I want is a pretty girl, a decent meal, and the right to shoot lightning at fools.»

-Anders (Dragon Age: Origins — Awakening)


 

Reply With Quote


11-21-20, 11:08 PM

 
#4

A Murloc Raider

Join Date: Nov 2020

Posts: 7

Thank you for your help.
I changed to your code, still get the error, slightly different, but same error, when starting the first battle, and it doesn’t record the first battle, but does record later battles. I removed the SV before I went in game.

I have a full team, but the wild pets don’t always, testing in Darnassus where pets are single, low level. I’m fairly sure it was throwing the error on 3 wild pets, full team, too, but will go test the theory. …

Theory tested, and No, no error when starting with wild pets that have a full team with changed lua file. Also tested my original lua file and no it doesn’t error with the other team being full either. Both versions of lua recorded the first battle.


 

Reply With Quote


11-21-20, 11:46 PM

 
#5

A Pyroguard Emberseer

 

SDPhantom's Avatar

AddOn Author - Click to view addons

Join Date: Jul 2006

Posts: 2,253

That’s the spot it’s complaining about. Line 69 in function BattleDex.RecordPet(). The only line there that would generate that error (there are other operations like it, but it would throw a different error generating the second key) is this.

Code:

_G.BattleDexDB.pets[species] = _G.BattleDexDB.pets[species] or {};

The error is specifically saying species is nil.

PS: The theory was about the enemy team having less than 3 pets. The only other explanation is if BattleDex.RecordBattle() is running before pet data is available.

__________________
WoWInterface AddOns

«All I want is a pretty girl, a decent meal, and the right to shoot lightning at fools.»

-Anders (Dragon Age: Origins — Awakening)


 

Reply With Quote


11-22-20, 12:42 AM

 
#6

A Murloc Raider

Join Date: Nov 2020

Posts: 7

So is there a way I can get it to realize that when the pet doesn’t exist it’s 0, zero, not nil? or that it’s ok that the pet doesn’t exist? and just record the existing pet/s

a couple of lines down it tells it to either record/add 0 or 1
I’m presuming that’s not enough?

Code:

	_G.BattleDexDB.pets[species][key] = _G.BattleDexDB.pets[species][key] or 0;
	_G.BattleDexDB.pets[species][key] = _G.BattleDexDB.pets[species][key] + 1;

 

Reply With Quote


11-22-20, 11:32 AM

 
#7

A Cliff Giant

 

DahkCeles's Avatar

AddOn Author - Click to view addons

Join Date: Jun 2020

Posts: 73

Option 1: Add a safeguard to RecordPet() so that it doesn’t try to execute when information is missing.

Lua Code:

  1. function BattleDex.RecordPet(species, level, quality, primary)

  2. if (species) then

  3. --print(string.format("s=%d, l=%d, q=%d, p=%d", species, level, quality, primary));

  4. _G.BattleDexDB.pets[species] = _G.BattleDexDB.pets[species] or {};

  5. local key = primary.."_"..level.."_"..quality;

  6. _G.BattleDexDB.pets[species][key] = _G.BattleDexDB.pets[species][key] or 0;

  7. _G.BattleDexDB.pets[species][key] = _G.BattleDexDB.pets[species][key] + 1;

  8. end

  9. end

Option 2: Change RecordBattle() so it is smart enough to know you sometimes have fewer than three pets.

I think you can do it using C_PetBattles.GetNumPets() but its probably also doable with a simple if (s2) then … end

Lua Code:

  1. function BattleDex.RecordBattle()

  2. if (not C_PetBattles.IsWildBattle()) then

  3. return;

  4. end

  5. -- first pet

  6. local s1 = C_PetBattles.GetPetSpeciesID(2, 1);

  7. local l1 = C_PetBattles.GetLevel(2, 1);

  8. local r1 = C_PetBattles.GetBreedQuality(2, 1);

  9.     BattleDex.RecordPet(s1, l1, r1, 0); -- 4th arg means self is primary

  10. -- second pet

  11. if (C_PetBattles.GetNumPets(2) >= 2) then

  12. local s2 = C_PetBattles.GetPetSpeciesID(2, 2);

  13. local l2 = C_PetBattles.GetLevel(2, 2);    

  14. local r2 = C_PetBattles.GetBreedQuality(2, 2);

  15.         BattleDex.RecordPet(s2, l2, r2, s1);    -- 4th arg points to first pet

  16. end

  17. -- third pet

  18. if (C_PetBattles.GetNumPets(2) >= 3) then

  19. local s3 = C_PetBattles.GetPetSpeciesID(2, 3);

  20. local l3 = C_PetBattles.GetLevel(2, 3);

  21. local r3 = C_PetBattles.GetBreedQuality(2, 3); 

  22.         BattleDex.RecordPet(s3, l3, r3, s1);    -- 4th arg points to first pet

  23. end

  24. end



Last edited by DahkCeles : 11-23-20 at 04:48 PM.
Reason: «then» on line 22


 

Reply With Quote


11-22-20, 01:21 PM

 
#8

A Murloc Raider

Join Date: Nov 2020

Posts: 7

Awesome, I went with option 2. It errored on login, but putting ‘then’ on line 22 fixed that, and it’s now recording the low level pets without error.

Thank you very much everyone for your help


 

Reply With Quote


11-22-20, 05:47 PM

 
#9

A Pyroguard Emberseer

 

SDPhantom's Avatar

AddOn Author - Click to view addons

Join Date: Jul 2006

Posts: 2,253

I’d honestly convert it to a loop.

Lua Code:

  1. function BattleDex.RecordBattle()

  2. if not C_PetBattles.IsWildBattle() then return; end

  3. local primary=0;

  4. for i=1,C_PetBattles.GetNumPets(2) do

  5. local species=C_PetBattles.GetPetSpeciesID(2,i);

  6.         BattleDex.RecordPet(

  7.             species

  8.             ,C_PetBattles.GetLevel(2,i)

  9.             ,C_PetBattles.GetBreedQuality(2,i)

  10.             ,primary--  Passes zero for the first iteration

  11. );

  12. if i==1 then primary=species; end-- Sets the primary species for following iterations

  13. end

  14. end

__________________
WoWInterface AddOns

«All I want is a pretty girl, a decent meal, and the right to shoot lightning at fools.»

-Anders (Dragon Age: Origins — Awakening)


 

Reply With Quote

One problem when trying to help people with their Lua problem is that they don’t know how to read Lua errors. You can be 100% sure that saying «it doesn’t work» is absolutely not helpful at all. So I’ll tell you the ways to read Lua errors properly and what it means.

In this post, I used «<>» symbol to denote something arbitrary. Start by reading the syntax of Lua error. Lua error is usually have syntax like this:

<filename>:<lineNumber>: <message>

<filename> is the script file. <lineNumber> is line number where it occured. That’s very easy to remember, right? Now for the error message. The error message is usually very descriptive but sometimes it doesn’t really tell you what exactly is wrong, so here are some lists of Lua errors that I’m aware of. If your Lua error is unlisted, that can mean I didn’t add it yet or it’s thrown by external program.

  1. attempt to call global ‘<name>’ (a <non-function> value)
    This caused when you’re trying to call a global variable called ‘<name>’ but ‘<name>’ is not a function type. Example
    print() -- works
    table() -- attempt to call global 'table' (a table value)
    _VERSION() -- attempt to call global '_VERSION' (a string value)
    anilvalue() -- attempt to call global 'anilvalue' (a nil value)
    
  2. attempt to call field ‘<field>’ (a <non-function> value)
    Similar to above, but this occurs when you try to call something within a table.
    -- Note that 'math' is a global variable which is table
    math.abs(123) -- works
    math.pi() -- attempt to call field 'pi' (a number value)
    
  3. bad argument #<n> to ‘<name>’ (<type1> expected, got <type2>)
    This is caused when a function ‘<name>’ expects value with type <type1> for n-th argument, but user passed something with type <type2> instead.
    -- io.open expects string for the 1st argument
    local file = io.open(io.open) -- bad argument #1 to 'open' (string expected, got function)
    -- tonumber 2nd argument expects number if present
    tonumber("0xFF") -- works
    tonumber("0xFF", table) -- bad argument #2 to 'tonumber' (number expected, got table)
    
  4. table index is nil
    To be honest, this is most undescriptive Lua error message. What it means that you try to assign a value to a table at index «nil» (I mean literal nil).
    table[nil] = io -- table index is nil
    
  5. bad argument #<n> to ‘<name>’ (invalid option ‘<something>’)
    This means you passed invalid option. Notable function that throw this is ‘collectgarbage’ and ‘file:seek’.
    print(collectgarbage("count")) -- works
    collectgarbage("asd") -- bad argument #1 to 'collectgarbage' (invalid option 'asd')
    

So I think that covers most common Lua errors that you mostly encounter. In case you need help, please provide the Lua error message, plus the traceback if available. The traceback is also easy to read, the syntax is similar to above, and it definely helps.

… unless you got a very rare «PANIC» error which is unhelpful. No, really.

Понравилась статья? Поделить с друзьями:
  • Szone online ошибка нет ошибки
  • Systemsettingsadminflows exe ошибка приложения 0xc0000142
  • Systemsettings exe ошибка приложения windows 10
  • Systemdetection dll far cry 3 ошибка
  • Systemausfall ошибка в автобусе лиаз