local x = 10 -- numberlocal name = "sid" -- stringlocal isAlive = true -- booleanlocal a = nil -- no value or invalid value-- increment in numberslocal n = 1n = n + 1print(n) -- 2-- strings-- Concatenate stringslocal phrase = "I am"local name = "Sid"print(phrase .. " " .. name) -- I am Sidprint("I am " .. "Sid")
-- Number comparisonslocal age = 10if age > 18 then print("over 18") -- this will not be executedend-- elseif and elseage = 20if age > 18 then print("over 18")elseif age == 18 then print("18 huh")else print("kiddo")end-- Boolean comparisonlocal isAlive = trueif isAlive then print("Be grateful!")end-- String comparisonslocal name = "sid"if name ~= "sid" then print("not sid")end
local age = 22if age == 10 and x > 0 then -- both should be true print("kiddo!")elseif x == 18 or x > 18 then -- 1 or more are true print("over 18")end-- result: over 18
local function print_num(a) print(a)end-- orlocal print_num = function(a) print(a)endprint_num(5) -- prints 5 -- multiple parametersfunction sum(a, b) return a + bend
local colors = { "red", "green", "blue" }print(colors[1]) -- red-- Different ways to loop through lists-- #colors is the length of the table, #tablename is the syntaxfor i = 1, #colors do print(colors[i])end-- ipairs for index, value in ipairs(colors) do print(colors[index]) -- or print(value)end-- If you don't use index or value here then you can replace it with _ for _, value in ipairs(colors) do print(value)end
local info = { name = "sid", age = 20, isAlive = true}-- both print sidprint(info["name"])print(info.name)-- Loop by pairsfor key, value in pairs(info) do print(key .. " " .. tostring(value))end-- prints name sid, age 20 etc
require("path")-- for example in ~/.config/nvim/lua , all dirs and files are accessible via require-- Do note that all files in that lua folder are in path!-- ~/.config/nvim/lua/abc.lua -- ~/.config/nvim/lua/abc/init.luarequire "abc"
This is a Neovim function which is used for merging tables and their values recursively. Most plugins use it for merging config tables.
Copy
-- table 1local person = { name = "joe", age = 19, skills = {"python", "html"},}-- table 2local someone = { name = "siduck", skills = {"js", "lua"},}-- "force" will overwrite equal values from the someone table over the person tablelocal result = vim.tbl_deep_extend("force", person, someone)-- result : { name = "siduck", age = 19, skills = {"js", "lua"},}-- The list tables won't merge because they don't have keys check :h vim.tbl_deep_extend for more info