Меню

Table index is nil ошибка

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 😛

@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: Я обнаружил, что это работает, если я ставлю его на свой собственный клиент (хотя он все еще получает ошибки), но не будет работать на моем сервере.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • T6sp exe call of duty black ops 2 ошибка при запуске
  • T62a lan ошибка сети