CHDK Wiki
m (→‎Strings: can use single quotes too)
Tags: Visual edit Visual edit: Check apiedit
 
(24 intermediate revisions by 9 users not shown)
Line 1: Line 1:
=CHDK scripting with LUA=
+
=CHDK scripting with Lua=
 
{| align="right" style="border-collapse:collapse; font-size: x-small;"
 
{| align="right" style="border-collapse:collapse; font-size: x-small;"
 
| __TOC__
 
| __TOC__
 
|}
 
|}
''The latest CHDK builds includes [[LUA]] as additional scripting language, this page is intended to give a overview of the syntax of LUA usage in CHDK scripts.''
+
''Since 2008, CHDK builds have included [[Lua]] 5.1 as an additional scripting language. This page provides an overview of the Lua syntax usable in CHDK scripts. The [http://www.lua.org/manual/5.1/ Lua reference manual] provides a complete description of the language.''
==LUA Syntax short manual==
+
==Lua Syntax short manual==
 
===Some Basics...===
 
===Some Basics...===
 
*Lua is a case-sensitive language
 
*Lua is a case-sensitive language
*Lua is dynamically typed, variables in LUA do not have types, there are no type definitions for variables in LUA.
+
*Lua is dynamically typed. Variables in Lua do not have types, and there are no type definitions for variables in Lua. However, variable can hold eight different kinds of values : number, string, boolean, table, function, nil, userdata, thread.
   
 
===Keywords===
 
===Keywords===
Line 16: Line 16:
 
</pre>
 
</pre>
   
  +
In addition to the keywords above, many core language features are provided by the [http://www.lua.org/manual/5.1/manual.html#5.1 Lua basic library]. Some useful basic functions are:
'''Special CHDK keywords:'''
 
 
<pre>
 
<pre>
  +
error ipairs pairs print require
click press release shoot sleep require
 
  +
tonumber tostring type
 
</pre>
 
</pre>
  +
  +
CHDK also includes slightly modified versions of the [[Lua/Lua_Reference#Lua_standard_libraries|Lua standard libraries]].
  +
 
'''CHDK functions:'''
  +
CHDK specific functions provide access to CHDK functionality such as key presses and exposure control. The [[CHDK Scripting Cross Reference Page]] provides a comprehensive list of available functions.
   
 
===Comments===
 
===Comments===
Comments starts with a double hyphen '''--''' anywhere outside a string.
+
Comments start with a double hyphen "'''--"''' anywhere outside a string.
   
If the text immediately after '''--''' is not an opening square bracket '''[''' , the comment is a short comment, which runs until the end of the line. Otherwise, it is a long comment, which runs until the corresponding closing square bracket ''']''' . Long comments are frequently used to disable code temporarily.
+
If the text immediately after "'''--"''' is not two opening square brackets '''<nowiki>[[</nowiki>''' , the comment is a short comment, which runs until the end of the line. Otherwise, it is a long comment, which runs until there are two closing square brackets '''<nowiki>]]</nowiki>''' . Long comments are frequently used to disable code temporarily.
   
 
Sample:
 
Sample:
 
<source lang="lua">
 
<source lang="lua">
print("Hello CHDK !") -- this is a line with a comment at the end
+
print("Hello CHDK ! Variable n="..n) -- this is a line with a comment at the end
 
</source>
 
</source>
   
 
===Variables===
 
===Variables===
 
* Variables have to start with a character or an underscore
 
* Variables have to start with a character or an underscore
* Numeric Lua variables are 32 bit signed integer (-2147483648 to +2147483647)
+
* Numeric Lua variables in CHDK are 32 bit signed integers (-2147483648 to +2147483647). This differs from standard Lua, which normally uses floating point numbers.
 
* Variables used in the script header must be lower latin letters from '''a''' to '''z'''
 
* Variables used in the script header must be lower latin letters from '''a''' to '''z'''
* Before the first assignment to a variable, its value is <tt>nil</tt>.
+
* Before the first assignment to a variable, its value is <tt>nil</tt>.
   
There are three kinds of variables in Lua: '''global''' variables, '''local''' variables, and '''table fields'''.
+
There are three scopes for variables in Lua: '''global''' variables, '''local''' variables, and '''table fields'''.
 
*Any variable is assumed to be '''global''' unless explicitly declared as a local.
 
*Any variable is assumed to be '''global''' unless explicitly declared as a local.
 
*'''Global''' variables are visible from any place
 
*'''Global''' variables are visible from any place
*'''Local''' variables are ony visible from inside their scope: the scope of this variables begins at the first statement after their declaration and lasts until the end of the innermost block that includes the declaration. They can be declared anywhere inside a block and start with the initial assignment <tt> local</tt>
+
*'''Local''' variables are only visible from inside their scope: the scope of this variables begins at the first statement after their declaration and lasts until the end of the innermost block that includes the declaration. They can be declared anywhere inside a block and start with the initial assignment <tt> local</tt>
   
 
===Strings===
 
===Strings===
* Strings are delimited by single quotation marks ''' ' ' ''', double quotation marks '''" "''' or square brackets '''[[ ]]''' . Only the bracket form may cover multiple lines.
+
* Strings are delimited by single quotation marks ''' ' ' ''', double quotation marks '''" "''' or square brackets '''[[ ]]''' . Only the bracket form may cover multiple lines.
* Strings can be concatenated by two dots '''..'''
+
* Strings can be concatenated by two dots '''..'''
 
* They can contain most of the C-like escape sequences like <tt>'\f'</tt> (form feed), <tt>'\r'</tt> (carriage return) or <tt>'\t'</tt> (horizontal tab).
 
* They can contain most of the C-like escape sequences like <tt>'\f'</tt> (form feed), <tt>'\r'</tt> (carriage return) or <tt>'\t'</tt> (horizontal tab).
 
* Strings in Lua can contain any 8-bit value, including embedded zeros, which can be specified as <tt>'\0'</tt>
 
* Strings in Lua can contain any 8-bit value, including embedded zeros, which can be specified as <tt>'\0'</tt>
  +
  +
===Control Structures===
  +
Lua has many of the same control structures as other languages, providing ''if'' for conditional and ''while'', ''repeat'', and ''for'' for iteration.
  +
  +
Note that these structures test for boolean values - ''true'' or ''false''. Unlike C and other languages, a numberic value will test as ''true'' even if it's zero.  Also, a variable with no assigned value ( ''nil'' ) will test as ''false''.
   
 
===Tables===
 
===Tables===
*tables are enclosed in curly brackets <tt>{ }</tt>
+
*Tables are enclosed in curly brackets <tt>{ };</tt>
*they can contain values of all types (except nil), also other tables
+
*They can contain values of all types (except nil), including other tables;
 
*To iterate over the elements contained in an array the operators <tt>ipairs()</tt> or <tt>pairs()</tt> can be used:
 
*To iterate over the elements contained in an array the operators <tt>ipairs()</tt> or <tt>pairs()</tt> can be used:
::<tt>ipairs()</tt> iterates only over the indices in a table (only outputs the numerically indexed content)
+
::<tt>ipairs()</tt> iterates only over the indices in a table (only outputs the numerically indexed content);
::<tt>pairs() </tt> iterates over the keys in a table
+
::<tt>pairs() </tt> iterates over the keys in a table.
   
 
<u>Tables as arrays:</u>
 
<u>Tables as arrays:</u>
Line 81: Line 92:
 
Both (tables as arrays and dictionaries) can be used together, you are not restricted to using table constructors as just sequentially indexed lists, or as dictionaries, you can mix the two together.
 
Both (tables as arrays and dictionaries) can be used together, you are not restricted to using table constructors as just sequentially indexed lists, or as dictionaries, you can mix the two together.
   
'''''More informations and samples about tables can be found here:''''' http://lua-users.org/wiki/TablesTutorial
+
'''''More information and examples using tables can be found here:''''' http://lua-users.org/wiki/TablesTutorial
   
 
===Libraries===
 
===Libraries===
Libraries are standard LUA scripts placed either in {{scaps|chdk\scripts}} or {{scaps|chdk\lualib}} , called within a script with
+
Libraries are standard Lua scripts placed either in {{scaps|chdk\scripts}} or {{scaps|chdk\lualib}} , called within a script with
 
<pre>
 
<pre>
 
require "libname"
 
require "libname"
Line 97: Line 108:
   
 
===The script header===
 
===The script header===
The header of a LUA script is the same as on a uBASIC script, packed into a long comment - the script parser interpretes this the same way in LUA as in uBASIC.
+
The header of a Lua script is the same as on a uBASIC script, packed into a long comment - the script parser interprets this the same way in Lua as in uBASIC. See also : [[CHDK Script Header]]
   
A Sample LUA header:
+
A Sample Lua header:
   
 
<source lang="lua">
 
<source lang="lua">
Line 111: Line 122:
 
@param h Endless?
 
@param h Endless?
 
@default h 0
 
@default h 0
--]]
+
]]
 
