- String to number:
tonumber()
- Book: Programming in Lua - Roberto Ierusalimschy
Chained assignment
This doesn't seem to be possible in lua.
Closest we can get is:
> a,b = 2
> print(a,b)
2 nil
Another attempt gave error:
> a = b = 2
:1: unexpected symbol near '=' stdin
Repeat a string
> print(string.rep('a', 2))
aa> print(string.rep('a', 4/2))
aa
Length of a string
Use #
.
> print(#"hello")
5
> a = "hi"
> print(#a)
2
Global variables
No need to declare them separately.
They are sort of always there, unless they are nil
.
Tables
The only built-in data structure available in lua.
Quite flexible though. Tables could be termed the 'heart' of lua.
- Insert new element: table.insert(<table-var>, <elem/key>)
- Delete element: table.remove(<table-var>, <elem/key>)
- Get element: table.getn(<table-var>, <elem/key>) or <table-var>["<elem/key>"] or <table-var>.<elem/key>
- Iterate over elements: pairs(<table-var>)
Note: {}
and nil
are not equivalent.
> t = {a=1}
> print(t['a'])
Can be used as a list/dictionary.
-- dictionary style
= {a=1, b=2}
t
-- list style
= {1, 2} t
Indexing starts from 1
> a={0,1,2,3}
> for i,x in pairs(a) do
> print(i)
> end
1
2
3
4
'Joining' elements of a table
> a = {"a", "b"}
> print(table.concat(a,'\n'))
a
b> print(table.concat(a,''))
ab
Elements needn't be strings. It will be converted to string, apparently.
> print(table.concat({"a", 3}, ''))
a3> print(table.concat({"a", 3, 1.2}, ''))
.2 a31
Operators
equal to | == |
not equal to | ~= |
string concatenation | .. |
if
statement
if <condition> then
<branch 1>
elseif <condition> then
<branch 2>
else
<branch 3>
end
Functions
-- Function taking no args
function noarg_fn()
<body>
end
-- Function taking args
function with_args(a,b)
<body>
end
Anonymous function
> a = function () print(3) end
> a()
3
Integer division
lua >= 5.3 has the //
operator, but we can use math.floor
for older versions.
-- lua 5.2
> print(3/2)
1.5
> print(math.floor(3/2))
1
Reference: https://stackoverflow.com/questions/9654496/lua-converting-from-float-to-int
String manipulation
Reference: http://math2.org/luasearch/string.html
Indexing starts from 1.
> a = "0123456789"
> print(a:sub(#a-3))
6789
> print(a:sub(1, #a-3)
0123456
> print(string.sub(a,1, #a-3))
0123456
- Delete last character in a string:
string.sub(a,1, #a-1)
Linters
https://github.com/lunarmodules/luacheck
General
os.getenv "ROOTDIR" or "out"
: results in value of shell variable$ROOTDIR
or the string"out"
os.date("!%Y-%m-%d %T")
: get current datestring.format()
: like python'sstr.format()
math.sqrt(4)
Chunk: a sequence of statements
- Could be an entire file.
- Could be a single line in an interactive session.
Launch repl with
lua
commandEmacs mode: https://github.com/immerrr/lua-mode
Importing libraries
- Libraries are like tables.
require
them and bind it to a variable- Table attributes are the definitions provided by the library
local filter = require "make4ht-filter"
Package management
- luarocks: Like pip for python