Ошибка attempt to index a nil value

Главная » Основные форумы » Программирование на языке Lua

Страницы:
1

 

Алекс Лепс


Пользователь

Сообщений: 5
Регистрация: 23.08.2016

#1

23.08.2016 18:13:47

Знаю что возможно это уже обсуждалось, но я очень плохо знаю языки программирования. Этот код работает если в стакане есть все строки, если нет то выдает ошибку nil. Стакан 20 на 20,
но если допустим в нем только десять заявок и есть пустые строки то возникает ошибка.( то есть стакан не полностью заполнен).
….
for i=0,19 do
m={}
mm=getQuoteLevel2(«SPBFUT»,»NKZ6″)
a0=mm.bid[mm.bid_count-i].quantity <———ОШИБКА ЗДЕСЬ
b0=mm.bid[mm.bid_count-i].price
c0=math.ceil(b0*1000000)
d0=tostring((c0/1000000)+1)
aa0=mm.offer[mm.offer_count-i].quantity
bb0=mm.offer[mm.offer_count-i].price
cc0=math.ceil(bb0*1000000)
dd0=tostring((cc0/1000000)-1)

Спасибо

 

Николай Камынин


Пользователь

Сообщений: 2889
Регистрация: 30.01.2015

#2

23.08.2016 18:48:03

mm=getQuoteLevel2(«SPBFUT»,»NKZ6″)
if  mm and mm.bit_count and mm.offer_count then
a0=mm.bid[mm.bid_count-i].quantity <———ОШИБКА ЗДЕСЬ
b0=mm.bid[mm.bid_count-i].price
c0=math.ceil(b0*1000000)
d0=tostring((c0/1000000)+1)
aa0=mm.offer[mm.offer_count-i].quantity
bb0=mm.offer[mm.offer_count-i].price
cc0=math.ceil(bb0*1000000)
dd0=tostring((cc0/1000000)-1)
end

 

Алекс Лепс


Пользователь

Сообщений: 5
Регистрация: 23.08.2016

#3

23.08.2016 19:23:20

Спасибо за ответ, но это для меня ничего не меняет, возможно вы что то не дописали или я просто не понимаю что вы хотите сказать)

 

Николай Камынин


Пользователь

Сообщений: 2889
Регистрация: 30.01.2015

#4

23.08.2016 19:50:38

mm=getQuoteLevel2(«SPBFUT»,»NKZ6″)  
if  mm and mm.bit_count and mm.offer_count then
————————-
local n=mm.bid_count;
while n>0 do
a0=mm.bid[n].quantity
b0=mm.bid[n].price  
c0=math.ceil(b0*1000000)  
d0=tostring((c0/1000000)+1)  
n=n-1;
end
————————
n=mm.bid_count;
while n>0 do
aa0=mm.offer[n].quantity  
bb0=mm.offer[n].price  
cc0=math.ceil(bb0*1000000)  
dd0=tostring((cc0/1000000)-1)
n=n-1
end
———————
end
————————————
-примерно так

 

Алекс Лепс


Пользователь

Сообщений: 5
Регистрация: 23.08.2016

#5

23.08.2016 20:04:54

Спасибо за вашу помощь, я попробую переделать.  

 

Алекс Лепс


Пользователь

Сообщений: 5
Регистрация: 23.08.2016

#6

24.08.2016 11:51:20

на самом деле то ли я не понимаю то ли меня, я упростил пример

function main()
mm=getQuoteLevel2(«SPBFUT»,»NKZ6″)
a0=mm.bid[mm.bid_count-10].quantity
message («объем=»..a0,2)
end

в этом примере программа обращается к 10 строке стакана и запрашивает количество, но так как стакан полупустой
то этой строки нет и lua выдает ошибку attempt to index field(a nil value)
как обойти эту ошибку в конкретном примере помогите пожалуйста.

 

Sergey Denegin


Пользователь

Сообщений: 451
Регистрация: 20.04.2016

#7

24.08.2016 12:04:35

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

if mm.bid[mm.bid_count-10] ~= nil then
 a0=mm.bid[mm.bid_count-10].quantity
end

у тебя ошибка возникает, т.к. сам элемент mm.bid[mm.bid_count-10] равен nil, а ты пытаешься взять из него поле quantity

Напиши, если помог

 

Алекс Лепс


Пользователь

Сообщений: 5
Регистрация: 23.08.2016

#8

24.08.2016 12:17:04

Да, спасибо. Таким образом программа выполняется без ошибки. Кое что проясняется. Теперь попробую воткнуть это в свой код. Спасибо!

 

Sergey Denegin


Пользователь

