<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title>Форум QUIK [тема: Функция возвращает nil]</title>
		<link>http://forum.quik.ru</link>
		<description>Новое в теме Функция возвращает nil форума  на сайте Форум QUIK [forum.quik.ru]</description>
		<language>ru</language>
		<docs>http://backend.userland.com/rss2</docs>
		<pubDate>Sat, 02 May 2026 22:44:57 +0300</pubDate>
		<item>
			<title>Функция возвращает nil</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message36337/topic4265/">Функция возвращает nil</a></b> <i>При выходе из функции она возвращает nil, хотя внутри функции все ОК</i> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			<br />====quote====<br /><a class="blog-p-user-name" id="bp_7fqx5EjL" href="/user/17/" bx-tooltip-user-id="17">Sergey Gorokhov</a> написал:<br /> <br />====quote====<br /><noindex><a href="/user/12873/" target="_blank" rel="nofollow">VNG_nemo</a></noindex> написал:<br />переменная posixNewLblTime получает значение nil.<br />=============<br /> А как Вы это поняли?<br />Если по строке <br /> <br />====quote====<br /><noindex><a href="/user/12873/" target="_blank" rel="nofollow">VNG_nemo</a></noindex> написал:<br />message(tostring(posixNewLblTimeF)..&quot; &nbsp;IsLabelChange_posixNewLblTime&quot;)		<br />=============<br /> <br />То в ней явно другая переменная, а не искомая posixNewLblTime<br />=============<br />Сергей, огромное спасибо, все работает. Искал один косяк, а накосячил в другом месте.<br />Еще раз спасибо <br />
			<i>13.02.2019 07:54:02, VNG_nemo.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message36337/topic4265/</link>
			<guid>http://forum.quik.ru/messages/forum10/message36337/topic4265/</guid>
			<pubDate>Wed, 13 Feb 2019 07:54:02 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Функция возвращает nil</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message36335/topic4265/">Функция возвращает nil</a></b> <i>При выходе из функции она возвращает nil, хотя внутри функции все ОК</i> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			<br />====quote====<br /><a class="blog-p-user-name" id="bp_PERsUUKc" href="/user/12873/" bx-tooltip-user-id="12873">VNG_nemo</a> написал:<br />переменная posixNewLblTime получает значение nil.<br />=============<br />А как Вы это поняли?<br />Если по строке <br /><br />====quote====<br /><a class="blog-p-user-name" id="bp_snlRYSKe" href="/user/12873/" bx-tooltip-user-id="12873">VNG_nemo</a> написал:<br />message(tostring(posixNewLblTimeF).." &nbsp;IsLabelChange_posixNewLblTime")		<br />=============<br /><br />То в ней явно другая переменная, а не искомая posixNewLblTime <br />
			<i>13.02.2019 05:56:47, Sergey Gorokhov.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message36335/topic4265/</link>
			<guid>http://forum.quik.ru/messages/forum10/message36335/topic4265/</guid>
			<pubDate>Wed, 13 Feb 2019 05:56:47 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Функция возвращает nil</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message36310/topic4265/">Функция возвращает nil</a></b> <i>При выходе из функции она возвращает nil, хотя внутри функции все ОК</i> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Здравствуйте форумчане. В коде ниже функция GETLABLEPOSIXTIME внутри себя <br />рассчитывается корректно (должна возвращать время метки в формате posix, в <br />сообщении его и выводит), но при обращении к ней в функции IsLabelChange <br />переменная posixNewLblTime получает значение nil. Второй день бьюсь, не пойму <br />в чем косяк. Что не так делаю?<table class="forum-spoiler"><thead onclick="if (this.nextSibling.style.display=='none') { this.nextSibling.style.display=''; BX.addClass(this, 'forum-spoiler-head-open'); } else { this.nextSibling.style.display='none'; BX.removeClass(this, 'forum-spoiler-head-open'); } BX.onCustomEvent('BX.Forum.Spoiler:toggle', [{node: this}]); event.stopPropagation();"><tr><th><div>Скрытый текст</div></th></tr></thead><tbody class="forum-spoiler" style="display:none;"><tr><td>Settings={<br />	Name = &quot;0_12.02.2019&quot;,--имя индикатора<br />	AssetID = &quot;sber&quot;,--идентификатор инструмента<br />	LabelName = &quot;D:\метка.bmp&quot;,--имя файла метки &quot;down-254095_1280_1&quot;,<br />	stopper = false,--обработка на каждом тике <br />	complect = 0,<br />-- начальное местоположение меток<br />	fplace = 40,<br />	splace = 5,<br />	Yvalue = 0,<br /> &nbsp; &nbsp; &nbsp;line=<br /> &nbsp; &nbsp; &nbsp; &nbsp; {<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name = &quot;High&quot;,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Type =TYPE_LINE,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Width = 1,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Color = RGB(120,90, 140)<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}--,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;--{<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --Name = &quot;Low&quot;,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --Type =TYPE_LINE,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --Width = 1,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --Color = RGB(120,90,140)<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;--},<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;--{<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --Name = &quot;Close&quot;,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --Type =TYPE_LINE,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Width = 1,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --Color = RGB(120,90, 140)<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;--},<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;--{<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;--Name = &quot;Open&quot;,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --Type =TYPE_LINE,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --Width = 1,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --Color = RGB(120,90,140)<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;--}<br />			--}<br /> &nbsp; &nbsp; &nbsp; &nbsp; }<br />}<br /><br /><br />--глобальные переменные<br />-- Внимание, название всех параметров меток должны писаться большими буквами<br />	label={<br />	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --TEXT=&quot;метка&quot;;<br />	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; IMAGE_PATH=Settings.LabelName;<br />	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --TRANSPARENCY=50,<br />	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --TRANSPARENT_BACKGROUND=1,<br />	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --YVALUE=Settings.Yvalue,<br />	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DATE=0,<br />	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TIME=0;<br />				 --R=255;<br />				 --G=255;<br />				 --B=255;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}<br /><br /><br />t={}--исходная таблица данных свечек<br />tposixByTime={}--индексы свечек проиндексированные по времени<br />tposixOldLabelTime={}--таблица старых значений даты-времени выведенных на чарт меток в POSIX-формате<br />count=0--ограничитель количества циклов<br />Label_Id = {}--массив с идентификаторами меток			<br />ScriptPath=&quot;&quot;--полный путь к иконке (для метки)<br />flagIndExist=false--флаг существования индикатора на чарте<br />flagLblModify=false--флаг, сигнализирующий о перемещении метки<br />a=0<br />b=0<br />c=0<br />k=0<br />v=0<br />tDT={}<br />	<br />function Init()<br /><br /><br />--объявление переменных. Присваиваем начальные значения чтобы сразу типизировать.<br />	local n = 0--количество строк в таблице (количество свечек)<br />	local l = &quot;&quot;--подпись инструмента<br />	local NmbrOfCandles = 0--номер последней справа свечи на графике<br />	local CandleIndex = 0<br />	--local tDT={}<br /><br /><br />---&#91;&#91;	<br /> &nbsp; &nbsp;if Settings.AssetID == &quot;&quot; then <br /> &nbsp; &nbsp; &nbsp; &nbsp;message(&quot;Необходимо установить идентификатор инструмента&quot;)<br /> &nbsp; &nbsp;end<br />	--ScriptPath = getScriptPath()..&quot;\\&quot;..Settings.LabelName;	--путь к файлу метки<br />		--message(&quot;Init_ScriptPath &nbsp;&quot;..ScriptPath);		<br />	--label&#91;&quot;IMAGE_PATH&quot;&#93;=ScriptPath;<br />--номер предпоследней справа свечи на графике. Нумерация начинается с нуля.<br /> &nbsp; &nbsp;NmbrOfCandles = getNumCandles(Settings.AssetID)-2;<br />--получим таблицу с данными всех свечек, проиндексированную по номеру свечки<br />--t - таблица значений свечек<br />--n - количество полученных свечек(строк таблицы)<br />--l - подпись к инструменту<br />--текущую свечу не получаем<br />	t,n,l = getCandlesByIndex(Settings.AssetID,0,0,NmbrOfCandles);<br />--получить индекс двух свечек, номера которых заданы во входных параметрах<br />--и установить метки<br />	CandleIndex = NmbrOfCandles-Settings.splace;<br />	tposixOldLabelTime&#91;&quot;splace&quot;&#93;, Label_Id&#91;&quot;splace&quot;&#93; = PUTLABEL(CandleIndex);<br />		--message(&quot;Initsplace &nbsp;&quot;..tostring(tposixOldLabelTime&#91;&quot;splace&quot;&#93;));	<br />		--message(&quot;Initsplace &nbsp;&quot;..tostring(Label_Id&#91;&quot;splace&quot;&#93;));						<br /><br /><br />	CandleIndex = NmbrOfCandles-Settings.fplace;<br />	tposixOldLabelTime&#91;&quot;fplace&quot;&#93;, Label_Id&#91;&quot;fplace&quot;&#93; = PUTLABEL(CandleIndex);<br />		--message(&quot;Initfplace &nbsp;&quot;..tostring(tposixOldLabelTime&#91;&quot;fplace&quot;&#93;));	<br />		--message(&quot;Initfplace &nbsp;&quot;..tostring(Label_Id&#91;&quot;fplace&quot;&#93;));	<br />--берем из таблицы только время-дату свечи<br />	count = 0;<br />	for k=0,NmbrOfCandles-1 &nbsp;do<br />		count = count + 1; if count &gt; 100000 then break end;<br />--преобразуем в POSIX-формат поле datetime<br />--транспонируем таблицу - индексируем по времени		<br />		tDT&#91;k&#93; = os.time (t&#91;k&#93;.datetime);<br />		b=k;<br />		tposixByTime&#91;tDT&#91;b&#93;&#93; = b;<br />		--&#91;&#91;<br />		if NmbrOfCandles-Settings.splace==b then<br />			--message(&quot;Initsplace &nbsp;&quot;..tostring(tDT&#91;b&#93;)..&quot; &nbsp;&quot;..tostring(tposixByTime&#91;b&#93;))<br />		end;<br />		if NmbrOfCandles-Settings.fplace==b then<br />			--message(&quot;Initfplace &nbsp;&quot;..tostring(tDT&#91;b&#93;)..&quot; &nbsp;&quot;..tostring(tposixByTime&#91;b&#93;))<br />		end			<br />		--&#93;&#93;<br />	end<br /><br /><br />	return 1<br /><br /><br />end<br /><br /><br />function OnCalculate(index)<br /><br /><br />	local LblIdF = 0<br />	local LblIdS = 0	<br />	local posixNewLblTimeF = 0	<br />	local posixOldLblTimeF = 0<br />	local posixNewLblTimeS = 0	<br />	local posixOldLblTimeS = 0	<br />	local indput<br />	local IndLines={}<br />	local ChTrend<br />	local flagIndChange=false--false-перестроить индикатор, true - не перестраивать<br /><br /><br />---&#91;&#91;<br />--если флаг перемещения метки не установлен<br />	if flagLblModify==false then<br />--проверяем перемещалась ли первая метка	<br />		LblIdF=IsLabelChange(&quot;fplace&quot;);<br />--проверяем вторую метку		<br />		LblIdS=IsLabelChange(&quot;splace&quot;);<br />		--если индикатор существует, то выходим без расчетов, возвращаем массив линий<br />			if &nbsp;flagIndExist==true then<br />					flagIndChange=true;<br />			--иначе строим индикатор, выставляем его флаг, возвращаем массив линий		<br />				else <br />				flagIndChange=false;					<br />				flagIndExist=true;<br />			end<br />	--если метка перемещалась flagLblModify==true			<br />		else<br />		--строим индикатор, выставляем флаг индикатора, <br />		--сбрасываем флаг метки, возвращаем индикатор<br />			flagIndChange=false;<br />			flagIndExist=true;<br />			flagLblModify=false		<br />	end<br />	--рассчитываем индикатор или выводим линии без расчета<br />	--ChTrend=PUTINDICATOR(LblIdF,LblIdS,flagIndChange)<br />	--&#93;&#93;<br />	return ChTrend<br />end<br /><br /><br />function OnDestroy ()<br /><br /><br />	local tmp<br />	tmp=DelAllLabels(Settings.AssetID)<br />end<br /><br /><br />function IsLabelChange(place)<br />--функция принимает индекс массива Label_Id&#91;&quot;строка&quot;&#93;<br />--устанавливает глобальные флаги и <br />--записывает posix-время в глобальную таблицу tposixOldLabelTime<br />--возврашает Id метки<br />	local LblId = 0<br />	local posixNewLblTime = 0	<br />	local posixOldLblTime = 0<br /><br /><br />--проверяем перемещалась ли метка	<br />--считываем Id метки из массива	<br />		LblId = Label_Id&#91;place&#93;;<br />			message(tostring(LblId)..&quot; &nbsp;IsLabelChange_LblId&quot;)		<br />--считываем posix-время для этой метки<br />		posixOldLblTime = tposixOldLabelTime&#91;place&#93;;<br />			message(tostring(posixOldLblTime)..&quot; &nbsp;IsLabelChange_posixOldLblTime&quot;);<br />--преобразуем время метки с чарта в posix-формат<br />		posixNewLblTime = GETLABLEPOSIXTIME (LblId);<br />			message(tostring(posixNewLblTimeF)..&quot; &nbsp;IsLabelChange_posixNewLblTime&quot;)		<br />		---&#91;&#91;<br />		--если время не совпадает, выставляем флаги отсутствия индикатора и модификации метки<br />	if posixNewLblTime ~= nil then<br />		if	posixOldLblTime ~= posixNewLblTime &nbsp;then<br />		--выставляем флаги<br />			--метка перемещена<br />			flagLblModify=true;<br />			--индикатор не построен<br />			flagIndExist=false;<br />		--изменяем время метки в массиве<br />			tposixOldLabelTime&#91;place&#93; = posixNewLblTime;						<br />		--message(tostring(posixOldLblTime)..&quot; &nbsp;IsLabelChange_posixOldLblTime&quot;)<br />		--message(tostring(posixNewLblTimeF)..&quot; &nbsp;IsLabelChange_posixNewLblTime&quot;)		<br />		--message(&quot;IsLabelChange_LblId &nbsp; &quot;..tostring(LblId));<br />		end<br />	end<br />	return LblId<br />end <br /><br /><br /><br /><br />FTEXT = function (V)<br />--функция подставляет нули при их отсутствии на первой позиции даты-времени<br />	V=tostring (V)<br />	if string.len (V) == 1 then V = &quot;0&quot;.. V end<br />	return V <br />end	<br />	<br />PUTLABEL = function (index)<br />--&#91;&#91;функция для установки метки на чарт по индексу<br />	принимает индекс свечи <br />	возвращает время метки в posix-формате и Id метки<br />	<br />	входные параметры:<br />				-индекс свечи<br />				-строка с названием точки для индексации массива установленных меток<br />--&#93;&#93;<br />	local Date=&quot;&quot;--дата свечки<br />	local Time=&quot;&quot;--время свечки	<br />	local Yvalue=0<br />	LabelId=0<br />	--message (&quot;PUTLABELindex..&quot;..tostring(index));<br />--дата и время свечи<br />	Date=t&#91;index&#93;.datetime.year..FTEXT(t&#91;index&#93;.datetime.month)..FTEXT(t&#91;index&#93;.datetime.day); --дата<br /><br /><br />	Time=FTEXT(t&#91;index&#93;.datetime.hour)..FTEXT(t&#91;index&#93;.datetime.min)..FTEXT(t&#91;index&#93;.datetime.sec);<br /><br /><br />--привязка к оси У<br />	Yvalue = t&#91;index&#93;.high;<br />--заполнить структуру данных метки<br />		label={<br />			IMAGE_PATH=Settings.LabelName;<br />			YVALUE=Settings.Yvalue+Yvalue;<br />			DATE=Date,<br />	 &nbsp; &nbsp; &nbsp; &nbsp;TIME=Time			<br />			};<br />--добавляем метку на чарт и запоминаем Id метки в массиве, проиндексированном принятой строкой			<br />	LabelId = AddLabel(Settings.AssetID,label);<br />	--message (&quot;PUTLABELindex &nbsp;LabelId &nbsp;&quot;..tostring(LabelId))<br />	return os.time (t&#91;index&#93;.datetime), LabelId<br />end<br /><br /><br /><br /><br />function GETLABLEPOSIXTIME (LabelId)<br /><br /><br />--функция принимает Id метки и возвращает ее время в posix-формате<br />	local id--Id метки<br />	local NewLbLParam = {}--структура параметров метки<br />	local LabelTime = &quot;&quot;--строка с данными даты-времени метки<br />	local dt={}--структура в формате datetime<br />	local osTime=0<br />---&#91;&#91;	<br />	id = LabelId;<br />	--message(&quot;GETLABLEPOSIXTIME_LabelId &nbsp;&quot;..tostring(id));					<br />--получаем таблицу с параметрами метки (в нижнем регистре в формате строки)<br />	NewLbLParam = GetLabelParams(Settings.AssetID, id);<br />	--message(&quot;GETLABLEPOSIXTIME_LbLParam.date &nbsp;&quot;..tostring(NewLbLParam.date));<br />	--message(&quot;GETLABLEPOSIXTIME_LbLParam.time &nbsp;&quot;..tostring(NewLbLParam.time));	<br />--преобразуем в формат datetime<br />	dt.year,dt.month,dt.day = string.match(NewLbLParam.date,&quot;(%d%d%d%d)(%d%d)(%d%d)&quot;)<br />	if #NewLbLParam.time == 5 then <br />			LabelTime=&quot;0&quot;.. NewLbLParam.time <br />		else LabelTime=&quot;&quot;.. NewLbLParam.time<br />	end<br />	dt.hour,dt.min,dt.sec = string.match(LabelTime,&quot;(%d%d)(%d%d)(%d%d)&quot;)<br />--&#91;&#91;<br />message(&quot;GETLABLEPOSIXTIME_dt.year &nbsp;&quot;..tostring(dt.year));<br />message(&quot;GETLABLEPOSIXTIME_dt.month &nbsp;&quot;..tostring(dt.month));<br />message(&quot;GETLABLEPOSIXTIME_dt.day &nbsp;&quot;..tostring(dt.day));<br />message(&quot;GETLABLEPOSIXTIME_dt.hour &nbsp;&quot;..tostring(dt.hour));<br />message(&quot;GETLABLEPOSIXTIME_dt.min &nbsp;&quot;..tostring(dt.min));<br />message(&quot;GETLABLEPOSIXTIME_dt.sec &nbsp;&quot;..tostring(dt.sec));<br />message(&quot;GETLABLEPOSIXTIME_os.time &nbsp;&quot;..tostring(os.time (dt)));<br />	--&#93;&#93;<br />--преобразуем в формат POSIX<br />	osTime = os.time (dt);<br />	message(&quot;GETLABLEPOSIXTIME_os.time &nbsp;&quot;..tostring(osTime));<br />	return osTime;<br /><br /><br />end<br /><br /><br /><br /><br />function PUTINDICATOR(LblId1,LblId2,boolIndExist)<br /><br /><br />	local i<br />	local j<br />	local k<br />	local TrndH=0<br />	local TrndL=0	<br />	local h<br />	local l <br />	local CndlIdx1=0<br />	local CndlIdx2=0<br />	local ABIdx={}<br />	local IntervalCndlNmbr=0<br />	local koef<br />	local VChLines={}<br />	local VChTrend={}<br />	local VChUp={}<br />	local VChDn={}<br />	local VChUpMax<br />	local VChDnMin<br />	local posixLblTime1<br />	local posixLblTime2	<br />	local APointIdx<br />	local BPointIdx	<br />	local APointLvl<br />	local BPointLvl<br />	local idxUpMax<br />	local idxDnMin<br />	local AidxUp<br />	local AidxDn<br />	local BidxUp<br />	local BidxDn<br />	local VChTrnd=0<br /><br /><br /><br />	return VChTrnd<br /><br /><br />end</td></tr></tbody></table> <br />
			<i>12.02.2019 15:10:58, VNG_nemo.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message36310/topic4265/</link>
			<guid>http://forum.quik.ru/messages/forum10/message36310/topic4265/</guid>
			<pubDate>Tue, 12 Feb 2019 15:10:58 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
	</channel>
</rss>
