Lua


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
stdin:1: unexpected symbol near '='

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.

Note: {} and nil are not equivalent.

> t = {a=1}
> print(t['a'])

Can be used as a list/dictionary.

-- dictionary style
t = {a=1, b=2}

-- list style
t = {1, 2}

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}, ''))
a31.2

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

Linters

https://github.com/lunarmodules/luacheck

Package management