Сообщений: 451
Регистрация: 20.04.2016

#9

24.08.2016 12:20:04

всегда пожалуйста

 

Николай Камынин


Пользователь

Сообщений: 2889
Регистрация: 30.01.2015

#10

24.08.2016 15:59:18

Цитата
Алекс Лепс написал:
Спасибо за вашу помощь, я попробую переделать.

В примере написано две проверки
первый if проверяет существования стакана и очереди в нем
Циклы делаются по фактической длине очереди У вас циклы делались на фиксированную длину очереди.
Примерно так.

 

Вячеслав +


Пользователь

Сообщений: 95
Регистрация: 27.01.2016

#11

27.08.2016 04:30:37

Алекс Лепс

,
можно увидеть весь код целиком? Странно то, что 20 раз в цикле Вы запрашиваете getQuoteLevel2(«SPBFUT»,»NKZ6″) …

 

rbatar


Пользователь

Сообщений: 13
Регистрация: 06.09.2016

#12

08.09.2016 17:51:59

Помогите избавиться от ошибки nil.
Следующий код выдаёт ошибку «lua 78: attempt to index a nil value» , когда началась новая сессия и данные в терминал ещё не подгрузились.

      78  if getItem(«futures_client_limits»,0).cbplused ~= nil then
79       message( «futures_client_limits не равен nil» ,1)
80   end

 

rbatar


Пользователь

Сообщений: 13
Регистрация: 06.09.2016

#13

08.09.2016 18:28:15

Реализовал пока так, но хотелось бы не использовать массив var
var ={}
var = getItem(«futures_client_limits»,0)
if tostring(var) ~= «nil» then
message( «futures_client_limits не равен nil» ,1)
end  

 

swerg


Пользователь

Сообщений: 1190
Регистрация: 02.02.2015

миру мир!

#14

08.09.2016 19:15:41

Цитата
rbatar написал:
78  if getItem(«futures_client_limits»,0).cbplused ~= nil then

Сначала следует проверить, что вот эта часть не равна nil
getItem(«futures_client_limits»,0)

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

if getItem(«futures_client_limits»,0) ~= nil then

или
if var ~=nil then

 

rbatar


Пользователь

Сообщений: 13
Регистрация: 06.09.2016

#15

08.09.2016 19:22:08

Спасибо за помощь. Ваш  1-й вариант то, что надо

Цитата
if getItem(«futures_client_limits»,0) ~= nil then
 

Николай Камынин


Пользователь

Сообщений: 2889
Регистрация: 30.01.2015

#16

08.09.2016 20:23:21

а так:
local x=»futures_client_limits»;
local y = getItem(x,0)
if y  then  
message( x..» не равен nil» ,1)
end

 

rbatar


Пользователь

Сообщений: 13
Регистрация: 06.09.2016

#17

08.09.2016 20:39:22

Цитата
local x=»futures_client_limits»;
local y = getItem(x,0)
if y  then  
message( x..» не равен nil» ,1)
end

Да, так тоже очень неплохо. Спасибо, Николай, возьму на вооружение.

 

Вячеслав


Пользователь

Сообщений: 3
Регистрация: 14.04.2017

#18

14.04.2017 22:23:46

Доброго дня! Уважаемые мастера программирования, у меня (как и у Алекс Лепс) Квиком выдается ошибка «attempt to index field ‘?’ (a nil value)»

Я подозреваю что неправильно написал перебор элементов массива в коде, для которых потом выполняется функция. Вот кусок кода:

p_seccode={«PPPP»,»YYYY»,»AAAA»,»GGGG»,»NNNN»,»RRRR»,»HHHH»} — это массив бумаг
chart={«RSI1″,»RSI2″,»RSI3″,»RSI4″,»RSI5″,»RSI6″,»RSI7»} — это массив индикаторов графиков

for i,v in pairs(p_seccode) do

     function robot()

           for i,v in pairs(chart) do
           local RSI=getNumCandles(chart[i])
           local N=getNumCandles(«Price»)
           t,n,i=getCandlesByIndex(«Price», 0, N-1, 1)  
           RSI_t,RSI_n,RSI_i=getCandlesByIndex(«RSI», 0, RSI-3, 2)
и т.д.

     Я не знаток языка Lua, поэтому буду очень благодарен помощи! Спасибо!

 

Sergey Gorokhov


QUIK clients support

Сообщений: 3877
Регистрация: 23.01.2015

#19

14.04.2017 22:38:46

Здравствуйте,
Если Вы перебираете идентификаторы, то и в getCandlesByIndex тоже надо их перебирать.
т.е. напишите так:
RSI_t,RSI_n,RSI_i=getCandlesByIndex(RSI, 0, RSI-3, 2)

