Fix negative gvars precision (#6321)
[opentx.git] / doc / lua-reference-guide.tex
blob39caa030e727e5ee8bfb00df37bb0f0bb56c26d6
1 \documentclass[a4paper,french,10pt]{article}
3 \usepackage[utf8]{inputenc}
4 \usepackage[english]{babel}
5 \usepackage[T1]{fontenc}
6 \usepackage{geometry}
7 \usepackage{hyperref}
8 \usepackage{lmodern} % font Latin Modern, qui n'est pas une police Bitmap, donc tu auras de l'anti aliasing
9 \usepackage{tocloft}
10 \usepackage{booktabs}
11 \usepackage{longtable}
12 \usepackage{xcolor}
13 \usepackage{listings}
14 \usepackage{pifont,mdframed}
15 \usepackage{enumitem}
16 \usepackage[parfill]{parskip}
17 \usepackage{fancyhdr}
18 \usepackage{calc}
19 \usepackage{ifthen}
21 \setlength{\parskip}{\baselineskip}
24 \definecolor{luagray}{rgb}{0.96,0.96,0.96}
26 {\renewcommand{\arraystretch}{1.2} %<- modify value to suit your needs
27 %%%%%%%%%%%
28 % Defines the listings Lua style
29 %%%%%%%%%%%
30 \lstdefinestyle{myLuastyle}
32 language = {[5.0]Lua},
33 basicstyle = \ttfamily\footnotesize,
34 showstringspaces = false,
35 upquote = true,
36 frame = single,
37 captionpos = b,
38 breaklines =true,
39 backgroundcolor = \color{luagray},
42 %%%%%%%%%%
43 % Set the lua style as default listings style
44 %%%%%%%%%%
45 \lstset{style=myLuastyle}
47 %%%% On crée une figure Tikz qui permet de mettre le caractère passé en paramètre dans un rond (utilisé pour le symbole information
49 \newcommand\encircle[1]{%
50 \tikz[baseline=(X.base)]
51 \node (X) [draw, shape=circle, inner sep=0] {\strut #1};}
53 %%% Environnements
54 \newenvironment{warning}
55 {\par\begin{mdframed}[linewidth=2pt,linecolor=red]%
56 \begin{list}{}{\leftmargin=1cm
57 \labelwidth=\leftmargin}\item[\color{red}\Large\ding{53}]}
58 {\end{list}\end{mdframed}\par}
60 \newenvironment{info}
61 {\par\begin{mdframed}[linewidth=2pt,linecolor=blue]%
62 \begin{list}{}{\leftmargin=1cm
63 \labelwidth=\leftmargin}\item[\color{blue}\Large\ding{43}]}
64 {\end{list}\end{mdframed}\par}
69 \newenvironment{function}[1]
70 {\mdfsetup{
71 skipabove=\topsep,
72 skipbelow=\topsep,
73 innertopmargin=0pt,
74 innerbottommargin=4pt,
75 leftmargin=-13pt,
76 splitbottomskip=0ex,
77 splittopskip=0ex,
78 topline=false,
79 leftline=true,
80 bottomline=false,
81 rightline=false,
82 innerrightmargin=0pt,
83 innerlinewidth=2pt,
84 font=\normalfont,
85 frametitle={\textbf{local #1.}},
86 linecolor=black,
88 \begin{mdframed}%
90 {\end{mdframed}}
95 \geometry{top=2cm,bottom=2cm,left=2cm,right=1.5cm}
99 \pagestyle{fancy}
100 \renewcommand{\sectionmark}[1]{\markright{#1}}
101 \renewcommand{\footrulewidth}{1pt}
102 \fancyhf{}
103 \rhead{\fancyplain{}{Lua Scripting in OpenTx - Reference Guide }}
104 \lhead{\fancyplain{}{\rightmark }}
105 \rfoot{\fancyplain{}{\thepage}}
106 \lfoot{\fancyplain{}{Version 1.0}}
109 \title {
110 \vspace{60mm}
111 \Huge{\textsc{Lua Scripting in OpenTx\\}
112 \vspace{8mm}
113 \LARGE{\textsc{Reference Guide}}}
114 \vspace{45mm}
118 \author{OpenTx Team @ \url{http://www.open-tx.org/}}
120 \date{Version 1.0}
123 \begin{document}
125 \maketitle
126 \newpage
128 \tableofcontents
129 \newpage
131 \section{Introduction}
132 \paragraph{}
133 OpenTX 2.0 added support for Lua (current version 5.2.2) user scripts.
135 Lua is a lightweight multi-paradigm programming language designed as a scripting language\footnote{More at \href{http://www.wikipedia.org}{Wikipedia}}.
137 There are several types of Lua scripts used in openTX. More general information about Lua scripts can be found on page \url{http://www.open-tx.org/lua-instructions.html}
139 Lua scripts must be placed on SD card in correct folders and have an extension .lua. Maximum Lua script file name length is TODO characters. The script folders have been reorganized in OpenTX 2.0.3. The folder structure looks like this:
141 \begin{itemize}[leftmargin=*,itemsep=5mm,nolistsep]
142 \item[] \texttt{/SCRIPTS/WIZARD/} - For the Wizard script
143 \item[] \texttt{/SCRIPTS/MIXES/} - For model scripts
144 \item[] \texttt{/SCRIPTS/FUNCTIONS/} - For function scripts
145 \item[] \texttt{/SCRIPTS/<MODEL\_NAME>/telemXX.lua} - For telemetry scripts
146 \item[] \texttt{/SCRIPTS/TEMPLATES/} - For template scripts
147 \end{itemize}
149 \begin{figure}[h]
150 \begin{center}
151 \begin{longtable}{ll}
152 \toprule
153 \textbf{Lua Standard Libraries} & \textbf{Included} \\
154 \midrule
155 \endhead
156 \texttt{package} & no \\
157 \texttt{coroutine} & no \\
158 \texttt{table} & no \\
159 \texttt{io} & no \\
160 \texttt{os} & no \\
161 \texttt{string} & no \\
162 \texttt{bit} & future 2.1.0? \\
163 \texttt{math} & available from 2.0.0\\
164 \texttt{debug} & no \\
165 \bottomrule
166 \end{longtable}
167 \caption{Packaged libraries}
168 \end{center}
169 \end{figure}
170 \newpage
172 \section{Model Scripts}
174 \begin{warning}
175 Do not use Lua model scripts for controlling any aspect of your model that could cause a crash if script stops executing.
176 \end{warning}
178 \subsection{General description}
179 \paragraph{}
180 Each model can have several model scripts associated with it. These scripts are run periodically for entire time that model is selected/active. These scripts behave similar to standard OpenTX mixers but at the same time provide much more flexible and powerful tool.
183 Typically model scripts take several values as inputs, do some calculation or logic processing based on them and output one or more values. Each run of scripts should be as short as possible. Exceeding certain script execution runtime will result in script being forcefully stopped and disabled.
185 See also :
186 \begin{itemize}[leftmargin=*,itemsep=5mm,nolistsep]
187 \item[-] Lua \href{dunno}{One-time Scripts} - one-time running general scripts
188 \item[-] Lua \href{dunno}{Function Scripts}
189 \item[-] Lua \href{dunno}{Telemetry Scripts}
190 \item[-] Lua \href{dunno}{Script Reference} - detailed reference of OpenTX Lua implementation and interface
191 \item[-] Lua \href{dunno}{Script Examples} - some example scripts with comments
192 \end{itemize}
194 \subsubsection*{Examples of typical use of model scripts}
196 \begin{itemize}[leftmargin=*, itemsep=5mm,nolistsep]
197 \item[-] replacement for complex mixes that are \textbf{not critical to model function}
198 \item[-] complex processing of inputs and reaction to their current state and/or their history
199 \item[-] filtering of telemetry values
200 \item[-] automatic detection of number of battery cells and setting of low battery threshold
201 \item[-] automatic announcing of maximum altitude for each DLG throw
202 \item[-] see also Lua \href{dunno}{Script Examples}
203 \end{itemize}
205 \subsection{Limitations of model scripts}
206 \begin{itemize}[leftmargin=*,itemsep=5mm,nolistsep]
207 \item[-] Should not display anything on LCD screen.
208 \item[-] Can't wait for user input via dialog.
209 \item[-] Should not exceed maximum allowed runtime/ number of instructions.
210 \item[-] Standard OpenTX mixes are run every XX milliseconds in a very deterministic way (guaranteed execution) while model scripts are run from another thread with less priority. Their execution period is around 30ms and is not guaranteed!
211 \item[-] A script could be disabled/killed anytime due to several causes like (error in script, not enough free memory, etc...)
212 \end{itemize}
214 \subsection{Anatomy of model script}
215 \subsubsection{Location of model script}
216 \paragraph{}
217 Place them on SD card in folder \texttt{SCRIPTS/MIXES}
218 \subsubsection{Lifetime of model script}
219 \paragraph{}
220 \begin{itemize}[leftmargin=*,itemsep=5mm,nolistsep]
221 \item[-] script is loaded from SD card when model is selected
222 \item[-] script \textbf{init} function is called
223 \item[-] script \textbf{run} function is periodically called (inside GUI thread, period cca 30ms)
224 \item[-] script is stopped and disabled if it misbehaves (too long runtime, error in code, low memory)
225 \item[-] all model scripts are stopped while one-time script is running (see \href{dunno}{Lua One-time scripts})
226 \end{itemize}
228 \subsubsection{Script interface definitionn}
229 \paragraph{}
230 Every script must include a \textbf{return} statement at the end, that defines its interface to the rest of OpenTX code.
232 This statement defines:
233 \begin{itemize}[leftmargin=*,itemsep=5mm,nolistsep]
234 \item[-] script \textbf{inputs} (optional)
235 \item[-] script \textbf{outputs} (optional)
236 \item[-] script \textbf{init} function (optional)
237 \item[-] script \textbf{run} function
238 \end{itemize}
240 For example:
241 \begin{lstlisting}[caption={A dummy Lua script}]
242 -- script body would be here
244 return { input=inputs, output=outputs, run=run_func, init=init_func }
245 \end{lstlisting}
247 This example defines :
249 \begin{itemize}[leftmargin=*,itemsep=5mm,nolistsep]
250 \item[-] \texttt{inputs} table (array) as \textbf{input} values to model script
251 \item[-] \texttt{outputs} table as \textbf{output} of model script
252 \item[-] \texttt{run\_func()} as \textbf{periodic execution function} that takes inputs as parameters and returns outputs table
253 \item[-] \texttt{init\_func()} as function that is \textbf{called one time} when script is loaded and begins execution.
254 \end{itemize}
255 \paragraph{}
256 \begin{info}
257 Parameters \textbf{init}, \textbf{input} and \textbf{output} are optional. \\ If model script doesn't use them, they can be omitted from return statement.
258 \end{info}
260 \begin{lstlisting}[caption={Example without init and output}]
261 local inputs = { { "Aileron", SOURCE }, { "Ail. ratio", VALUE, -100, 100, 0 } }
263 local function run_func(ail, ratio)
264 -- do some stuff
265 if (ail > 50) and ( ratio < 40) then
266 playFile("foo.wav")
270 -- script that only uses input and run
271 return { run=run_func, input=inputs }
272 \end{lstlisting}
274 \newpage
276 \subsubsection{Script interface definition}
277 \paragraph{}
278 If defined, \textbf{init} function is called right after the script is loaded from SD card and begins execution. Init is called \textbf{only once} before the run function is called for the first time.
280 \begin{longtable}{p{3cm}p{3cm}p{\dimexpr\columnwidth-6cm-6\tabcolsep\relax}}
281 \toprule
282 \textbf{Prototype} & \multicolumn{2}{l} {\texttt{local <init\_function\_name>()}} \\
283 \midrule
284 \textbf{Parameters} & none & \\
285 \midrule
286 \textbf{Returns} & none & \\
287 \bottomrule
288 \end{longtable}
290 \subsubsection{Script execution}
291 \paragraph{}
292 The \textbf{run} function is the function that is periodically called for the entire lifetime of script. Syntax of run function is different between model scripts and one-time scripts.
294 \begin{longtable}{p{3cm}p{3cm}p{\dimexpr\columnwidth-6cm-6\tabcolsep\relax}}
295 \toprule
296 \textbf{Prototype} & \multicolumn{2}{l} {\texttt{local <run\_function\_name>([first input, [second input], ...])}} \\
297 \midrule
298 \textbf{Parameters} & <> & zero or more input values, their names are arbitrary, their meaning and order is defined by the input table \\
299 \midrule
300 \textbf{Returns} & none & if output table is empty (i.e. script has no output) \\
301 & values & (comma separated list of values) list of output values, their order and meaning is defined by the output table \\
302 \bottomrule
303 \end{longtable}
305 \subsubsection{Macro Test}
307 \newcounter{parameters}
308 \newcounter{returns}
310 \newenvironment{funcdef}[0]
311 {\setcounter{parameters}{0}\setcounter{returns}{0}
312 \newcommand{\prototype}[1]{\textbf{Prototype} & \multicolumn{2}{l} {\texttt{##1}}}
313 \newcommand{\parameter}[2]{\ifthenelse{\value{parameters}=0}{\\\midrule\textbf{Parameters}}{\\}\stepcounter{parameters}& \texttt{##1} & ##2}
314 \newcommand{\return}[2]{\ifthenelse{\value{returns}=0}{\\\midrule\textbf{Returns}}{\\}\stepcounter{returns}& ##1 & ##2}
315 \begin{longtable}{p{3cm}p{3cm}p{\dimexpr\columnwidth-6cm-6\tabcolsep\relax}}
316 \toprule}
317 {\\\bottomrule
318 \end{longtable}}
320 \begin{funcdef}
321 \prototype{local <run\_function\_name>([first input, [second input], ...])}
322 \parameter{<>}{zero or more input values, their names are arbitrary, their meaning and order is defined by the input table}
323 \parameter{none}{test}
324 \parameter{none}{test}
325 \return{none}{[text...]}
326 \return{none}{[text...]}
327 \return{none}{[text...]}
328 \return{none}
329 \end{funcdef}
331 \begin{funcdef}
332 \prototype{playNumber(number, unit, att)}
333 \parameter{number}{(integer)}
334 \parameter{unit}{(integer)}
335 \parameter{att}{(integer)}
336 \return{nil}
337 \end{funcdef}
339 \end{document}