Главная » Основные форумы » Программирование на языке Lua
Страницы:
1
Алекс Лепс
Сообщений: 5 |
#1 23.08.2016 18:13:47 Знаю что возможно это уже обсуждалось, но я очень плохо знаю языки программирования. Этот код работает если в стакане есть все строки, если нет то выдает ошибку nil. Стакан 20 на 20, |
Николай Камынин
Сообщений: 2889 |
#2 23.08.2016 18:48:03 mm=getQuoteLevel2(«SPBFUT»,»NKZ6″) |
Алекс Лепс
Сообщений: 5 |
#3 23.08.2016 19:23:20 Спасибо за ответ, но это для меня ничего не меняет, возможно вы что то не дописали или я просто не понимаю что вы хотите сказать) |
Николай Камынин
Сообщений: 2889 |
#4 23.08.2016 19:50:38 mm=getQuoteLevel2(«SPBFUT»,»NKZ6″) |
Алекс Лепс
Сообщений: 5 |
#5 23.08.2016 20:04:54 Спасибо за вашу помощь, я попробую переделать. |
Алекс Лепс
Сообщений: 5 |
#6 24.08.2016 11:51:20 на самом деле то ли я не понимаю то ли меня, я упростил пример function main() в этом примере программа обращается к 10 строке стакана и запрашивает количество, но так как стакан полупустой |
Sergey Denegin
Сообщений: 451 |
#7 24.08.2016 12:04:35 для проверки значения, можно использовать условие: if mm.bid[mm.bid_count-10] ~= nil then у тебя ошибка возникает, т.к. сам элемент mm.bid[mm.bid_count-10] равен nil, а ты пытаешься взять из него поле quantity Напиши, если помог |
Алекс Лепс
Сообщений: 5 |
#8 24.08.2016 12:17:04 Да, спасибо. Таким образом программа выполняется без ошибки. Кое что проясняется. Теперь попробую воткнуть это в свой код. Спасибо! |
Sergey Denegin
Сообщений: 451 |
#9 24.08.2016 12:20:04 всегда пожалуйста |
Николай Камынин
Сообщений: 2889 |
#10 24.08.2016 15:59:18
В примере написано две проверки |
||
Вячеслав +
Сообщений: 95 |
#11 27.08.2016 04:30:37 Алекс Лепс
, |
rbatar
Сообщений: 13 |
#12 08.09.2016 17:51:59 Помогите избавиться от ошибки nil. 78 if getItem(«futures_client_limits»,0).cbplused ~= nil then |
rbatar
Сообщений: 13 |
#13 08.09.2016 18:28:15 Реализовал пока так, но хотелось бы не использовать массив var |
swerg
Сообщений: 1190 миру мир! |
#14 08.09.2016 19:15:41
Сначала следует проверить, что вот эта часть не равна nil В следующем посте вы это, собственно, и сделали, правда несколько экзотическим образом. if getItem(«futures_client_limits»,0) ~= nil then или |
||
rbatar
Сообщений: 13 |
#15 08.09.2016 19:22:08 Спасибо за помощь. Ваш 1-й вариант то, что надо
|
||
Николай Камынин
Сообщений: 2889 |
#16 08.09.2016 20:23:21 а так: |
rbatar
Сообщений: 13 |
#17 08.09.2016 20:39:22
Да, так тоже очень неплохо. Спасибо, Николай, возьму на вооружение. |
||
Вячеслав
Сообщений: 3 |
#18 14.04.2017 22:23:46 Доброго дня! Уважаемые мастера программирования, у меня (как и у Алекс Лепс) Квиком выдается ошибка «attempt to index field ‘?’ (a nil value)» Я подозреваю что неправильно написал перебор элементов массива в коде, для которых потом выполняется функция. Вот кусок кода: p_seccode={«PPPP»,»YYYY»,»AAAA»,»GGGG»,»NNNN»,»RRRR»,»HHHH»} — это массив бумаг for i,v in pairs(p_seccode) do function robot() for i,v in pairs(chart) do Я не знаток языка Lua, поэтому буду очень благодарен помощи! Спасибо! |
Sergey Gorokhov
Сообщений: 3877 |
#19 14.04.2017 22:38:46 Здравствуйте, Если нужен дальнейший анализ, приведите полный код и укажите строку на которой возникает ошибка (написано в тексте ошибки) |
Вячеслав
Сообщений: 3 |
#20 14.04.2017 23:46:37 Сергей, пока не уловил как надо. Строчка, которую Вы написали, полностью совпадает с моей кроме кавычек. Наверное что то не вижу. Вот более полный код: —Параметры: —Служебные переменные function main() function to_log(a_msg) for i,v in pairs(p_seccode) do function robot() for i,v in pairs(chart) do if (in_trade) then if not(in_trade) then if (in_trade) then if not (in_trade) then end end |
Sergey Gorokhov
Сообщений: 3877 |
#21 14.04.2017 23:53:51
Вот именно. кавычки — это строковое значение, а без кавычек это переменная которая меняет значения. |
||
Вячеслав
Сообщений: 3 |
#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
5,9731 gold badge30 silver badges45 bronze badges
asked Feb 24, 2014 at 17:28
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
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
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
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
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’
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)
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
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)
Attempt to perform arithmetic on field ‘?’ (a nil value)
Description: performing arithmetic (*, /, -, +, %, ^) on a nil value
Attempt to compare nil with <TYPE>
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>
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
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() вовсе и не получает никаких таблиц. Вполне может быть, что косяк в какой-нибудь мелочи. У меня так часто бывает.
Пожалуйста, объясните где ошибка и, желательно, почему так происходит? А то который час сижу и пытаюсь понять в чем суть. Уже аж мозги сварились.
Извиняюсь, если подобные вопросы были. Искал, но что-то не нашел.