Если нужен дальнейший анализ, приведите полный код и укажите строку на которой возникает ошибка (написано в тексте ошибки)

 

Вячеслав


Пользователь

Сообщений: 3
Регистрация: 14.04.2017

#20

14.04.2017 23:46:37

Сергей, пока не уловил как надо. Строчка, которую Вы написали, полностью совпадает с моей кроме кавычек. Наверное что то не вижу.

Вот более полный код:

—Параметры:
p_classcode=»TQBR»
p_seccode={«POLY»,»YNDX»,»AVAZ»,»GAZP»,»NLMK»,»RTKM»,»HYDR»}
chart={«RSI1″,»RSI2″,»RSI3″,»RSI4″,»RSI5″,»RSI6″,»RSI7»}
p_account=»L01-00000F00″
p_clientcode=»56445″
p_count=77
p_spread=0.7
p_buy_level_RSI=70
p_sell_level_RSI=30

—Служебные переменные
is_run = true
count = 0
in_trade = true
order_num = «»
direction = «»  
last_price = 0

function main()
while is_run do
sleep(2000)
robot()
end
end

function to_log(a_msg)
p_file:write(os.date()..»   «..a_msg..»n»)
end

for i,v in pairs(p_seccode) do

   function robot()

   for i,v in pairs(chart) do
       local RSI=getNumCandles(chart[i])
       local N=getNumCandles(«Price»)
       t,n,i=getCandlesByIndex(«Price», 0, N-1, 1)  
       RSI_t,RSI_n,RSI_i=getCandlesByIndex(«RSI», 0, RSI-3, 2)

       if (in_trade) then
       —сигнал на покупку (RSI пересекает уровень продажи снизу вверх)
       if RSI_t[0].close<p_buy_level_RSI and RSI_t[1].close>p_buy_level_RSI then — — ВОТ ЗДЕСЬ ВЫБИВАЕТ ОШИБКУ
       Trade(«B»,p_count-count,t[0].close+p_spread)
       end
       end

       if not(in_trade) then
       —сигнал на продажу (RSI пересекает уровень продажи сверху вниз)
       if RSI_t[0].close>p_buy_level_RSI and RSI_t[1].close<p_buy_level_RSI then
       Trade(«S»,count+p_count,t[0].close-p_spread)
       end
       end

       if (in_trade) then
       —сигнал на покупку (RSI пересекает уровень продажи сверху вниз)
       if RSI_t[0].close>p_sell_level_RSI and RSI_t[1].close<p_sell_level_RSI then
       Trade(«S»,p_count-count,t[0].close+p_spread)
       end
       end

           if not (in_trade) then
       —сигнал на продажу (RSI пересекает уровень продажи снизу вверх)
       if RSI_t[0].close<p_sell_level_RSI and RSI_t[1].close>p_sell_level_RSI then
       Trade(«B»,count+p_count,t[0].close-p_spread)
       end
       end

       end    
end

end

 

Sergey Gorokhov


QUIK clients support

Сообщений: 3877
Регистрация: 23.01.2015

#21

14.04.2017 23:53:51

Цитата
Вячеслав написал:
Строчка, которую Вы написали, полностью совпадает с моей кроме кавычек. Наверное что то не вижу.

Вот именно. кавычки — это строковое значение, а без кавычек это переменная которая меняет значения.
Вам не кажется что брать свечки с одного графика,  по количеству свечек с другого, как-то не правильно?
А ведь именно это Вы и делаете в строке getCandlesByIndex(«RSI», 0, RSI-3, 2). Значение «RSI» (в кавычках) — это строка и она НЕ меняется. А RSI (без кавычек) — это переменная которая меняется в цикле local RSI=getNumCandles(chart[i])

 

Вячеслав


Пользователь

Сообщений: 3
Регистрация: 14.04.2017

#22

15.04.2017 13:30:28

Точно, я же говорю в упор не вижу чего то)) Сергей спасибо большое, буду исправлять.  

Страницы:
1

Читают тему (гостей: 1)

I can’t figure out what is wrong with my code but what I’m trying to achieve is to have regular spawns of blocks scroll past the screen which the player has to dodge. when each block goes off the left hand side of the screen, it increases the ‘obstacle values +1’

The problem I have is that when my ‘block’ object goes off screen I get this error:

«Attempt to index field ‘?’ (a nil value)»

can anyone help me because I really am stuck.
thanks

local yPos = {50,110,200}
local speed = 6
local block = {}
local obstacles = 0