</source>
 
</source>
   
 
===Script Commands===
 
===Script Commands===
All uBASIC script commands are also available in LUA, almost with the same syntax.
+
Most uBASIC script commands are also available in Lua, almost with the same syntax.
  +
  +
{{tagb|→}} See the '''[[CHDK_Scripting_Cross_Reference_Page|Scripting Cross Reference Page]]''' for the complete list of CHDK scripting commands for Lua and uBASIC.
   
 
See the [[uBASIC/TutorialScratchpad|Scripting Tutorial]] for a more complete explanation and for the usage of all commands.
 
See the [[uBASIC/TutorialScratchpad|Scripting Tutorial]] for a more complete explanation and for the usage of all commands.
Line 121: Line 134:
 
If an execution/parse error occurs a message with a short explanation and the line number is shown in the mini console.
 
If an execution/parse error occurs a message with a short explanation and the line number is shown in the mini console.
   
New and/or changed commands are listed in [[LUA/LUA Reference|'''LUA Reference''']].
+
New and/or changed commands are listed in [[Lua/Lua Reference|'''Lua Reference''']].
   
  +
...
[[Category:LUA|Syntax]]
+
[[Category:Lua]]
  +
[[Category:Development]]

Latest revision as of 17:09, 7 November 2015

CHDK scripting with Lua

