if, else

see codecademy.com

for

Warning: Unlike in Python, there is a = sign and no in keyword in between the iterator variable i and the range 1, 100!

for i = 1, 100 do  -- The range includes both ends.
  karlSum = karlSum + i
end

Functions

Optional Parameters, Default Parameters

see forum.defold.com

  • there is no mechanism in the language itself to indicate that a function parameter is optional, but there are plenty of examples in the Lua standard API where optional parameters exist and where the behaviour of a function depends on the number of arguments provided
  • A lot of Lua libraries use LDoc to write and automatically generate documentation, and optional arguments are documented like this:
--- Three dashes indicate the beginning of a function or field documented
-- using the LDoc format
-- @param var1 The first argument
-- @param[opt=6] var2 The second argument
-- @param[opt=0] var3 The third argument
-- @return Max The maximum value of var1 and var2
-- @return Min The minimum value of var2 and var3
function foobar(var1, var2, var3)
    var2 = var2 or 6
    var3 = var3 or 0
    return math.max(var1, var2), math.min(var2, var3)
end

Warning: This does not work with boolean default parameters, see reddit, eg. instead of

function foo(bar)
    local bar = bar or true
    ....
end

use

function foo(bar)
    if bar == nil then
        bar = true
    end
end

Warning: You can pass nil to skip parameters. However, most functions will not check each individual optional parameter, and only check each parameter if the previous one was provided., see stackoverflow

Run Lua Commands in Nvim

Check the value of a variable or a table:

:lua =vim.o.filetype

Troubleshooting

attempt to call a number value

in

for i in 1, nr_of_tabpages do
  options_table[tostring(i)] = tostring(i)
  option_names.insert(tostring(i))
end

fix: There must be an = sign instead of the in keyword in the for loop syntax.