function createBlock(event)
  local rnd = math.floor(math.random() * 4) + 1
  b = display.newImage('images/block3.png', display.contentWidth, yPos[math.floor(math.random() * 3)+1])
  b.x = 480
  b.name = 'block'
  physics.addBody(b, "static")
  blocks:insert(b)
  print(b.x)

  return true

end

function gameLoop( event )
   if(blocks ~= nil)then
     for i = 1, blocks.numChildren do
      blocks[i].x = blocks[i].x - speed -- (( THIS IS THE LINE WHICH GENERATES THE ERROR))
       if(blocks[i].x < -0) then
         display.remove(blocks[i])
         blocks[i] = nil
         print("+1!!")
         obstacles = obstacles +1
       end
     end 
  end
end


timerSrc = timer.performWithDelay(900, createBlock, 0)
Runtime:addEventListener("enterFrame", gameLoop)

Pimgd's user avatar

Pimgd

5,9731 gold badge30 silver badges45 bronze badges

asked Feb 24, 2014 at 17:28

Dips's user avatar

Here you are calling display.remove(blocks[i]) which is fine, but in the line right after you are setting blocks[i]=nil. There is no indication from the corona docs that this is a valid operation.

Also, once the object has been removed it is no longer in the group, so for sure doing blocks[i]=nil is incorrect: you are probably nilling the next block! I can’t check here but it would be interesting to print the id of the object i being deleted in this loop, before and after. You probably find that before executing display.remove(blocks[4]) (picking i=4 so example is clearer) the blocks[4] is not same object as after, so in effect you are removing two objects (and the second one is being removed incorrectly).

If blocks were a regular table rather than a userdata, the issues would be different, but you’d still have issues (beyond scope of your question; but I recommend you try it out!).

answered Feb 24, 2014 at 20:24

Oliver's user avatar

OliverOliver

27.1k9 gold badges69 silver badges101 bronze badges

I think the problem is in off screen object. When object is moving out of the visible group then it’s became nil. So you can’t not access that object.
You need to define alpha = 0 or isVisible = false of that object before moving out of the viewable screen and then you can access that object.

answered Feb 25, 2014 at 7:29

Chomu's user avatar

ChomuChomu

2141 silver badge10 bronze badges

You would get that error if you are «out of bounds,» per se. If you try to run your code, but try to access an index in table blocks that is nil then you will get that error.

My guess is that it has something to do with the numChildren thing you have going on there. Not really sure where that comes from, but I suggest using the default # operator to measure the size of the table.

For example:

for i = 1, #blocks do
    ...
end

Or even use an iterator:

for i, block in ipairs(blocks) do
    ...
end

Another possibility is that your blocks:insert() method is not inserting the values in order, starting the insert at 0, or not even using numerical indices (doubt that though).

In that case, I would suggest using the standard table.insert(blocks, b)

answered Feb 24, 2014 at 18:42

Stephen Leitnick's user avatar

Not sure how, but I think I successfully installed this library and now I’m trying to implement the example from the docs.

local evp_cipher = openssl.cipher.get('des')
m = 'abcdefghick'
key = m
cdata = evp_cipher:encrypt(m,key)
m1  = evp_cipher:decrypt(cdata,key)
assert(m==m1)

I’m getting the following error message, when I try to execute that script:

lua5.3: test2.lua:1: attempt to index a nil value (global 'openssl')
stack traceback:
	test2.lua:1: in main chunk
	[C]: in ?

Should this work out-of-the-box?

==========================EDIT==========================

I’ve noticed that the import is missing, but after adding

openssl = require('openssl')

as the first line of the script, I still don’t get very far. It’s just another error:

lua5.3: test2.lua:2: attempt to index a nil value (field 'cipher')
stack traceback:
	test2.lua:2: in main chunk
	[C]: in ?

Attempt to call a nil value

Description: calling a function that doesn’t exist

printtt(«abc») — printtt is not a function

test() — calling before it’s defined, same error

Unexpected symbol near ‘something’

Description: an invalid character is placed next to a value/keyword/variable/function call

function abc()) end — unexpected symbol near ‘)’

a l= 15 — unexpected symbol near ‘l’

local a = 5] — unexpected symbol near ‘]’

Attempt to index global ‘variable’ (a nil value)

Description: indexing via [key] or .key for a variable that doesn’t exist

abc.x = 5 — abc is nil, error

abc = {} — abc defined here

xyz[‘x’] = ‘abc’ — xyz is nil, error

Attempt to perform arithmetic on a nil value

Description: performing arithmetic (*, /, -, +, %, ^) on a nil value

print(xyz + 5) — error, xyz not defined

a = a + 5 — error, a not defined