Since 2008, CHDK builds have included Lua 5.1 as an additional scripting language. This page provides an overview of the Lua syntax usable in CHDK scripts. The Lua reference manual provides a complete description of the language.

Lua Syntax short manual

Some Basics...

  • Lua is a case-sensitive language
  • Lua is dynamically typed. Variables in Lua do not have types, and there are no type definitions for variables in Lua. However, variable can hold eight different kinds of values : number, string, boolean, table, function, nil, userdata, thread.

Keywords

and		break		do		else		elseif		end		false		for
function	if		in		local		nil		not		or		repeat
return		then		true		until		while

In addition to the keywords above, many core language features are provided by the Lua basic library. Some useful basic functions are:

error           ipairs          pairs           print           require
tonumber        tostring        type

CHDK also includes slightly modified versions of the Lua standard libraries.

CHDK functions: CHDK specific functions provide access to CHDK functionality such as key presses and exposure control. The CHDK Scripting Cross Reference Page provides a comprehensive list of available functions.

Comments

Comments start with a double hyphen "--" anywhere outside a string.

If the text immediately after "--" is not two opening square brackets [[ , the comment is a short comment, which runs until the end of the line. Otherwise, it is a long comment, which runs until there are two closing square brackets ]] . Long comments are frequently used to disable code temporarily.

Sample:

print("Hello CHDK ! Variable n="..n) -- this is a line with a comment at the end

Variables

  • Variables have to start with a character or an underscore
  • Numeric Lua variables in CHDK are 32 bit signed integers (-2147483648 to +2147483647). This differs from standard Lua, which normally uses floating point numbers.
  • Variables used in the script header must be lower latin letters from a to z
  • Before the first assignment to a variable, its value is nil.

There are three scopes for variables in Lua: global variables, local variables, and table fields.

  • Any variable is assumed to be global unless explicitly declared as a local.
  • Global variables are visible from any place
  • Local variables are only visible from inside their scope: the scope of this variables begins at the first statement after their declaration and lasts until the end of the innermost block that includes the declaration. They can be declared anywhere inside a block and start with the initial assignment local

Strings

  • Strings are delimited by single quotation marks ' ' , double quotation marks " " or square brackets [[ ]] . Only the bracket form may cover multiple lines.
  • Strings can be concatenated by two dots ..
  • They can contain most of the C-like escape sequences like '\f' (form feed), '\r' (carriage return) or '\t' (horizontal tab).
  • Strings in Lua can contain any 8-bit value, including embedded zeros, which can be specified as '\0'

Control Structures

Lua has many of the same control structures as other languages, providing if for conditional and whilerepeat, and for for iteration.

Note that these structures test for boolean values - true or false. Unlike C and other languages, a numberic value will test as true even if it's zero.  Also, a variable with no assigned value ( nil ) will test as false.

Tables

  • Tables are enclosed in curly brackets { };
  • They can contain values of all types (except nil), including other tables;
  • To iterate over the elements contained in an array the operators ipairs() or pairs() can be used:
ipairs() iterates only over the indices in a table (only outputs the numerically indexed content);
pairs() iterates over the keys in a table.

Tables as arrays:

Tables can be used to hold arrays of information. Table constructors can contain a comma separated list of objects to create an array. The array elements can be accessed using square brackets, table[index].
t = { 1,1,2,3,5,8,13 }
  print( t[1] )        -- returns:  1
  print( t[0] )        -- returns:  nil
  print( t[4] )        -- returns:  3
Notice that the indexing into the array starts at 1, not at zero. t[0] has the value nil, i.e. there is no element at position 0.

Tables as dictionaries

Tables can also be used to store information which is not indexed numerically, or sequentially, as with arrays.
In such a dictionary element pair has a key and a value, the key is used to set and retrieve a value associated with it.
A key need not be a number, it can be a string or nearly any other Lua object (except for nil).
t = { apple="green", orange="orange", banana="yellow" }
  for k,v in pairs(t) do print(k,v) end
returns:  apple   green
          orange  orange
          banana  yellow
Note that there's no guarantee as to the order in which keys will be stored in a table when using dictionaries so the order of retrieval of keys using pairs() is not guaranteed.

Both (tables as arrays and dictionaries) can be used together, you are not restricted to using table constructors as just sequentially indexed lists, or as dictionaries, you can mix the two together.

More information and examples using tables can be found here: http://lua-users.org/wiki/TablesTutorial

Libraries

Libraries are standard Lua scripts placed either in chdk\scripts or chdk\lualib , called within a script with

require "libname"

where libname is the filename of the library file without '.lua' suffix.

This means one can create a library of functions and recycle this lib in scripts with a call to require "libname".

Library files were first searched from chdk\scripts , and then if not found, from chdk\lualib ; if a file with the required name is available in both folders, the one from the first folder (chdk\scripts) is used.

There is also a special folder chdk\lualib\gen for generic Lua libraries, sometimes created during the build process and delivered with the CHDK 'complete' download packages.

The script header

The header of a Lua script is the same as on a uBASIC script, packed into a long comment - the script parser interprets this the same way in Lua as in uBASIC. See also : CHDK Script Header

A Sample Lua header:

--[[
rem 20080815 test script by xxx
@title test script
@param a Duration (min)/-1 disable
@default a -1
@param b Duration (sec)/n of seqs
@default b 5
@param h Endless?
@default h 0
]]

Script Commands

Most uBASIC script commands are also available in Lua, almost with the same syntax.

See the Scripting Cross Reference Page for the complete list of CHDK scripting commands for Lua and uBASIC.

See the Scripting Tutorial for a more complete explanation and for the usage of all commands.

If an execution/parse error occurs a message with a short explanation and the line number is shown in the mini console.

New and/or changed commands are listed in Lua Reference.

...