Attempt to perform arithmetic on field ‘?’ (a nil value)

Description: performing arithmetic (*, /, -, +, %, ^) on a nil value

Attempt to compare nil with <TYPE>

Description: using a comparison operator (<, >, ~=, ==, >=, <=) in which one side is a nil value

print(x < y) — y is not defined

Malformed number near <NUMBER>

Description: the number has an invalid character next to it

print(12345aaa) — aaa makes it a malformed number

Unfinished capture | Malformed pattern

Description: the pattern is missing a closing ), or a closing ]

print(string.match(‘ABC’, ‘(‘)) — unfinished capture

print(string.match(‘ABC’, ‘[‘)) — malformed pattern

When you get an error, Lua provides a stack trace showing you where it originates from, where the error occurs, the function calls that led to the error, and the line number of where it occurred.

A general error will look like this:

file_location:LINE NUMBER: error message

file_location:LINE NUMBER: in <local/function> ‘FUNC’

file_location:LINE NUMBER: in main chunk

C:Usersuserlua_file.lua:5: attempt to perform arithmetic on a nil value (field ‘x’)

C:Usersuserlua_file.lua:5: in local ‘c’

C:Usersuserlua_file.lua:7: in local ‘b’

C:Usersuserlua_file.lua:9: in function ‘a’

C:Usersuserlua_file.lua:12: in main chunk

The code that resulted in this error is:

Here you can see the line number 5 after the file location, which tells us where the exact line with the code that resulted in the error. The stack traceback shows the functions that were called that led up to that.

First, function a is called at line 12, then function b is called at line 9 inside of a, then c is called at line 7 inside of function b, and finally at line 5, the error occurs inside of function c.

A note to add is that comments can offset the line number and make it appear as the error is in a line that doesn’t exist or doesn’t look like an error,

Доброго времени суток.
Уже достаточно долгое время мучаюсь с небольшим куском кода. После изучения всяческих способов реализации ООП в луа, решил попробовать сделать его своими силами. И, фактически, все работает, но не так, как мне хотелось бы.

Тут мы раскладываем объекты по какой-то карте, при этом, каждый объект создается для каждой ячейки и индивидуален.

function map_lay()
	for y = 1, map_w do
		for x = 1, map_h do
			local f = NEW(floor) --Создаем новый объект. 
			f.x = x * f.w -- Вот тут выдает ошибку attempt to index local "f" (nil value)
			f.y = y * f.h
			map[x][y] = f
			end
		end
	end

Вот тут и сам процесс создания.

function NEW(p) --Определяем тип и сортируем в таблицы для удобной работы с объектами. Ну и да, сама функция создает объект.
		o = {}
		o.Parent = p.name --На самом деле, я начал проверку отсюда сразу, как только выдало ошибку. Ребенок и правда рождается мертвым, а именно - nil
		
					--Если у объекта есть родитель, передаем ребенка по назначению при помощи метатаблицы. 
		if o.Parent == nil then
				do end
			else
				function o.Parent:newCreate(o)
					setmetatable(o, {__index = o.Parent})
				end
			end
		
		if o.Type == "tile" then
			table.insert(Turfs, o)
			o.id = math.random(1, 999999) -- На скорую руку для проверки количества объектов в действительности, а не просто #Turfs, где все объекты вполне могут быть одним единственным.
                end

			
			
		created(o) -- Если создан, выполняется код из функции. Например, отрисовка или логирование.
		return o
			
end end

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

tile = {
		name = tile,
		w = 32,
		h = 32,
		x = 0,
		y = 0,
		Type = "tile",
		Parent,
		id
	}

	 --Интересный момент. Если это объявить вместо local f = NEW(floor), получается ровно то, что я и хотел, и все работает (То самое "фактически"). Ну, точнее, если еще и объявлять локально.
	floor = { 
		name = floor,
		w = 32,
		h = 32,
		x = 0,
		y = 0,
		Type = "tile",
		Parent = tile
		}

В общем, никак не могу понять, что я делаю не так. Испробовал различные варианты, пытался переписывать, но в итоге nil и все тут. Словно функция NEW() вовсе и не получает никаких таблиц. Вполне может быть, что косяк в какой-нибудь мелочи. У меня так часто бывает.
Пожалуйста, объясните где ошибка и, желательно, почему так происходит? А то который час сижу и пытаюсь понять в чем суть. Уже аж мозги сварились.
Извиняюсь, если подобные вопросы были. Искал, но что-то не нашел.

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка appid is not configured
  • Ошибка att пионер магнитола
  • Ошибка apphangb1 windows 7
  • Ошибка atapi код 11 windows 7

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

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